public async Task <dynamic> TranslateObject([FromBody] ObjectModel objModel) { Credentials credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies); DerivativesApi derivative = new DerivativesApi(); derivative.Configuration.AccessToken = credentials.TokenInternal; var manifest = await derivative.GetManifestAsync(objModel.urn); if (manifest.status == "inprogress") { return(null); // another job in progress } // prepare the payload List <JobPayloadItem> outputs = new List <JobPayloadItem>() { new JobPayloadItem(JobPayloadItem.TypeEnum.Ifc) }; JobPayload job = new JobPayload(new JobPayloadInput(objModel.urn), new JobPayloadOutput(outputs)); // start the translation dynamic jobPosted = await derivative.TranslateAsync(job, false /* do not force re-translate */); return(jobPosted); }
public async Task <IActionResult> DownloadDerivative(string urn, string outputType) { Credentials credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies); DerivativesApi derivative = new DerivativesApi(); derivative.Configuration.AccessToken = credentials.TokenInternal; var manifest = await derivative.GetManifestAsync(urn); foreach (KeyValuePair <string, dynamic> output in new DynamicDictionaryItems(manifest.derivatives)) { if (output.Value.outputType == outputType) { // already translated! if (_httpClient == null) { _httpClient = new HttpClient( // this should avoid HttpClient seaching for proxy settings new HttpClientHandler() { UseProxy = false, Proxy = null }, true); _httpClient.BaseAddress = new Uri(FORGE_BASE_URL); ServicePointManager.DefaultConnectionLimit = int.MaxValue; } // request to download file HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, string.Format("{0}/modelderivative/v2/designdata/{1}/manifest/{2}", FORGE_BASE_URL, urn, output.Value.children[0].urn)); request.Headers.Add("Authorization", "Bearer " + credentials.TokenInternal); // add our Access Token HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); Stream file = await response.Content.ReadAsStreamAsync(); // stream result to client var cd = new System.Net.Mime.ContentDisposition { FileName = "result.ifc", // always prompt the user for downloading, set to true if you want // the browser to try to show the file inline Inline = false, }; Response.Headers.Add("Content-Disposition", cd.ToString()); return(File(file, "application/octet-stream")); } } return(null); }
public async Task <dynamic> CreateBucket([FromBody] CreateBucketModel bucket) { BucketsApi buckets = new BucketsApi(); // Credentials credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies); // //dynamic token = await OAuthController.GetInternalAsync(); buckets.Configuration.AccessToken = credentials.TokenInternal; PostBucketsPayload bucketPayload = new PostBucketsPayload(bucket.bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient); return(await buckets.CreateBucketAsync(bucketPayload, "US")); }
public async Task <AccessToken> GetPublicTokenAsync() { Credentials credentials = await Credentials.FromSessionAsync(Request.Cookies, Response.Cookies); if (credentials == null) { base.Response.StatusCode = (int)HttpStatusCode.Unauthorized; return(new AccessToken()); } // return the public (viewables:read) access token return(new AccessToken() { access_token = credentials.TokenPublic, expires_in = (int)credentials.ExpiresAt.Subtract(DateTime.Now).TotalSeconds }); }
public async Task <dynamic> UploadObject([FromForm] UploadFileInput input) { // basic input validation if (string.IsNullOrWhiteSpace(input.bucketKey)) { throw new System.Exception("BucketKey parameter was not provided."); } if (input.inputFile == null) { throw new System.Exception("Missing file to upload"); // for now, let's support just 1 file at a time } string bucketKey = input.bucketKey; var fileSavePath = Path.Combine(Directory.GetCurrentDirectory() + "\\wwwroot\\appdata", Path.GetFileName(input.inputFile.FileName)); using (var stream = new FileStream(fileSavePath, FileMode.Create)) await input.inputFile.CopyToAsync(stream); // Credentials credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies); // // get the bucket... //dynamic oauth = await OAuthController.GetInternalAsync(); ObjectsApi objects = new ObjectsApi(); //objects.Configuration.AccessToken = oauth.access_token; objects.Configuration.AccessToken = credentials.TokenInternal; // upload the file/object, which will create a new object dynamic uploadedObj; using (StreamReader streamReader = new StreamReader(fileSavePath)) { uploadedObj = await objects.UploadObjectAsync(bucketKey, Path.GetFileName(input.inputFile.FileName), (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream"); } // cleanup System.IO.File.Delete(fileSavePath);// delete server copy return(uploadedObj); }
public async Task <IList <TreeNode> > GetOSSAsync([FromQuery] string id) { IList <TreeNode> nodes = new List <TreeNode>(); //dynamic oauth = await OAuthController.GetInternalAsync(); // // Credentials credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies); // //string bucketKey = NickName.ToLower() + "_designautomation"; //id = "#"; // if (id == "#") // root { // in this case, let's return all buckets BucketsApi appBckets = new BucketsApi(); appBckets.Configuration.AccessToken = credentials.TokenInternal; //appBckets.Configuration.AccessToken = oauth.access_token; // to simplify, let's return only the first 100 buckets dynamic buckets = await appBckets.GetBucketsAsync("US", 100); foreach (KeyValuePair <string, dynamic> bucket in new DynamicDictionaryItems(buckets.items)) { nodes.Add(new TreeNode(bucket.Value.bucketKey, bucket.Value.bucketKey, "bucket", true)); } } else { // as we have the id (bucketKey), let's return all ObjectsApi objects = new ObjectsApi(); //objects.Configuration.AccessToken = oauth.access_token; objects.Configuration.AccessToken = credentials.TokenInternal; var objectsList = objects.GetObjects(id, 100); foreach (KeyValuePair <string, dynamic> objInfo in new DynamicDictionaryItems(objectsList.items)) { nodes.Add(new TreeNode(Base64Encode((string)objInfo.Value.objectId), objInfo.Value.objectKey, "object", false)); } } return(nodes); }
//public async Task<IActionResult> Testing(string id) public async Task <IList <jsTreeNode> > Testing(string id) { IList <jsTreeNode> nodes = new List <jsTreeNode>(); // the API SDK Credentials credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies); ItemsApi itemApi = new ItemsApi(); itemApi.Configuration.AccessToken = credentials.TokenInternal; // extract the projectId & itemId from the href string[] idParams = id.Split('/'); string itemId = idParams[idParams.Length - 1]; string projectId = idParams[idParams.Length - 3]; var versions = await itemApi.GetItemVersionsAsync(projectId, itemId); dynamic item = await itemApi.GetItemAsync(projectId, itemId); string folderId = item.data.relationships.parent.data.id; string displayFileName = item.data.attributes.displayName; string versionId = null; foreach (KeyValuePair <string, dynamic> version in new DynamicDictionaryItems(versions.data)) { DateTime versionDate = version.Value.attributes.lastModifiedTime; string verNum = version.Value.id.Split("=")[1]; string userName = version.Value.attributes.lastModifiedUserName; versionId = version.Value.id; if (verNum == "1") { break; } string urn = string.Empty; try { urn = (string)version.Value.relationships.derivatives.data.id; } catch { } } //get user id UserController user = new UserController(); user.Credentials = credentials; dynamic userProfile = await user.GetUserProfileAsync(); string userId = userProfile.id; //// Prepare the DA input from BIM 360 //var input = await BuildBIM360DownloadURL(credentials.TokenInternal, projectId, versionId); //// Prepare the DA output to BIM 360 //var storageInfo = await PreWorkNewVersion(credentials.TokenInternal, projectId, versionId); //string storageId = storageInfo.storageId; //string fileName = storageInfo.fileName; //try //{ // BackgroundJob.Schedule(() => PostProcessFile(credentials.TokenInternal, userId, projectId, itemId, storageId, fileName), TimeSpan.FromSeconds(1)); //} //catch (Exception e) { } // StorageInfo info = await PreWorkNewVersion(credentials.TokenInternal, projectId, versionId); string callbackUrl = string.Format("{0}/api/forge/callback/designautomation/revit/{1}/{2}/{3}/{4}/{5}", Credentials.GetAppSetting("FORGE_WEBHOOK_URL"), userId, projectId, info.itemId.Base64Encode(), info.storageId.Base64Encode(), info.fileName.Base64Encode()); WorkItem workItemSpec = new WorkItem() { ActivityId = ActivityFullName, Arguments = new Dictionary <string, IArgument>() { { "inputFile", await BuildBIM360DownloadURL(credentials.TokenInternal, projectId, versionId) }, { "outputFile", await BuildBIM360UploadURL(credentials.TokenInternal, info) }, { "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } } } }; WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemsAsync(workItemSpec); try { var storageInfo = await PreWorkNewVersion(credentials.TokenInternal, projectId, versionId); string storageId = storageInfo.storageId; string fileName = storageInfo.fileName; BackgroundJob.Schedule(() => PostProcessFile(credentials.TokenInternal, userId, projectId, itemId, storageId, fileName), TimeSpan.FromSeconds(1)); } catch (Exception e) { } // return(nodes); }
//public async Task<IActionResult> Testing(string id) public async Task <IList <jsTreeNode> > Testing1(string id) { IList <jsTreeNode> nodes = new List <jsTreeNode>(); // the API SDK Credentials credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies); ItemsApi itemApi = new ItemsApi(); itemApi.Configuration.AccessToken = credentials.TokenInternal; // extract the projectId & itemId from the href string[] idParams = id.Split('/'); string itemId = idParams[idParams.Length - 1]; string projectId = idParams[idParams.Length - 3]; var versions = await itemApi.GetItemVersionsAsync(projectId, itemId); dynamic item = await itemApi.GetItemAsync(projectId, itemId); string folderId = item.data.relationships.parent.data.id; string fileName = item.data.attributes.displayName; string versionId = null; foreach (KeyValuePair <string, dynamic> version in new DynamicDictionaryItems(versions.data)) { DateTime versionDate = version.Value.attributes.lastModifiedTime; string verNum = version.Value.id.Split("=")[1]; string userName = version.Value.attributes.lastModifiedUserName; versionId = version.Value.id; string urn = string.Empty; try { urn = (string)version.Value.relationships.derivatives.data.id; } catch { } } // Prepare the DA input from BIM 360 var input = await BuildBIM360DownloadURL(credentials.TokenInternal, projectId, versionId); //var output = await PreWorkNewVersion(credentials.TokenInternal, projectId, versionId); // Create a version for this new file // prepare storage ProjectsApi projectApis = new ProjectsApi(); projectApis.Configuration.AccessToken = credentials.TokenInternal; StorageRelationshipsTargetData storageRelData = new StorageRelationshipsTargetData(StorageRelationshipsTargetData.TypeEnum.Folders, folderId); CreateStorageDataRelationshipsTarget storageTarget = new CreateStorageDataRelationshipsTarget(storageRelData); CreateStorageDataRelationships storageRel = new CreateStorageDataRelationships(storageTarget); BaseAttributesExtensionObject attributes = new BaseAttributesExtensionObject(string.Empty, string.Empty, new JsonApiLink(string.Empty), null); CreateStorageDataAttributes storageAtt = new CreateStorageDataAttributes(fileName, attributes); CreateStorageData storageData = new CreateStorageData(CreateStorageData.TypeEnum.Objects, storageAtt, storageRel); CreateStorage storage = new CreateStorage(new JsonApiVersionJsonapi(JsonApiVersionJsonapi.VersionEnum._0), storageData); dynamic storageCreated = await projectApis.PostStorageAsync(projectId, storage); VersionsApi versionsApi = new VersionsApi(); versionsApi.Configuration.AccessToken = credentials.TokenInternal; CreateVersion newVersionData = new CreateVersion ( new JsonApiVersionJsonapi(JsonApiVersionJsonapi.VersionEnum._0), new CreateVersionData ( CreateVersionData.TypeEnum.Versions, new CreateStorageDataAttributes ( fileName, new BaseAttributesExtensionObject ( "versions:autodesk.bim360:File", "1.0", new JsonApiLink(string.Empty), null ) ), new CreateVersionDataRelationships ( new CreateVersionDataRelationshipsItem ( new CreateVersionDataRelationshipsItemData ( CreateVersionDataRelationshipsItemData.TypeEnum.Items, itemId ) ), new CreateItemRelationshipsStorage ( new CreateItemRelationshipsStorageData ( CreateItemRelationshipsStorageData.TypeEnum.Objects, storageCreated.data.id ) ) ) ) ); dynamic newVersion = await versionsApi.PostVersionAsync(projectId, newVersionData); return(nodes); }
public async Task <IActionResult> StartWorkItem([FromForm] StartWorkitemInput input) //public async Task<IActionResult> StartWorkItem(string id) { // OAuth token // Credentials credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies); string id = $"https://developer.api.autodesk.com/data/v1/projects/b.9f77180c-7cd1-40d8-9d70-d80608dfdfd9/items/urn:adsk.wipprod:dm.lineage:SXwSwlsTT_GkrOQ3GXtDUA"; // extract the projectId & itemId from the href ItemsApi itemApi = new ItemsApi(); itemApi.Configuration.AccessToken = credentials.TokenInternal; string[] idParams = id.Split('/'); string itemId = idParams[idParams.Length - 1]; string projectId = idParams[idParams.Length - 3]; dynamic item = await itemApi.GetItemAsync(projectId, itemId); List <int?> filterVersionNumber = new List <int?>() { 1 }; var versions = await itemApi.GetItemVersionsAsync(projectId, itemId); string folderId = item.data.relationships.parent.data.id; string displayFileName = item.data.attributes.displayName; string versionId = null; foreach (KeyValuePair <string, dynamic> version in new DynamicDictionaryItems(versions.data)) { DateTime versionDate = version.Value.attributes.lastModifiedTime; string verNum = version.Value.id.Split("=")[1]; string userName = version.Value.attributes.lastModifiedUserName; versionId = version.Value.id; string urn = string.Empty; try { urn = (string)version.Value.relationships.derivatives.data.id; } catch { } } // // 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); // upload file to OSS Bucket // 1. ensure bucket existis string bucketKey = NickName.ToLower() + "_designautomation"; BucketsApi buckets = new BucketsApi(); buckets.Configuration.AccessToken = credentials.TokenInternal; 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 = credentials.TokenInternal; 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 " + credentials.TokenInternal } } }; //XrefTreeArgument inputFileArgument = BuildBIM360DownloadURL(oauth.access_token, projectId, versionId); // 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 " + credentials.TokenInternal } } }; // 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 })); }