Exemple #1
0
        public async Task <IActionResult> ClearAccount()
        {
            if (OAuthController.GetAppSetting("DISABLE_SETUP") == "true")
            {
                return(Unauthorized());
            }

            // clear account
            await _designAutomation.DeleteForgeAppAsync("me");

            return(Ok());
        }
Exemple #2
0
        public async Task <IActionResult> UploadOssFiles([FromBody] JObject appBundleSpecs)
        {
            if (OAuthController.GetAppSetting("DISABLE_SETUP") == "true")
            {
                return(Unauthorized());
            }

            System.Diagnostics.Debug.WriteLine("UploadOssFiles");
            // OAuth token
            dynamic oauth = await OAuthController.GetInternalAsync();

            ObjectsApi objects = new ObjectsApi();

            objects.Configuration.AccessToken = oauth.access_token;

            DerivativesApi derivatives = new DerivativesApi();

            derivatives.Configuration.AccessToken = oauth.access_token;

            // upload file to OSS Bucket
            // 1. ensure bucket existis
            BucketsApi buckets = new BucketsApi();

            buckets.Configuration.AccessToken = oauth.access_token;
            try
            {
                PostBucketsPayload bucketPayload = new PostBucketsPayload(BucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient);
                await buckets.CreateBucketAsync(bucketPayload, "US");
            }
            catch { }; // in case bucket already exists

            string [] filePaths = System.IO.Directory.GetFiles(LocalFilesFolder);
            foreach (string filePath in filePaths)
            {
                string fileName = System.IO.Path.GetFileName(filePath);
                using (StreamReader streamReader = new StreamReader(filePath))
                {
                    dynamic res = await objects.UploadObjectAsync(BucketKey, fileName, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream");

                    TranslateFile(res.objectId, null);
                }
            }

            return(Ok());
        }
Exemple #3
0
        private async Task <string> CreateWorkItem(JObject input, Dictionary <string, string> headers, string browerConnectionId, string outputName, string fileName, string url)
        {
            input["output"] = outputName;
            XrefTreeArgument inputJsonArgument = new XrefTreeArgument()
            {
                Url = "data:application/json," + input.ToString(Formatting.None)
            };

            XrefTreeArgument outputArgument = new XrefTreeArgument()
            {
                Url     = url,
                Verb    = Verb.Put,
                Headers = headers
            };

            string callbackComplete = string.Format(
                "{0}/api/forge/callback/oncomplete?id={1}&outputFile={2}",
                OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"),
                browerConnectionId,
                fileName);

            WorkItem workItemSpec = new WorkItem()
            {
                ActivityId = QualifiedBundleActivityName,
                Arguments  = new Dictionary <string, IArgument>()
                {
                    { "inputJson", inputJsonArgument },
                    { outputName, outputArgument },
                    { "onComplete", new XrefTreeArgument {
                          Verb = Verb.Post, Url = callbackComplete
                      } }
                }
            };
            WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemAsync(workItemSpec);

            return(workItemStatus.Id);
        }
Exemple #4
0
        public static async Task <string> GetClientIdAsync()
        {
            string clientIdKey = await OAuthController.GetAppSetting("FORGE_CLIENT_ID");

            return(clientIdKey.ToLower());
        }
        public async Task <IActionResult> StartWorkitem([FromForm] StartWorkitemInput input)
        {
            // basic input validation
            JObject workItemData       = JObject.Parse(input.data);
            string  widthParam         = workItemData["width"].Value <string>();
            string  heigthParam        = workItemData["height"].Value <string>();
            string  activityName       = string.Format("{0}.{1}", NickName, workItemData["activityName"].Value <string>());
            string  browerConnectionId = workItemData["browerConnectionId"].Value <string>();

            // save the file on the server
            var fileSavePath = Path.Combine(_env.ContentRootPath, Path.GetFileName(input.inputFile.FileName));

            using (var stream = new FileStream(fileSavePath, FileMode.Create)) await input.inputFile.CopyToAsync(stream);

            // OAuth token
            dynamic oauth = await OAuthController.GetInternalAsync();

            // upload file to OSS Bucket
            // 1. ensure bucket existis
            string     bucketKey = NickName.ToLower() + "-designautomation";
            BucketsApi buckets   = new BucketsApi();

            buckets.Configuration.AccessToken = oauth.access_token;
            try
            {
                PostBucketsPayload bucketPayload = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient);
                await buckets.CreateBucketAsync(bucketPayload, "US");
            }
            catch { };                                                                                                                                         // in case bucket already exists
                                                                                                                                                               // 2. upload inputFile
            string     inputFileNameOSS = string.Format("{0}_input_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputFile.FileName)); // avoid overriding
            ObjectsApi objects          = new ObjectsApi();

            objects.Configuration.AccessToken = oauth.access_token;
            using (StreamReader streamReader = new StreamReader(fileSavePath))
                await objects.UploadObjectAsync(bucketKey, inputFileNameOSS, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream");
            System.IO.File.Delete(fileSavePath);// delete server copy

            // prepare workitem arguments
            // 1. input file
            XrefTreeArgument inputFileArgument = new XrefTreeArgument()
            {
                Url     = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, inputFileNameOSS),
                Headers = new Dictionary <string, string>()
                {
                    { "Authorization", "Bearer " + oauth.access_token }
                }
            };
            // 2. input json
            dynamic inputJson = new JObject();

            inputJson.Width  = widthParam;
            inputJson.Height = heigthParam;
            XrefTreeArgument inputJsonArgument = new XrefTreeArgument()
            {
                Url = "data:application/json, " + ((JObject)inputJson).ToString(Formatting.None).Replace("\"", "'")
            };
            // 3. output file
            string           outputFileNameOSS  = string.Format("{0}_output_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputFile.FileName)); // avoid overriding
            XrefTreeArgument outputFileArgument = new XrefTreeArgument()
            {
                Url     = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFileNameOSS),
                Verb    = Verb.Put,
                Headers = new Dictionary <string, string>()
                {
                    { "Authorization", "Bearer " + oauth.access_token }
                }
            };

            // prepare & submit workitem
            // the callback contains the connectionId (used to identify the client) and the outputFileName of this workitem
            string   callbackUrl  = string.Format("{0}/api/forge/callback/designautomation?id={1}&outputFileName={2}", OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"), browerConnectionId, outputFileNameOSS);
            WorkItem workItemSpec = new WorkItem()
            {
                ActivityId = activityName,
                Arguments  = new Dictionary <string, IArgument>()
                {
                    { "inputFile", inputFileArgument },
                    { "inputJson", inputJsonArgument },
                    { "outputFile", outputFileArgument },
                    { "onComplete", new XrefTreeArgument {
                          Verb = Verb.Post, Url = callbackUrl
                      } }
                }
            };
            WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemAsync(workItemSpec);

            return(Ok(new { WorkItemId = workItemStatus.Id }));
        }
Exemple #6
0
        public async Task <IActionResult> StartWorkitem([FromForm] StartWorkitemInput input)
        {
            // basic input validation
            JObject workItemData       = JObject.Parse(input.data);
            string  widthParam         = workItemData["width"].Value <string>();
            string  heigthParam        = workItemData["height"].Value <string>();
            string  activityName       = string.Format("{0}.{1}", NickName, workItemData["activityName"].Value <string>());
            string  browerConnectionId = workItemData["browerConnectionId"].Value <string>();

            // save the file on the server
            var fileSavePath = Path.Combine(_env.ContentRootPath, input.inputFile.FileName);

            using (var stream = new FileStream(fileSavePath, FileMode.Create)) await input.inputFile.CopyToAsync(stream);

            // OAuth token
            dynamic oauth = await OAuthController.GetInternalAsync();

            // upload file to OSS Bucket
            // 1. ensure bucket existis
            string     bucketKey = NickName.ToLower() + "_designautomation";
            BucketsApi buckets   = new BucketsApi();

            buckets.Configuration.AccessToken = oauth.access_token;
            try
            {
                PostBucketsPayload bucketPayload = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient);
                await buckets.CreateBucketAsync(bucketPayload, "US");
            }
            catch { };                                                                                                                       // in case bucket already exists
            // 2. upload inputFile
            string     inputFileNameOSS = string.Format("{0}_input_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), input.inputFile.FileName); // avoid overriding
            ObjectsApi objects          = new ObjectsApi();

            objects.Configuration.AccessToken = oauth.access_token;
            using (StreamReader streamReader = new StreamReader(fileSavePath))
                await objects.UploadObjectAsync(bucketKey, inputFileNameOSS, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream");
            System.IO.File.Delete(fileSavePath);// delete server copy

            // prepare workitem arguments
            // 1. input file
            JObject inputFileArgument = new JObject
            {
                new JProperty("url", string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, inputFileNameOSS)),
                new JProperty("headers",
                              new JObject {
                    new JProperty("Authorization", "Bearer " + oauth.access_token)
                })
            };
            // 2. input json
            dynamic inputJson = new JObject();

            inputJson.Width  = widthParam;
            inputJson.Height = heigthParam;
            JObject inputJsonArgument = new JObject {
                new JProperty("url", "data:application/json, " + ((JObject)inputJson).ToString(Formatting.None).Replace("\"", "'"))
            };                                                                                                                               // ToDo: need to improve this
            // 3. output file
            string  outputFileNameOSS  = string.Format("{0}_output_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), input.inputFile.FileName); // avoid overriding
            JObject outputFileArgument = new JObject
            {
                new JProperty("verb", "PUT"),
                new JProperty("url", string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFileNameOSS)),
                new JProperty("headers",
                              new JObject {
                    new JProperty("Authorization", "Bearer " + oauth.access_token)
                })
            };

            // prepare & submit workitem
            string   callbackUrl  = string.Format("{0}/api/forge/callback/designautomation?id={1}", OAuthController.GetAppSetting("FORGE_WEBHOOK_CALLBACK_HOST"), browerConnectionId);
            WorkItem workItemSpec = new WorkItem(
                null, activityName,
                new Dictionary <string, JObject>()
            {
                { "inputFile", inputFileArgument },
                { "inputJson", inputJsonArgument },
                { "outputFile", outputFileArgument },
                //{ "onProgress", new JObject { new JProperty("verb", "POST"), new JProperty("url", callbackUrl) }},
                { "onComplete", new JObject {
                      new JProperty("verb", "POST"), new JProperty("url", callbackUrl)
                  } }
            },
                null);
            WorkItemsApi workItemApi = new WorkItemsApi();

            workItemApi.Configuration.AccessToken = oauth.access_token;;
            WorkItemStatus newWorkItem = await workItemApi.WorkItemsCreateWorkItemsAsync(null, null, workItemSpec);

            return(Ok(new { WorkItemId = newWorkItem.Id }));
        }
        public async Task <dynamic> TranslateObject([FromBody] ObjectModel objModel)
        {
            dynamic oauth = await OAuthController.GetInternalAsync();

            // prepare the webhook callback
            DerivativeWebhooksApi webhook = new DerivativeWebhooksApi();

            webhook.Configuration.AccessToken = oauth.access_token;
            dynamic existingHooks = await webhook.GetHooksAsync(DerivativeWebhookEvent.ExtractionFinished);

            // get the callback from your settings (e.g. web.config)
            string callbackUlr = OAuthController.GetAppSetting("FORGE_WEBHOOK_URL") + "/api/forge/callback/modelderivative";

            bool createHook = true; // need to create, we don't know if our hook is already there...

            foreach (KeyValuePair <string, dynamic> hook in new DynamicDictionaryItems(existingHooks.data))
            {
                if (hook.Value.scope.workflow.Equals(objModel.connectionId))
                {
                    // ok, found one hook with the same workflow, no need to create...
                    createHook = false;
                    if (!hook.Value.callbackUrl.Equals(callbackUlr))
                    {
                        await webhook.DeleteHookAsync(DerivativeWebhookEvent.ExtractionFinished, new System.Guid(hook.Value.hookId));

                        createHook = true; // ops, the callback URL is outdated, so delete and prepare to create again
                    }
                }
            }

            // need to (re)create the hook?
            if (createHook)
            {
                await webhook.CreateHookAsync(DerivativeWebhookEvent.ExtractionFinished, callbackUlr, objModel.connectionId);
            }

            // prepare the payload
            List <JobPayloadItem> outputs = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._2d,
                    JobPayloadItem.ViewsEnum._3d
                })
            };
            JobPayload job;

            if (string.IsNullOrEmpty(objModel.rootFilename))
            {
                job = new JobPayload(new JobPayloadInput(objModel.objectName), new JobPayloadOutput(outputs), new JobPayloadMisc(objModel.connectionId));
            }
            else
            {
                job = new JobPayload(new JobPayloadInput(objModel.objectName, true, objModel.rootFilename), new JobPayloadOutput(outputs), new JobPayloadMisc(objModel.connectionId));
            }


            // start the translation
            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = oauth.access_token;
            dynamic jobPosted = await derivative.TranslateAsync(job, true /* force re-translate if already here, required data:write*/);

            return(jobPosted);
        }
