Ejemplo n.º 1
0
        public async Task <dynamic> TranslateObject([FromBody] TranslateObjectModel objModel)
        {
            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
                })
            };
            JobPayload job;

            job = new JobPayload(new JobPayloadInput(objModel.objectName), new JobPayloadOutput(outputs));

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

            derivative.Configuration.AccessToken = oauth.access_token;
            dynamic jobPosted = await derivative.TranslateAsync(job);

            return(jobPosted);
        }
        public async Task <IList <TreeNode> > GetOSSAsync(string id)
        {
            IList <TreeNode> nodes = new List <TreeNode>();
            dynamic          oauth = await OAuthController.GetInternalAsync();

            if (id == "#") // root
            {
                // in this case, let's return all buckets
                BucketsApi appBckets = new BucketsApi();
                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.Replace(ClientId + "-", string.Empty), "bucket", true));
                }
            }
            else
            {
                // as we have the id (bucketKey), let's return all
                ObjectsApi objects = new ObjectsApi();
                objects.Configuration.AccessToken = oauth.access_token;
                var objectsList = objects.GetObjects(id);
                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 <dynamic> UploadObject([FromForm] UploadFile input)
        {
            // save the file on the server
            var fileSavePath = Path.Combine(_env.ContentRootPath, input.fileToUpload.FileName);

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


            // 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(input.bucketKey,
                                                              input.fileToUpload.FileName, (int)streamReader.BaseStream.Length, streamReader.BaseStream,
                                                              "application/octet-stream");
            }

            // cleanup
            System.IO.File.Delete(fileSavePath);

            return(uploadedObj);
        }
Ejemplo n.º 4
0
        public async Task DeleteBucket([FromBody] BucketModel bucket)
        {
            BucketsApi buckets = new BucketsApi();
            dynamic    token   = await OAuthController.GetInternalAsync();

            buckets.Configuration.AccessToken = token.access_token;
            await buckets.DeleteBucketAsync(bucket.bucketKey);
        }
        public async Task <dynamic> TranslateObject([FromBody] TranslateObjectModel 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 = new JobPayload(new JobPayloadInput(objModel.objectName), 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 <List <string> > GetAvailableEngines()
        {
            dynamic oauth = await OAuthController.GetInternalAsync();

            // define Engines API
            Page <string> engines = await _designAutomation.GetEnginesAsync();

            // return just REVIT engines
            return(engines.Data.Where(e => e.Contains("Revit")).OrderBy(e => e).ToList <string>());
        }
        public async Task <dynamic> CreateBucket([FromBody] CreateBucketModel bucket)
        {
            BucketsApi buckets = new BucketsApi();
            dynamic    token   = await OAuthController.GetInternalAsync();

            buckets.Configuration.AccessToken = token.access_token;
            PostBucketsPayload bucketPayload = new PostBucketsPayload(string.Format("{0}-{1}", ClientId, bucket.bucketKey.ToLower()), null,
                                                                      PostBucketsPayload.PolicyKeyEnum.Transient);

            return(await buckets.CreateBucketAsync(bucketPayload, "US"));
        }
Ejemplo n.º 8
0
        public async Task <dynamic> DeleteObject([FromBody] DeleteObjectModel objInfo)
        {
            ObjectsApi objs  = new ObjectsApi();
            dynamic    token = await OAuthController.GetInternalAsync();

            objs.Configuration.AccessToken = token.access_token;

            await objs.DeleteObjectAsync(objInfo.bucketKey, objInfo.objectKey);

            return(Task.CompletedTask);
        }
Ejemplo n.º 9
0
        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("Only one file is alowed"); // for now, let's support just 1 file at a time
            }
            else if (req.Files.Count == 0)
            {
                throw new System.Exception("Missing file to upload");
            }


            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);
        }
Ejemplo n.º 10
0
        public async Task <dynamic> DeleteBucket([FromBody] DeleteBucketModel objInfo)
        {
            // get the bucket...

            BucketsApi Buck  = new BucketsApi();
            dynamic    token = await OAuthController.GetInternalAsync();

            Buck.Configuration.AccessToken = token.access_token;


            await Buck.DeleteBucketAsync(objInfo.bucketKey);

            return(Task.CompletedTask);
        }
        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);


            // 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,
                                                              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 <IActionResult> StartWorkItem([FromForm] StartWorkitemInput input)
        {
            // basic input validation
            string activityName       = string.Format("{0}.{1}", NickName, input.activityId);
            string browerConnectionId = input.browerConnectionId;
            string bucketKey          = input.bucketId;
            string inputFileNameOSS   = input.objectId;

            bool isCount = input.activityId.ToLower() == "countitactivity+dev";

            // 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, inputFileNameOSS),
                Headers = new Dictionary <string, string>()
                {
                    { "Authorization", "Bearer " + oauth.access_token }
                }
            };
            // 2. input json
            XrefTreeArgument inputJsonArgument = new XrefTreeArgument()
            {
                Url = "data:application/json, " + (input.data.Replace("\"", "'"))
            };

            // 3. output file
            string outputFileNameOSS = null;

            if (isCount)
            {
                outputFileNameOSS = string.Format("{0}_{1}.txt", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileNameWithoutExtension(inputFileNameOSS)); // avoid overriding
            }
            else
            {
                outputFileNameOSS = string.Format("{0}_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(inputFileNameOSS)); // 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}&bucketKey={2}&outputFileName={3}", OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"), browerConnectionId, bucketKey, outputFileNameOSS);
            WorkItem workItemSpec = new WorkItem()
            {
                ActivityId = activityName,
                Arguments  = new Dictionary <string, IArgument>()
                {
                    { "inputFile", inputFileArgument },
                    { "inputJson", inputJsonArgument },
                    { isCount? "outputTxt": "outputFile", outputFileArgument },
                    { "onComplete", new XrefTreeArgument {
                          Verb = Verb.Post, Url = callbackUrl
                      } }
                }
            };
            WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemsAsync(workItemSpec);

            return(Ok(new { WorkItemId = workItemStatus.Id }));
        }