예제 #1
0
        public async Task <IActionResult> OnCallback(string id, string outputFileName, string name, string type, [FromBody] dynamic body)
        {
            try
            {
                dynamic oauth = await OAuthController.GetInternalAsync();

                string bucketkey = NickName.ToLower() + "-designautomation";

                ObjectsApi objectsApi = new ObjectsApi();
                objectsApi.Configuration.AccessToken = oauth.access_token;
                dynamic objIPT = await objectsApi.GetObjectDetailsAsync(bucketkey, outputFileName);

                dynamic urnIPT = null;
                if (type == "part")
                {
                    urnIPT = TranslateObject(objIPT, outputFileName, false);
                }
                else if (type == "assembly")
                {
                    urnIPT = TranslateObject(objIPT, name + ".iam", true);
                }

                await _hubContext.Clients.Client(id).SendAsync("onComplete", (string)await urnIPT);

                //generate a signed URL to download the result file and send to the client
                dynamic signedUrl = await objectsApi.CreateSignedResourceAsyncWithHttpInfo(NickName.ToLower() + "-designautomation", outputFileName, new PostBucketsSigned(10), "read");

                await _hubContext.Clients.Client(id).SendAsync("downloadResult", (string)(signedUrl.Data.signedUrl));
            }
            catch {
            }

            // ALWAYS return ok (200)
            return(Ok());
        }
예제 #2
0
        public async Task <ActionResult <IList <string> > > GetFileInBucket()
        {
            dynamic oauth = await OAuthController.GetInternalAsync();

            // define Engines API
            string     bucketKey = NickName.ToLower() + "_designautomation";
            ObjectsApi objects   = new ObjectsApi();

            objects.Configuration.AccessToken = oauth.access_token;

            try
            {
                dynamic response = await objects.GetObjectsAsyncWithHttpInfo(bucketKey);

                IDictionary <string, dynamic> dict = response.Data.Dictionary["items"].Dictionary;
                List <string> list = new List <string>();
                foreach (dynamic item in dict)
                {
                    list.Add(item.Value.Dictionary["objectKey"]);
                }

                return(Ok(list)); // return list of objects in bucket
            }
            catch
            {
                return(BadRequest());
            }
        }
예제 #3
0
        public async Task <IActionResult> OnCallbackExractParams(string id, string outputFileName, [FromBody] dynamic body)
        {
            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);

                ObjectsApi objectsApi = new ObjectsApi();
                dynamic    parameters = await objectsApi.GetObjectAsyncWithHttpInfo(NickName.ToLower() + "_designautomation", outputFileName);

                string data;
                using (StreamReader reader = new StreamReader(parameters.Data))
                    data = reader.ReadToEnd();

                await _hubContext.Clients.Client(id).SendAsync("onParameters", data);
            }
            catch (Exception e) { }

            // ALWAYS return ok (200)
            return(Ok());
        }
예제 #4
0
        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));
        }
예제 #5
0
        private async Task <XrefTreeArgument> BuildUploadURL(string resultFilename)
        {
            string    bucketName     = "revitdesigncheck" + NickName.ToLower();
            var       awsCredentials = new Amazon.Runtime.BasicAWSCredentials(Credentials.GetAppSetting("AWS_ACCESS_KEY"), Credentials.GetAppSetting("AWS_SECRET_KEY"));
            IAmazonS3 client         = new AmazonS3Client(awsCredentials, Amazon.RegionEndpoint.USWest2);

            if (!await client.DoesS3BucketExistAsync(bucketName))
            {
                await client.EnsureBucketExistsAsync(bucketName);
            }

            Dictionary <string, object> props = new Dictionary <string, object>();

            props.Add("Verb", "PUT");
            Uri uploadToS3 = new Uri(client.GeneratePreSignedURL(bucketName, resultFilename, DateTime.Now.AddMinutes(10), props));

            return(new XrefTreeArgument()
            {
                Url = uploadToS3.ToString(),
                Verb = Verb.Put
            });
        }
        private async Task <XrefTreeArgument> BuildUploadURL(string resultFilename)
        {
            string     bucketName = "revitdesigncheck" + NickName.ToLower();
            BucketsApi buckets    = new BucketsApi();
            dynamic    token      = await Credentials.Get2LeggedTokenAsync(new Scope[] { Scope.BucketCreate, Scope.DataWrite });

            buckets.Configuration.AccessToken = token.access_token;
            PostBucketsPayload bucketPayload = new PostBucketsPayload(bucketName, null, PostBucketsPayload.PolicyKeyEnum.Transient);

            try
            {
                await buckets.CreateBucketAsync(bucketPayload, "US");
            }
            catch { }

            ObjectsApi objects   = new ObjectsApi();
            dynamic    signedUrl = await objects.CreateSignedResourceAsyncWithHttpInfo(bucketName, resultFilename, new PostBucketsSigned(5), "readwrite");

            return(new XrefTreeArgument()
            {
                Url = (string)(signedUrl.Data.signedUrl),
                Verb = Verb.Put
            });
        }
        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 }));
        }