Exemple #8
0
        public async Task <IActionResult> StartWorkitems([FromBody] JObject input)
        {
            System.Diagnostics.Debug.WriteLine("StartWorkitem");
            string browerConnectionId = input["browerConnectionId"].Value <string>();
            bool   useCache           = input["useCache"].Value <bool>();
            string pngWorkItemId      = "skipped";
            string jsonWorkItemId     = "skipped";
            string zipWorkItemId      = "skipped";

            // OAuth token
            dynamic oauth = await OAuthController.GetInternalAsync();

            string pngFileName = browerConnectionId + ".png";

            pngWorkItemId = await CreateWorkItem(
                input,
                new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } },
                browerConnectionId,
                "outputPng",
                pngFileName,
                string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", BucketKey, pngFileName)
                );

            if (useCache)
            {
                string    hash        = MD5Encode(input["params"] as JObject);
                string    zipFileName = hash + ".zip";
                double [] cells       = new double [] {
                    1, 0, 0, 0,
                    0, 1, 0, 0,
                    0, 0, 1, 0,
                    0, 0, 0, 1
                };
                if (await IsInCache(zipFileName))
                {
                    JObject data = new JObject(
                        new JProperty("components",
                                      new JArray(
                                          new JObject(
                                              new JProperty("fileName", zipFileName),
                                              new JProperty("cells", cells)
                                              )
                                          )
                                      )
                        );
                    await SendComponentsDataToClient(browerConnectionId, data);

                    return(Ok(new {
                        PngWorkItemId = pngWorkItemId,
                        JsonWorkItemId = jsonWorkItemId,
                        ZipWorkItemId = zipWorkItemId
                    }));
                }
                else
                {
                    zipWorkItemId = await CreateWorkItem(
                        input,
                        new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } },
                        browerConnectionId,
                        "outputZip",
                        zipFileName,
                        string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", BucketKey, zipFileName)
                        );
                }
            }

            string jsonFileName = browerConnectionId + ".json";

            jsonWorkItemId = await CreateWorkItem(
                input,
                new Dictionary <string, string>() { { "Content-Type", "application/json" } },
                browerConnectionId,
                "outputJson",
                jsonFileName,
                string.Format("{0}/api/forge/callback/ondata/json?id={1}", OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"), browerConnectionId)
                );

            return(Ok(new {
                PngWorkItemId = pngWorkItemId,
                JsonWorkItemId = jsonWorkItemId,
                ZipWorkItemId = zipWorkItemId
            }));
        }
