Beispiel #1
0
        //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);
        }
Beispiel #2
0
        //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);
        }
Beispiel #3
0
        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 }));
        }