예제 #8
0
        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> OnCallback(string id, string outputFileName, string bucketKey, [FromBody] dynamic body)
        {
            try
            {
                // Webhook はすぐに戻るはずです。Hangfireを使用してジョブをスケジュールできます。
                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);

                ObjectsApi objectsApi = new ObjectsApi();
                dynamic    signedUrl  = await objectsApi.CreateSignedResourceAsyncWithHttpInfo(NickName.ToLower() + "_designautomation", outputFileName, new PostBucketsSigned(10), "read");

                await _hubContext.Clients.Client(id).SendAsync("downloadResult", (string)(signedUrl.Data.signedUrl));

                dynamic objectDetail = await objectsApi.GetObjectDetailsAsyncWithHttpInfo(bucketKey, outputFileName);

                Encoding encoding  = Encoding.UTF8;
                string   objectUrn = (string)(objectDetail.Data.objectId);
                byte[]   bytes     = encoding.GetBytes(objectUrn);
                string   urn       = System.Convert.ToBase64String(bytes);
                await _hubContext.Clients.Client(id).SendAsync("translateResult", urn);
            }
            catch (Exception e) { }

            // 必ずOKを返す (200)
            return(Ok());
        }
예제 #10
0
        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));
            }
        }
        private void LoginConnect()
        {
            if (!string.IsNullOrEmpty(userId) && !string.IsNullOrEmpty(nickName))
            {
                ShowConnectProgress = true;

                var finalProfileUrl = !string.IsNullOrEmpty(profileUrl) ? profileUrl :
                                      ("https://dummyimage.com/40x40/a1a1a1/000000.png&text=" + NickName.ToLower()[0]);
                _sendbird.GetAPI().Connect(userId, nickName, finalProfileUrl);
                LocalCache.CurrentNickName = nickName;
            }
        }
        private async Task <IActionResult> PostGoodPractices(string projectId, int version, string hubId, string rvt, string guid)
        {
            // basic input validation
            string activityName = "cyBnhhxpfsbhGC1jv4CdyDSLwj912JA4.UpdateRVTParamActivity+dev";
            //var projectId = (string)rvt.projectId;
            //var version = (int)rvt.version;

            // 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 { };

            // prepare workitem arguments
            // 1. input file
            //var guid = (string)rvt.guid;
            var rvtName = rvt;//(string)rvt.rvtName;
            XrefTreeArgument inputFileArgument = new XrefTreeArgument()
            {
                Url       = $"https://developer.api.autodesk.com/oss/v2/buckets/wip.dm.prod/objects/{guid}",
                LocalName = "myzip",
                PathInZip = rvtName,
                Headers   = new Dictionary <string, string>()
                {
                    { "Authorization", "Bearer " + oauth.access_token }
                }
            };

            // 2. input json
            dynamic inputJson = new JObject();

            inputJson.HubId     = hubId;
            inputJson.ProjectId = projectId;
            inputJson.Version   = version;
            var 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("OutputFile.json")); // 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/mongo?id={1}&outputFileName={2}", Credentials.GetAppSetting("FORGE_WEBHOOK_URL"), "", 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 }));
        }
예제 #13
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 }));
        }
예제 #14
0
        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 }));
        }
        public async Task <IActionResult> OnCallback(string id, string outputFileName, [FromBody] dynamic body)
        {
            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);

                // send the result output log to the client
                byte[] bs     = client.DownloadData(request);
                string report = System.Text.Encoding.Default.GetString(bs);
                await _hubContext.Clients.Client(id).SendAsync("onComplete", report);

                // generate a signed URL to download the result file and send to the client
                ObjectsApi objectsApi = new ObjectsApi();
                dynamic    signedUrl  = await objectsApi.CreateSignedResourceAsyncWithHttpInfo(NickName.ToLower() + "-designautomation", outputFileName, new PostBucketsSigned(10), "read");

                await _hubContext.Clients.Client(id).SendAsync("downloadResult", (string)(signedUrl.Data.signedUrl));
            }
            catch { }

            // ALWAYS return ok (200)
            return(Ok());
        }