Exemple #9
0
        public async Task <IActionResult> CreateActivity([FromBody] JObject activitySpecs)
        {
            if (OAuthController.GetAppSetting("DISABLE_SETUP") == "true")
            {
                return(Unauthorized());
            }

            System.Diagnostics.Debug.WriteLine("CreateActivity");
            Page <string> activities = await _designAutomation.GetActivitiesAsync();

            if (!activities.Data.Contains(QualifiedBundleActivityName))
            {
                string   commandLine  = CommandLine();
                Activity activitySpec = new Activity()
                {
                    Id         = kBundleActivityName,
                    Appbundles = new List <string>()
                    {
                        QualifiedBundleActivityName
                    },
                    CommandLine = new List <string>()
                    {
                        commandLine
                    },
                    Engine     = kEngineName,
                    Parameters = new Dictionary <string, Parameter>()
                    {
                        { "inputJson", new Parameter()
                          {
                              Description = "input json", LocalName = "params.json", Ondemand = false, Required = true, Verb = Verb.Get, Zip = false
                          } },
                        { "outputZip", new Parameter()
                          {
                              Description = "output zip file", LocalName = "output.zip", Ondemand = false, Required = false, Verb = Verb.Put, Zip = false
                          } },
                        { "outputPng", new Parameter()
                          {
                              Description = "output png file", LocalName = "output.png", Ondemand = false, Required = false, Verb = Verb.Put, Zip = false
                          } },
                        { "outputJson", new Parameter()
                          {
                              Description = "output json file", LocalName = "output.json", Ondemand = false, Required = false, Verb = Verb.Put, Zip = false
                          } }
                    }
                };
                Activity newActivity = await _designAutomation.CreateActivityAsync(activitySpec);

                // specify the alias for this Activity
                Alias aliasSpec = new Alias()
                {
                    Id = Alias, Version = 1
                };
                Alias newAlias = await _designAutomation.CreateActivityAliasAsync(kBundleActivityName, aliasSpec);

                return(Ok(new { Activity = QualifiedBundleActivityName }));
            }

            // as this activity points to a AppBundle "dev" alias (which points to the last version of the bundle),
            // there is no need to update it (for this sample), but this may be extended for different contexts
            return(Ok(new { Activity = "Activity already defined" }));
        }
