private async Task <IList <TreeNode> > GetFolderContents(string href) { IList <TreeNode> nodes = new List <TreeNode>(); string[] idParams = href.Split('/'); string folderId = idParams[idParams.Length - 1]; string projectId = idParams[idParams.Length - 3]; FoldersApi folderApi = new FoldersApi(); folderApi.Configuration.AccessToken = AccessToken; var folderContents = await folderApi.GetFolderContentsAsync(projectId, folderId); foreach (KeyValuePair <string, dynamic> folderContentItem in new DynamicDictionaryItems(folderContents.data)) { string displayName = folderContentItem.Value.attributes.displayName; if (string.IsNullOrWhiteSpace(displayName)) { // BIM 360 related documents don't have displayName // need to ask each one for a name ItemsApi itemsApi = new ItemsApi(); itemsApi.Configuration.AccessToken = AccessToken; dynamic item = await itemsApi.GetItemAsync(projectId, folderContentItem.Value.id); displayName = item.included[0].attributes.displayName; } TreeNode itemNode = new TreeNode(folderContentItem.Value.links.self.href, displayName, (string)folderContentItem.Value.type, true); nodes.Add(itemNode); } return(nodes); }
private async Task GetItemVersionsAsync(Credentials credentials, string hubId, string folderUrn, string itemHref, PerformContext context) { await credentials.RefreshAsync(); BackgroundJobClient metadataQueue = new BackgroundJobClient(); IState state = new EnqueuedState("metadata"); // the API SDK ItemsApi itemApi = new ItemsApi(); itemApi.Configuration.AccessToken = credentials.TokenInternal; // extract the projectId & itemId from the href string[] idParams = itemHref.Split('/'); string itemUrn = idParams[idParams.Length - 1]; string projectId = idParams[idParams.Length - 3]; var item = await itemApi.GetItemAsync(projectId, itemUrn); string versionUrn = (string)item.data.relationships.tip.data.id; string fileName = (string)item.data.attributes.displayName; string extension = fileName.Split(".").Last().ToLower(); if (Config.SupportedFormats.IndexOf(extension) == -1) { return; } string absolutePath = string.Format("/manifest/_doc/{0}", ModelDerivativeController.Base64Encode(itemUrn)); RestClient client = new RestClient(Config.ElasticSearchServer); RestRequest request = new RestRequest(absolutePath, RestSharp.Method.GET); if (!string.IsNullOrEmpty(Config.AWSKey) && !string.IsNullOrEmpty(Config.AWSSecret)) { SortedDictionary <string, string> headers = AWS.Signature.SignatureHeader( Amazon.RegionEndpoint.GetBySystemName(Config.AWSRegion), new Uri(Config.ElasticSearchServer).Host, "GET", string.Empty, absolutePath); foreach (var entry in headers) { request.AddHeader(entry.Key, entry.Value); } } IRestResponse res = await client.ExecuteTaskAsync(request); if (res.StatusCode == HttpStatusCode.OK && Config.SkipAlreadyIndexed) { context.WriteLine(string.Format("{0}: already indexed, skip", fileName)); System.Threading.Thread.Sleep(1000); // otherwise we'll reach the rate limit... return; } context.WriteLine(string.Format("{0}: {1}", fileName, versionUrn)); await ModelDerivativeHub.NotifyFileFound(_hubContext, hubId); metadataQueue.Create(() => ProcessFile(credentials.UserId, hubId, projectId, folderUrn, itemUrn, versionUrn, fileName, null), state); }
private async Task <dynamic> PreWorkNewVersion(string userAccessToken, string projectId, string versionId) { // get version VersionsApi versionApi = new VersionsApi(); versionApi.Configuration.AccessToken = userAccessToken; dynamic versionItem = await versionApi.GetVersionItemAsync(projectId, versionId); // get item ItemsApi itemApi = new ItemsApi(); itemApi.Configuration.AccessToken = userAccessToken; string itemId = versionItem.data.id; dynamic item = await itemApi.GetItemAsync(projectId, itemId); string folderId = item.data.relationships.parent.data.id; string fileName = item.data.attributes.displayName; // prepare storage ProjectsApi projectApi = new ProjectsApi(); projectApi.Configuration.AccessToken = userAccessToken; 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 projectApi.PostStorageAsync(projectId, storage); string[] storageIdParams = ((string)storageCreated.data.id).Split('/'); string[] bucketKeyParams = storageIdParams[storageIdParams.Length - 2].Split(':'); string bucketKey = bucketKeyParams[bucketKeyParams.Length - 1]; string objectName = storageIdParams[storageIdParams.Length - 1]; string uploadUrl = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, objectName); return(new StorageInfo { fileName = fileName, itemId = item.data.id, storageId = storageCreated.data.id, uploadUrl = uploadUrl }); }
public async Task <string> GetFolderId(string projectId, string versionId, string userAccessToken) { VersionsApi versionApi = new VersionsApi(); versionApi.Configuration.AccessToken = userAccessToken; dynamic versionItem = await versionApi.GetVersionItemAsync(projectId, versionId); string itemId = versionItem.data.id; ItemsApi itemApi = new ItemsApi(); itemApi.Configuration.AccessToken = userAccessToken; dynamic item = await itemApi.GetItemAsync(projectId, itemId); string folderId = item.data.relationships.parent.data.id;; return(folderId); }
private async Task <IList <jsTreeNode> > GetItemVersions(string href) { IList <jsTreeNode> nodes = new List <jsTreeNode>(); // the API SDK ItemsApi itemApi = new ItemsApi(); itemApi.Configuration.AccessToken = Credentials.TokenInternal; // extract the projectId & itemId from the href string[] idParams = href.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; 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; string urn = string.Empty; try { urn = (string)version.Value.relationships.derivatives.data.id; } catch { urn = Base64Encode(version.Value.id); } // some BIM 360 versions don't have viewable jsTreeNode node = new jsTreeNode( urn, string.Format("v{0}: {1} by {2}", verNum, versionDate.ToString("dd/MM/yy HH:mm:ss"), userName), "versions", false); nodes.Add(node); } 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 })); }