예제 #16
0
        public async Task <IActionResult> StartWorkitem([FromForm] StartWorkitemInput input)
        {
            // basic input validation
            WorkItemStatus workItemStatus = null;
            JObject        workItemData   = JObject.Parse(input.data);

            string        browerConnectionId = workItemData["browerConnectionId"].Value <string>();
            string        fileType           = workItemData["fileType"].Value <string>();
            string        activityName       = string.Format("{0}.{1}", NickName, workItemData["activityName"].Value <string>());
            List <string> activityList       = await GetDefinedActivities();

            if (!activityList.Contains(workItemData["activityName"].Value <string>()))
            {
                await CreateAppBundle();
                await CreateActivity(fileType);
            }
            if (fileType == "assembly")
            {
                string path = _env.ContentRootPath;
                Trace.TraceInformation("Zipping started");
                string fileSavePath = await CreateZipFileStreamAsync(input.inputFile, input.inputFiles, path);

                // 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(fileSavePath)); // 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),
                    PathInZip = input.inputFile.FileName,
                    Headers   = new Dictionary <string, string>()
                    {
                        { "Authorization", "Bearer " + oauth.access_token }
                    }
                };

                // 2. output file
                //string outputFileNameOSS = string.Format("{0}_output_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputFile.FileName)); // avoid overriding
                //string outputFileNameOSS = string.Format("{0}_output_{1}.zip", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputFile.FileName)); // avoid overriding
                string           outputFileNameOSS  = string.Format("{0}_output_{1}.zip", 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}&name={3}&type={4}", OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"), browerConnectionId, outputFileNameOSS, Path.GetFileNameWithoutExtension(input.inputFile.FileName), fileType);
                WorkItem workItemSpec = new WorkItem()
                {
                    ActivityId = activityName,
                    Arguments  = new Dictionary <string, IArgument>()
                    {
                        { "inputFile", inputFileArgument },
                        { "outputFile", outputFileArgument },
                        { "onComplete", new XrefTreeArgument {
                              Verb = Verb.Post, Url = callbackUrl
                          } }
                    }
                };
                workItemStatus = await _designAutomation.CreateWorkItemAsync(workItemSpec);
            }
            else if (fileType == "part")
            {
                // 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. output file
                //string outputFileNameOSS = string.Format("{0}_output_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputFile.FileName)); // avoid overriding
                string           outputFileNameOSS  = string.Format("{0}_output_{1}.ipt", 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}&name={3}&type={4}", OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"), browerConnectionId, outputFileNameOSS, "", fileType);
                WorkItem workItemSpec = new WorkItem()
                {
                    ActivityId = activityName,
                    Arguments  = new Dictionary <string, IArgument>()
                    {
                        { "inputFile", inputFileArgument },
                        { "outputFile", outputFileArgument },
                        { "onComplete", new XrefTreeArgument {
                              Verb = Verb.Post, Url = callbackUrl
                          } }
                    }
                };
                workItemStatus = await _designAutomation.CreateWorkItemAsync(workItemSpec);
            }



            return(Ok(new { WorkItemId = workItemStatus.Id }));
        }
예제 #17
0
        public virtual void JoinChannels()
        {
            if (Status.IsStopping || CreateChannel == null)
            {
                return;
            }

            var channels = Config.Parameters.StringArrayValue("Channels").Select(chan => "#" +
                                                                                 (!IsChannelCaseSensitive ? chan.ToLower() : chan).Replace("#", "")
                                                                                 ).ToArray();

            if (!String.IsNullOrWhiteSpace(NickName) &&
                !String.IsNullOrWhiteSpace(Config.GetParameterValue("Username") as string))
            {
                if (!channels.Contains("#" + (!IsChannelCaseSensitive ? NickName.ToLower() : NickName)))
                {
                    channels = channels.Union(new String[] { (!IsChannelCaseSensitive ? NickName.ToLower(): NickName) }).ToArray();
                }
            }

            foreach (var channel in channels)
            {
                var chatChannel = CreateChannel();
                chatChannel.ReadMessage   = ReadMessage;
                chatChannel.LeaveCallback = (leaveChannel) =>
                {
                    Log.WriteInfo("{0} leaving channel {1}", Config.ChatName, channel);

                    leaveChannel.ChannelStats.ViewersCount = 0;
                    leaveChannel.Chat.UpdateStats();

                    if (Status.IsLoginFailed)
                    {
                        IsAnonymous = true;
                    }

                    lock (toolTipLock)
                    {
                        UI.Dispatch(() => Status.ToolTips.RemoveAll(tooltip => tooltip.Header == channel));
                    }

                    lock (channelsLock)
                    {
                        ChatChannels.RemoveAll(chan => chan == null);
                        ChatChannels.RemoveAll(item => item.ChannelName == leaveChannel.ChannelName);
                    }

                    if (RemoveChannel != null)
                    {
                        RemoveChannel(leaveChannel.ChannelName, this);
                    }

                    if (Status.IsStopping)
                    {
                        return;
                    }

                    lock ( channelsLock  )
                    {
                        if (ChatChannels.Count <= 0)
                        {
                            Status.ResetToDefault();
                            Status.IsConnected  = false;
                            Status.IsConnecting = true;
                        }
                    }
                    Thread.Sleep(1000);
                    lock (joinLock)
                        JoinChannel(chatChannel, channel);
                };
                lock (joinLock)
                    Task.Run(() => JoinChannel(chatChannel, channel));
            }
        }