Exemple #10
0
        public async Task <IActionResult> CreateAppBundle([FromBody] JObject appBundleSpecs)
        {
            if (OAuthController.GetAppSetting("DISABLE_SETUP") == "true")
            {
                return(Unauthorized());
            }

            System.Diagnostics.Debug.WriteLine("CreateAppBundle");
            string zipFileName = "UpdateIPTParam.bundle";

            // check if ZIP with bundle is here
            string packageZipPath = Path.Combine(LocalBundlesFolder, zipFileName + ".zip");

            if (!System.IO.File.Exists(packageZipPath))
            {
                throw new Exception("Appbundle not found at " + packageZipPath);
            }

            // get defined app bundles
            Page <string> appBundles = await _designAutomation.GetAppBundlesAsync();

            // check if app bundle is already define
            dynamic newAppVersion;
            string  qualifiedAppBundleId = string.Format("{0}.{1}+{2}", NickName, kBundleActivityName, Alias);

            if (!appBundles.Data.Contains(qualifiedAppBundleId))
            {
                // create an appbundle (version 1)
                AppBundle appBundleSpec = new AppBundle()
                {
                    Package     = kBundleActivityName,
                    Engine      = kEngineName,
                    Id          = kBundleActivityName,
                    Description = string.Format("Description for {0}", kBundleActivityName),
                };
                newAppVersion = await _designAutomation.CreateAppBundleAsync(appBundleSpec);

                if (newAppVersion == null)
                {
                    throw new Exception("Cannot create new app");
                }

                // create alias pointing to v1
                Alias aliasSpec = new Alias()
                {
                    Id = Alias, Version = 1
                };
                Alias newAlias = await _designAutomation.CreateAppBundleAliasAsync(kBundleActivityName, aliasSpec);
            }
            else
            {
                // create new version
                AppBundle appBundleSpec = new AppBundle()
                {
                    Engine      = kEngineName,
                    Description = kBundleActivityName
                };
                newAppVersion = await _designAutomation.CreateAppBundleVersionAsync(kBundleActivityName, appBundleSpec);

                if (newAppVersion == null)
                {
                    throw new Exception("Cannot create new version");
                }

                // update alias pointing to v+1
                AliasPatch aliasSpec = new AliasPatch()
                {
                    Version = newAppVersion.Version
                };
                Alias newAlias = await _designAutomation.ModifyAppBundleAliasAsync(kBundleActivityName, Alias, aliasSpec);
            }

            // upload the zip with .bundle
            RestClient  uploadClient = new RestClient(newAppVersion.UploadParameters.EndpointURL);
            RestRequest request      = new RestRequest(string.Empty, Method.POST);

            request.AlwaysMultipartFormData = true;
            foreach (KeyValuePair <string, string> x in newAppVersion.UploadParameters.FormData)
            {
                request.AddParameter(x.Key, x.Value);
            }
            request.AddFile("file", packageZipPath);
            request.AddHeader("Cache-Control", "no-cache");
            await uploadClient.ExecuteTaskAsync(request);

            return(Ok(new { AppBundle = QualifiedBundleActivityName, Version = newAppVersion.Version }));
        }
