public async Task <IActionResult> GetResults() { dynamic oauth = await OAuthController.GetInternalAsync(); string bucketKey = NickName.ToLower() + "_designautomation"; string outputFileNameOSS = string.Format("{0}_output_{1}", _createTime, "max sample file.max"); // avoid overriding ObjectsApi objects = new ObjectsApi(); objects.Configuration.AccessToken = oauth.access_token; System.IO.FileStream result = objects.GetObject(bucketKey, outputFileNameOSS); if (result == null) { return(NotFound()); } return(Ok(result.Name)); }
public async Task <IActionResult> ClearAccount() { if (!_env.IsDevelopment()) { return(BadRequest()); // disable when published :-) } dynamic oauth = await OAuthController.GetInternalAsync(); // define the account api (ForgeApps) Autodesk.Forge.DesignAutomation.v3.ForgeAppsApi forgeAppApi = new ForgeAppsApi(); forgeAppApi.Configuration.AccessToken = oauth.access_token; // clear account await forgeAppApi.ForgeAppsDeleteUserAsync("me"); return(Ok()); }
/// <summary> /// Define a new activity /// </summary> public static async Task <bool> IsInCache(string fileName) { dynamic oauth = await OAuthController.GetInternalAsync(); ObjectsApi objects = new ObjectsApi(); objects.Configuration.AccessToken = oauth.access_token; try { dynamic res = await objects.GetObjectDetailsAsync(BucketKey, fileName); return(true); } catch {} return(false); }
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()); }
public async Task <dynamic> UploadObject() { // basic input validation HttpRequest req = HttpContext.Current.Request; if (string.IsNullOrWhiteSpace(req.Params["bucketKey"])) { throw new System.Exception("BucketKey parameter was not provided."); } if (req.Files.Count != 1) { throw new System.Exception("Missing file to upload"); // for now, let's support just 1 file at a time } string bucketKey = req.Params["bucketKey"]; HttpPostedFile file = req.Files[0]; // save the file on the server var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"), file.FileName); file.SaveAs(fileSavePath); // get the bucket... dynamic oauth = await OAuthController.GetInternalAsync(); ObjectsApi objects = new ObjectsApi(); objects.Configuration.AccessToken = oauth.access_token; // upload the file/object, which will create a new object dynamic uploadedObj; using (StreamReader streamReader = new StreamReader(fileSavePath)) { uploadedObj = await objects.UploadObjectAsync(bucketKey, file.FileName, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream"); } // cleanup File.Delete(fileSavePath); return(uploadedObj); }
private async Task TranslateFile(string objectId, string rootFileName, string workflowId = null) { dynamic oauth = await OAuthController.GetInternalAsync(); // prepare the payload List <JobPayloadItem> outputs = new List <JobPayloadItem>() { new JobPayloadItem( JobPayloadItem.TypeEnum.Svf, new List <JobPayloadItem.ViewsEnum>() { JobPayloadItem.ViewsEnum._2d, JobPayloadItem.ViewsEnum._3d } ) }; JobPayloadMisc misc = null; if (workflowId != null) { misc = new JobPayloadMisc(workflowId); } JobPayload job; string urn = Base64Encode(objectId); if (rootFileName != null) { job = new JobPayload(new JobPayloadInput(urn, true, rootFileName), new JobPayloadOutput(outputs), misc); } else { job = new JobPayload(new JobPayloadInput(urn), new JobPayloadOutput(outputs)); } // start the translation DerivativesApi derivative = new DerivativesApi(); derivative.Configuration.AccessToken = oauth.access_token; dynamic res = await derivative.TranslateAsync(job, true); }
public async Task <IActionResult> OnComplete(string id, string outputFile, [FromBody] dynamic body) { System.Diagnostics.Debug.WriteLine($"OnComplete, id = {id}, outputFile = {outputFile}"); try { // your webhook should return immediately! we can use Hangfire to schedule a job JObject bodyJson = JObject.Parse((string)body.ToString()); await _hubContext.Clients.Client(id).SendAsync("onComplete", bodyJson.ToString()); var client = new RestClient(bodyJson["reportUrl"].Value <string>()); var request = new RestRequest(string.Empty); byte[] bs = client.DownloadData(request); string report = System.Text.Encoding.Default.GetString(bs); await _hubContext.Clients.Client(id).SendAsync("onComplete", report); if (outputFile.EndsWith(".png")) { dynamic oauth = await OAuthController.GetInternalAsync(); ObjectsApi objects = new ObjectsApi(); objects.Configuration.AccessToken = oauth.access_token; dynamic signedUrl = await objects.CreateSignedResourceAsyncWithHttpInfo(BucketKey, outputFile, new PostBucketsSigned(10), "read"); await _hubContext.Clients.Client(id).SendAsync("onPicture", (string)(signedUrl.Data.signedUrl)); } if (outputFile.EndsWith(".zip")) { string objectId = "urn:adsk.objects:os.object:" + BucketKey + "/" + outputFile; TranslateFile(objectId, "shelves.iam"); } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("OnComplete, e.Message = " + e.Message); } // ALWAYS return ok (200) return(Ok()); }
public async Task <List <string> > GetAvailableEngines() { dynamic oauth = await OAuthController.GetInternalAsync(); List <string> allEngines = new List <string>(); // define Engines API string paginationToken = null; while (true) { Page <string> engines = await _designAutomation.GetEnginesAsync(paginationToken); allEngines.AddRange(engines.Data); if (engines.PaginationToken == null) { break; } paginationToken = engines.PaginationToken; } allEngines.Sort(); return(allEngines); // return list of engines }
public async Task <IActionResult> OnComplete(string id, string outputFile, string outputRfaFile, [FromBody] dynamic body) { System.Diagnostics.Debug.WriteLine($"OnComplete, id = {id}, outputFile = {outputFile}, outputRfaFile = {outputRfaFile}"); try { JObject bodyJson = JObject.Parse((string)body.ToString()); // your webhook should return immediately! we can use Hangfire to schedule a job var client = new RestClient(bodyJson["reportUrl"].Value <string>()); var request = new RestRequest(string.Empty); byte[] bs = client.DownloadData(request); string report = System.Text.Encoding.Default.GetString(bs); await _hubContext.Clients.Client(id).SendAsync("onReport", report); await _hubContext.Clients.Client(id).SendAsync("onComplete", bodyJson.ToString()); // If we got a reasonable file name if (outputRfaFile != null) { dynamic oauth = await OAuthController.GetInternalAsync(); ObjectsApi objects = new ObjectsApi(); objects.Configuration.AccessToken = oauth.access_token; dynamic signedUrl = await objects.CreateSignedResourceAsyncWithHttpInfo(TransientBucketKey, outputRfaFile, new PostBucketsSigned(30), "read"); string url = signedUrl.Data.signedUrl; await _hubContext.Clients.Client(id).SendAsync("onUrl", "{ \"url\": \"" + url + "\", \"text\": \"Download output.rfa\" }"); } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("OnComplete, e.Message = " + e.Message); } // ALWAYS return ok (200) return(Ok()); }
public async Task <List <string> > GetDefinedActivities() { dynamic oauth = await OAuthController.GetInternalAsync(); // define Activities API ActivitiesApi activitiesApi = new ActivitiesApi(); activitiesApi.Configuration.AccessToken = oauth.access_token;; // filter list of PageString activities = await activitiesApi.ActivitiesGetItemsAsync(); List <string> definedActivities = new List <string>(); foreach (string activity in activities.Data) { if (activity.StartsWith(NickName) && activity.IndexOf("$LATEST") == -1) { definedActivities.Add(activity.Replace(NickName + ".", String.Empty)); } } return(definedActivities); }
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 <IActionResult> CreateAppBundle([FromBody] JObject appBundleSpecs) { // basic input validation string zipFileName = appBundleSpecs["zipFileName"].Value <string>(); string engineName = appBundleSpecs["engine"].Value <string>(); // standard name for this sample string appBundleName = zipFileName + "AppBundle"; // 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); } // define Activities API dynamic oauth = await OAuthController.GetInternalAsync(); AppBundlesApi appBundlesApi = new AppBundlesApi(); appBundlesApi.Configuration.AccessToken = oauth.access_token; // get defined app bundles PageString appBundles = await appBundlesApi.AppBundlesGetItemsAsync(); // check if app bundle is already define dynamic newAppVersion; string qualifiedAppBundleId = string.Format("{0}.{1}+{2}", NickName, appBundleName, Alias); if (!appBundles.Data.Contains(qualifiedAppBundleId)) { // create an appbundle (version 1) AppBundle appBundleSpec = new AppBundle(appBundleName, null, engineName, null, null, string.Format("Description for {0}", appBundleName), null, appBundleName); newAppVersion = await appBundlesApi.AppBundlesCreateItemAsync(appBundleSpec); if (newAppVersion == null) { throw new Exception("Cannot create new app"); } // create alias pointing to v1 Alias aliasSpec = new Alias(1, null, Alias); Alias newAlias = await appBundlesApi.AppBundlesCreateAliasAsync(appBundleName, aliasSpec); } else { // create new version AppBundle appBundleSpec = new AppBundle(null, null, engineName, null, null, appBundleName, null, null); newAppVersion = await appBundlesApi.AppBundlesCreateItemVersionAsync(appBundleName, appBundleSpec); if (newAppVersion == null) { throw new Exception("Cannot create new version"); } // update alias pointing to v+1 Alias aliasSpec = new Alias(newAppVersion.Version, null, null); Alias newAlias = await appBundlesApi.AppBundlesModifyAliasAsync(appBundleName, 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, object> 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 = qualifiedAppBundleId, Version = newAppVersion.Version })); }
public async Task <IActionResult> CreateActivity([FromBody] JObject activitySpecs) { // basic input validation string zipFileName = activitySpecs["zipFileName"].Value <string>(); string engineName = activitySpecs["engine"].Value <string>(); // define Activities API dynamic oauth = await OAuthController.GetInternalAsync(); ActivitiesApi activitiesApi = new ActivitiesApi(); activitiesApi.Configuration.AccessToken = oauth.access_token; // standard name for this sample string appBundleName = zipFileName + "AppBundle"; string activityName = zipFileName + "Activity"; // PageString activities = await activitiesApi.ActivitiesGetItemsAsync(); string qualifiedActivityId = string.Format("{0}.{1}+{2}", NickName, activityName, Alias); if (!activities.Data.Contains(qualifiedActivityId)) { // define the activity // ToDo: parametrize for different engines... dynamic engineAttributes = EngineAttributes(engineName); string commandLine = string.Format(@"$(engine.path)\\{0} /i $(args[inputFile].path) /al $(appbundles[{1}].path) /s $(settings[script].path)", engineAttributes.executable, appBundleName); ModelParameter inputFile = new ModelParameter(false, false, ModelParameter.VerbEnum.Get, "input file", true, "$(inputFile)"); ModelParameter inputJson = new ModelParameter(false, false, ModelParameter.VerbEnum.Get, "input json", false, "params.json"); ModelParameter outputFile = new ModelParameter(false, false, ModelParameter.VerbEnum.Put, "output file", true, "outputFile." + engineAttributes.extension); Activity activitySpec = new Activity( new List <string>() { commandLine }, new Dictionary <string, ModelParameter>() { { "inputFile", inputFile }, { "inputJson", inputJson }, { "outputFile", outputFile } }, engineName, new List <string>() { string.Format("{0}.{1}+{2}", NickName, appBundleName, Alias) }, new Dictionary <string, dynamic>() { { "script", new { value = "UpdateParam\n" } } }, string.Format("Description for {0}", activityName), null, activityName); Activity newActivity = await activitiesApi.ActivitiesCreateItemAsync(activitySpec); // specify the alias for this Activity Alias aliasSpec = new Alias(1, null, Alias); Alias newAlias = await activitiesApi.ActivitiesCreateAliasAsync(activityName, aliasSpec); return(Ok(new { Activity = qualifiedActivityId })); } // 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" })); }
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); }
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 })); }
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 })); }
private async Task <string> UploadFile(string bucketKey, string filePath) { // OAuth token dynamic oauth = await OAuthController.GetInternalAsync(); string objectId = ""; ObjectsApi objects = new ObjectsApi(); objects.Configuration.AccessToken = oauth.access_token; string fileName = System.IO.Path.GetFileName(filePath); using (BinaryReader binaryReader = new BinaryReader(new FileStream(filePath, FileMode.Open))) { System.Diagnostics.Debug.WriteLine("Uploading " + fileName); //dynamic uploadRes = await objects.UploadObjectAsync(PersistentBucketKey, fileName, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream"); // get file size long fileSize = binaryReader.BaseStream.Length; // decide if upload direct or resumable (by chunks) if (fileSize > UPLOAD_CHUNK_SIZE) // upload in chunks { long chunkSize = UPLOAD_CHUNK_SIZE; // 2 Mb long numberOfChunks = (long)Math.Round((double)(fileSize / chunkSize)) + 1; long start = 0; chunkSize = (numberOfChunks > 1 ? chunkSize : fileSize); long end = chunkSize; string sessionId = Guid.NewGuid().ToString(); // upload one chunk at a time for (int chunkIndex = 0; chunkIndex < numberOfChunks; chunkIndex++) { string range = string.Format("bytes {0}-{1}/{2}", start, end, fileSize); long numberOfBytes = chunkSize + 1; byte[] fileBytes = new byte[numberOfBytes]; MemoryStream memoryStream = new MemoryStream(fileBytes); binaryReader.BaseStream.Seek((int)start, SeekOrigin.Begin); int count = binaryReader.Read(fileBytes, 0, (int)numberOfBytes); memoryStream.Write(fileBytes, 0, (int)numberOfBytes); memoryStream.Position = 0; dynamic chunkUploadResponse = await objects.UploadChunkAsyncWithHttpInfo(bucketKey, fileName, (int)numberOfBytes, range, sessionId, memoryStream); if (chunkUploadResponse.StatusCode == 200) { objectId = chunkUploadResponse.Data.objectId; } start = end + 1; chunkSize = ((start + chunkSize > fileSize) ? fileSize - start - 1 : chunkSize); end = start + chunkSize; } } else // upload in a single call { using (StreamReader streamReader = new StreamReader(filePath)) { dynamic uploadedObj = await objects.UploadObjectAsync( bucketKey, fileName, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream"); objectId = uploadedObj.objectId; } } } return(objectId); }
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()); }
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 })); }
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)); } }