Exemple #11
0
        private async Task <string> CreateWorkItem(JToken input, Dictionary <string, string> headers, string browerConnectionId, string inputBucket, string inputName, string outputName, string outputRfaName)
        {
            input["output"] = outputName;
            XrefTreeArgument inputJsonArgument = new XrefTreeArgument()
            {
                Url = "data:application/json," + input.ToString(Formatting.None)
            };

            string inputUrl     = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", inputBucket, inputName);
            string outputUrl    = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", TransientBucketKey, outputName);
            string outputRfaUrl = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", TransientBucketKey, outputRfaName);

            XrefTreeArgument inputArgument = new XrefTreeArgument()
            {
                Url     = inputUrl,
                Verb    = Verb.Get,
                Headers = headers
            };

            XrefTreeArgument outputArgument = new XrefTreeArgument()
            {
                Url     = outputUrl,
                Verb    = Verb.Put,
                Headers = headers
            };

            XrefTreeArgument outputRfaArgument = new XrefTreeArgument()
            {
                Url     = outputRfaUrl,
                Verb    = Verb.Put,
                Headers = headers
            };

            string callbackComplete = string.Format(
                "{0}/api/forge/callback/oncomplete?id={1}&outputFile={2}&outputRfaFile={3}",
                OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"),
                browerConnectionId,
                outputName,
                outputRfaName);

            XrefTreeArgument callbackArgument = new XrefTreeArgument {
                Verb = Verb.Post,
                Url  = callbackComplete
            };

            WorkItem workItemSpec = new WorkItem()
            {
                ActivityId = QualifiedBundleActivityName,
                Arguments  = new Dictionary <string, IArgument>()
                {
                    { "inputZip", inputArgument },
                    { "inputJson", inputJsonArgument },
                    { "outputZip", outputArgument },
                    { "onComplete", callbackArgument }
                }
            };

            if (outputRfaName != null)
            {
                workItemSpec.Arguments.Add("outputRfa", outputRfaArgument);
            }

            WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemAsync(workItemSpec);

            return(workItemStatus.Id);
        }
Exemple #12
0
        public async Task <IActionResult> UploadOssFiles([FromBody] JObject appBundleSpecs)
        {
            if (OAuthController.GetAppSetting("DISABLE_SETUP") == "true")
            {
                return(Unauthorized());
            }

            System.Diagnostics.Debug.WriteLine("UploadOssFiles");
            // OAuth token
            dynamic oauth = await OAuthController.GetInternalAsync();

            ObjectsApi objects = new ObjectsApi();

            objects.Configuration.AccessToken = oauth.access_token;

            DerivativesApi derivatives = new DerivativesApi();

            derivatives.Configuration.AccessToken = oauth.access_token;

            // upload file to OSS Bucket
            // 1. ensure bucket existis
            BucketsApi buckets = new BucketsApi();

            buckets.Configuration.AccessToken = oauth.access_token;
            try
            {
                PostBucketsPayload bucketPayload = new PostBucketsPayload(PersistentBucketKey, null, PostBucketsPayload.PolicyKeyEnum.Persistent);
                await buckets.CreateBucketAsync(bucketPayload, "US");
            }
            catch { }; // in case bucket already exists
            try
            {
                PostBucketsPayload bucketPayload = new PostBucketsPayload(TransientBucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient);
                await buckets.CreateBucketAsync(bucketPayload, "US");
            }
            catch { }; // in case bucket already exists

            string [] filePaths = System.IO.Directory.GetFiles(LocalFilesFolder);
            foreach (string filePath in filePaths)
            {
                string fileName = System.IO.Path.GetFileName(filePath);
                string objectId = await UploadFile(PersistentBucketKey, filePath);

                System.Diagnostics.Debug.WriteLine("Translating " + fileName);
                _ = TranslateFile(objectId, fileName.Replace(".zip", ""));
            }

            DerivativeWebhooksApi webhooks = new DerivativeWebhooksApi();

            webhooks.Configuration.AccessToken = oauth.access_token;

            dynamic webhookRes = await webhooks.GetHooksAsync(DerivativeWebhookEvent.ExtractionFinished);

            foreach (KeyValuePair <string, dynamic> item in new DynamicDictionaryItems(webhookRes.data))
            {
                Guid hookId = new Guid(item.Value.hookId);
                System.Diagnostics.Debug.WriteLine("Deleting webhook, hookId " + hookId);
                await webhooks.DeleteHookAsync(DerivativeWebhookEvent.ExtractionFinished, hookId);
            }

            string callbackComplete = string.Format(
                "{0}/api/forge/callback/ontranslated",
                OAuthController.GetAppSetting("FORGE_WEBHOOK_URL")
                );

            System.Diagnostics.Debug.WriteLine("Creating webhook with workflowId = " + WorkflowId);
            dynamic res = await webhooks.CreateHookAsync(DerivativeWebhookEvent.ExtractionFinished, callbackComplete, WorkflowId);

            System.Diagnostics.Debug.WriteLine("Created webhook");

            return(Ok());
        }
Exemple #13
0
        public async Task <IActionResult> UpdateModel([FromBody] JObject workItemsSpecs)
        {
            // basic input validation
            string widthParam         = workItemsSpecs["width"].Value <string>();
            string heigthParam        = workItemsSpecs["height"].Value <string>();
            string activityName       = string.Format("{0}.{1}", NickName, "UpdateModel");
            string browerConnectionId = workItemsSpecs["browerConnectionId"].Value <string>();

            string inputFileNameOSS  = "";
            string outputFileNameOSS = "";

            // OAuth token
            dynamic oauth = await OAuthController.GetInternalAsync();

            // upload file to OSS Bucket
            // 1. ensure bucket existis
            string bucketKey = NickName.ToLower() + "_designautomation";

            // prepare workitem arguments
            // 1. input file
            XrefTreeArgument inputFileArgument = new XrefTreeArgument()
            {
                Url     = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, inputFileNameOSS),
                Headers = new Dictionary <string, string>()
                {
                    { "Authorization", "Bearer " + oauth.access_token }
                }
            };
            // 2. input json
            dynamic inputJson = new JObject();

            inputJson.Width  = widthParam;
            inputJson.Height = heigthParam;
            XrefTreeArgument inputJsonArgument = new XrefTreeArgument()
            {
                Url = "data:application/json, " + ((JObject)inputJson).ToString(Formatting.None).Replace("\"", "'")
            };
            // 3. output file
            XrefTreeArgument outputFileArgument = new XrefTreeArgument()
            {
                Url     = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFileNameOSS),
                Verb    = Verb.Put,
                Headers = new Dictionary <string, string>()
                {
                    { "Authorization", "Bearer " + oauth.access_token }
                }
            };

            // prepare & submit workitem
            string   callbackUrl  = string.Format("{0}/api/forge/callback/designautomation?id={1}&outputFileName={2}", OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"), browerConnectionId, outputFileNameOSS);
            WorkItem workItemSpec = new WorkItem()
            {
                ActivityId = activityName,
                Arguments  = new Dictionary <string, IArgument>()
                {
                    { "inputFile", inputFileArgument },
                    { "inputJson", inputJsonArgument },
                    { "outputFile", outputFileArgument },
                    { "onComplete", new XrefTreeArgument {
                          Verb = Verb.Post, Url = callbackUrl
                      } }
                }
            };
            WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemsAsync(workItemSpec);

            return(Ok(new { WorkItemId = workItemStatus.Id }));
        }
Exemple #14
0
        public async Task <IActionResult> ExtractParams([FromBody] JObject workItemsSpecs)
        {
            // basic input validation
            string documentPath       = workItemsSpecs["documentPath"].Value <string>();
            string projectPath        = workItemsSpecs["projectPath"].Value <string>();
            string inputFile          = workItemsSpecs["inputFile"].Value <string>();
            string outputFile         = inputFile + ".json";
            string browerConnectionId = workItemsSpecs["browerConnectionId"].Value <string>();
            string activityName       = string.Format("{0}.{1}", NickName, "ExtractParams+prod");

            string bucketKey = NickName.ToLower() + "_designautomation";

            // OAuth token
            dynamic oauth = await OAuthController.GetInternalAsync();

            // prepare workitem arguments
            // 1. input file
            XrefTreeArgument inputFileArgument = new XrefTreeArgument()
            {
                Url     = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, inputFile),
                Headers = new Dictionary <string, string>()
                {
                    { "Authorization", "Bearer " + oauth.access_token }
                }
            };
            // 2. input json
            dynamic inputJson = new JObject();

            inputJson.documentPath = documentPath;
            if (projectPath != "")
            {
                inputJson.projectPath = projectPath;
            }
            XrefTreeArgument inputJsonArgument = new XrefTreeArgument()
            {
                Url = "data:application/json, " + ((JObject)inputJson).ToString(Formatting.None).Replace("\"", "'")
            };
            // 3. output file
            XrefTreeArgument outputFileArgument = new XrefTreeArgument()
            {
                Url     = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFile),
                Verb    = Verb.Put,
                Headers = new Dictionary <string, string>()
                {
                    { "Authorization", "Bearer " + oauth.access_token }
                }
            };

            // prepare & submit workitem
            string   callbackUrl  = string.Format("{0}/api/forge/callback/designautomation/extractparams?id={1}&outputFileName={2}", OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"), browerConnectionId, HttpUtility.UrlEncode(outputFile));
            WorkItem workItemSpec = new WorkItem()
            {
                ActivityId = activityName,
                Arguments  = new Dictionary <string, IArgument>()
                {
                    { "inputFile", inputFileArgument },
                    { "inputParams", inputJsonArgument },
                    { "documentParams", outputFileArgument },
                    { "onComplete", new XrefTreeArgument {
                          Verb = Verb.Post, Url = callbackUrl
                      } }
                }
            };

            try
            {
                WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemsAsync(workItemSpec);

                return(Ok(new { WorkItemId = workItemStatus.Id }));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }