예제 #1
0
        public async Task <dynamic> DownloadObject([FromBody] DownloadFile input)
        {
            // get the bucket
            dynamic oauth = await OAuthController.GetInternalAsync();

            ObjectsApi objects = new ObjectsApi();

            objects.Configuration.AccessToken = oauth.access_token;

            // collect information about file
            string bucketKey      = input.bucketKey;
            string fileToDownload = input.fileToDownload;

            PostBucketsSigned postBucketsSigned = new PostBucketsSigned(20);

            try
            {
                dynamic result = await objects.CreateSignedResourceAsync(bucketKey, fileToDownload, postBucketsSigned);

                return(result);
            }
            catch (Exception ex) { }

            return(null);
        }
예제 #2
0
        /// <summary>
        /// The RunAsync.
        /// </summary>
        /// <returns>The <see cref="Task"/>.</returns>
        public async Task RunAsync()
        {
            if (string.IsNullOrEmpty(Owner))
            {
                Console.WriteLine("Please provide non-empty Owner.");
                return;
            }

            if (string.IsNullOrEmpty(UploadUrl))
            {
                Console.WriteLine($"Creating Bucket....");
                dynamic oauth = await GetInternalAsync();

                // 1. ensure bucket existis
                string bucketKey = Owner.ToLower();
                Console.WriteLine($"Creating Bucket {bucketKey}....");
                BucketsApi buckets = new BucketsApi();
                buckets.Configuration.AccessToken = oauth.access_token;
                try
                {
                    PostBucketsPayload bucketPayload = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient);
                    dynamic            bucketsRes    = await buckets.CreateBucketAsync(bucketPayload, "US");
                }
                catch
                {
                    // in case bucket already exists
                    Console.WriteLine($"\tBucket {bucketKey} exists");
                };
                ObjectsApi objects = new ObjectsApi();
                objects.Configuration.AccessToken = oauth.access_token;

                //2. Upload input file and get signed URL
                string inputFileNameOSS = string.Format("{0}_input_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(FilePaths.InputFile));
                Console.WriteLine($"Uploading input file {inputFileNameOSS} to {bucketKey}..... ");
                using (StreamReader streamReader = new StreamReader(FilePaths.InputFile))
                {
                    dynamic res = await objects.UploadObjectAsync(bucketKey, inputFileNameOSS, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream");
                }



                try
                {
                    PostBucketsSigned bucketsSigned = new PostBucketsSigned(60);
                    dynamic           signedResp    = await objects.CreateSignedResourceAsync(bucketKey, inputFileNameOSS, bucketsSigned, "read");

                    downloadUrl = signedResp.signedUrl;
                    Console.WriteLine($"\tSuccess: File uploaded to... \n\t{downloadUrl}");
                }
                catch { }
            }

            if (!await SetupOwnerAsync())
            {
                Console.WriteLine("Exiting.");
                return;
            }

            await SubmitWorkItemAsync(ActivityName);
        }
        public async Task <IActionResult> StartWorkitem()
        {
            // basic input validation



            try
            {
                dynamic oauth = await GetInternalASync();

                ObjectsApi objectsApi = new ObjectsApi();
                objectsApi.Configuration.AccessToken = oauth.access_token;
                PostBucketsSigned bucketsSigned = new PostBucketsSigned(60);
                dynamic           signedResp    = await objectsApi.CreateSignedResourceAsync(BucketKey, inputFileNameOSS, bucketsSigned, "read");

                DownloadUrl = signedResp.signedUrl;
                signedResp  = await objectsApi.CreateSignedResourceAsync(BucketKey, outputFileNameOSS, bucketsSigned, "readwrite");

                UploadUrl = signedResp.signedUrl;
                Console.WriteLine($"\tSuccess: signed resource for input.zip created!\n\t{DownloadUrl}");
                Console.WriteLine($"\tSuccess: signed resource for result.pdf created!\n\t{UploadUrl}");
            }
            catch { }
            Console.WriteLine("Submitting up workitem...");
            string callbackUrl    = string.Format("{0}/api/forge/designautomation/callback?id={1}&outputFileName={2}", FORGE_WEBHOOK_URL, browserConnectionId, outputFileNameOSS);
            var    workItemStatus = await api.CreateWorkItemAsync(
                new Autodesk.Forge.DesignAutomation.Model.WorkItem()
            {
                ActivityId = ActivityName,
                Arguments  = new Dictionary <string, IArgument>()
                {
                    {
                        "inputFile",
                        new XrefTreeArgument()
                        {
                            Url = "http://download.autodesk.com/us/support/files/autocad_2015_templates/acad.dwt"
                        }
                    }, {
                        "inputZip",
                        new XrefTreeArgument()
                        {
                            Url = DownloadUrl, Verb = Verb.Get, LocalName = "export"
                        }
                    }, {
                        "Result",
                        new XrefTreeArgument()
                        {
                            Verb = Verb.Put, Url = UploadUrl
                        }
                    },
                    { "onComplete",
                      new XrefTreeArgument {
                          Verb = Verb.Post, Url = callbackUrl
                      } }
                }
            });

            return(Ok(new { WorkItemId = workItemStatus.Id }));
        }
        /// <summary>
        /// Generate signed URL for the OSS object.
        /// </summary>
        private static async Task <string> GetSignedUrl(IObjectsApi api, string bucketKey, string objectName,
                                                        ObjectAccess access = ObjectAccess.Read, int minutesExpiration = 30)
        {
            var     signature = new PostBucketsSigned(minutesExpiration);
            dynamic result    = await api.CreateSignedResourceAsync(bucketKey, objectName, signature, AsString(access));

            return(result.signedUrl);
        }
예제 #5
0
        public async Task RunAsync()
        {
            if (string.IsNullOrEmpty(Owner))
            {
                Console.WriteLine("Please provide non-empty Owner.");
                return;
            }

            if (string.IsNullOrEmpty(UploadUrl))
            {
                Console.WriteLine("Creating Bucket and OSS Object");


                dynamic oauth = await GetInternalAsync();

                // 1. ensure bucket existis
                string     bucketKey = Owner.ToLower();
                BucketsApi buckets   = new BucketsApi();
                buckets.Configuration.AccessToken = oauth.access_token;
                dynamic bucketsRes = null;
                try
                {
                    PostBucketsPayload bucketPayload = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient);
                    bucketsRes = await buckets.CreateBucketAsync(bucketPayload, "US");
                }
                catch {
                    Console.WriteLine($"\tBucket {bucketKey} exists");
                }; // in case bucket already exists
                string     outputFileNameOSS = "output.zip";
                ObjectsApi objects           = new ObjectsApi();
                objects.Configuration.AccessToken = oauth.access_token;
                try
                {
                    PostBucketsSigned bucketsSigned = new PostBucketsSigned(60);
                    dynamic           signedResp    = await objects.CreateSignedResourceAsync(bucketKey, outputFileNameOSS, bucketsSigned, "readwrite");

                    UploadUrl = signedResp.signedUrl;
                }
                catch {}
            }

            if (!await SetupOwnerAsync())
            {
                Console.WriteLine("Exiting.");
                return;
            }

            var myApp = await SetupAppBundleAsync();

            var myActivity = await SetupActivityAsync(myApp);

            await SubmitWorkItemAsync(myActivity);
        }
예제 #6
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "workitem")] HttpRequest req,
            [Table("token", "token", "token", Connection = "StorageConnectionString")] Token token,
            [Table("workItems", Connection = "StorageConnectionString")] IAsyncCollector <WorkItemStatusEntity> workItemsTable,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed CreateWorkItem.");

            try
            {
                Autodesk.Forge.Client.Configuration.Default.AccessToken = token.ForgeToken.access_token;
                // Parse the body of the request
                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                WorkItemDescription workItemDescription = JsonConvert.DeserializeObject <WorkItemDescription>(requestBody);

                int existingCredits = await _utilities.GetConversionCredits(workItemDescription.userId);

                if (existingCredits > 0)
                {
                    // Create two signed URLs to upload the file to the activity and download the result
                    ObjectsApi        apiInstance           = new ObjectsApi();
                    string            rvtBucketKey          = Environment.GetEnvironmentVariable("rvtStorageKey"); // string | URL-encoded bucket key
                    string            ifcBucketKey          = Environment.GetEnvironmentVariable("ifcStorageKey"); // string | URL-encoded bucket key
                    string            inputObjectName       = workItemDescription.inputObjectName;                 // string | URL-encoded object name
                    string            outputObjectName      = workItemDescription.outputObjectName;
                    string            onCompleteCallbackUrl = Environment.GetEnvironmentVariable("api_uri") + "/api/onworkitemcomplete";
                    PostBucketsSigned postBucketsSigned     = new PostBucketsSigned(60 * 24 * 30);

                    DynamicJsonResponse dynamicJsonResponseDownload = await apiInstance.CreateSignedResourceAsync(rvtBucketKey, inputObjectName, postBucketsSigned, "read");

                    PostObjectSigned    downloadSigned            = dynamicJsonResponseDownload.ToObject <PostObjectSigned>();
                    DynamicJsonResponse dynamicJsonResponseUpload = await apiInstance.CreateSignedResourceAsync(ifcBucketKey, outputObjectName, postBucketsSigned, "readwrite");

                    PostObjectSigned uploadSigned = dynamicJsonResponseUpload.ToObject <PostObjectSigned>();

                    Autodesk.Forge.DesignAutomation.Model.WorkItem workItem = new Autodesk.Forge.DesignAutomation.Model.WorkItem()
                    {
                        ActivityId = workItemDescription.activityId,
                        Arguments  = new Dictionary <string, IArgument>
                        {
                            { "rvtFile", new XrefTreeArgument()
                              {
                                  Url = downloadSigned.SignedUrl
                              } },
                            { "result", new XrefTreeArgument {
                                  Verb = Verb.Put, Url = uploadSigned.SignedUrl
                              } },
                            { "onComplete", new XrefTreeArgument {
                                  Verb = Verb.Post, Url = onCompleteCallbackUrl
                              } }
                        }
                    };

                    Autodesk.Forge.Core.ApiResponse <WorkItemStatus> workItemResponse = await _workItemApi.CreateWorkItemAsync(workItem);

                    // ApiResponse<Page<string>> page = await _engineApi.GetEnginesAsync();
                    WorkItemStatus workItemStatusCreationResponse = workItemResponse.Content;

                    WorkItemStatusEntity WorkItemStatusObject = Mappings.ToWorkItemStatusEntity(
                        workItemStatusCreationResponse,
                        workItemDescription.userId,
                        workItemDescription.fileSize,
                        workItemDescription.version,
                        workItemDescription.fileName,
                        uploadSigned.SignedUrl,
                        downloadSigned.SignedUrl);

                    await workItemsTable.AddAsync(WorkItemStatusObject);

                    WorkItemStatusResponse workItemStatusResponse = new WorkItemStatusResponse()
                    {
                        WorkItemId             = workItemResponse.Content.Id,
                        OutputUrl              = uploadSigned.SignedUrl,
                        WorkItemCreationStatus = WorkItemCreationStatus.Created
                    };

                    return(new OkObjectResult(workItemStatusResponse));
                }
                else
                {
                    WorkItemStatusResponse workItemStatusResponse = new WorkItemStatusResponse()
                    {
                        WorkItemId             = null,
                        OutputUrl              = null,
                        WorkItemCreationStatus = WorkItemCreationStatus.NotEnoughCredit
                    };

                    return(new OkObjectResult(workItemStatusResponse));
                }
            }
            catch (Exception ex)
            {
                return(new BadRequestObjectResult(ex));
            }
        }
예제 #7
0
        /// <summary>
        /// The RunAsync.
        /// </summary>
        /// <returns>The <see cref="Task"/>.</returns>
        public async Task RunAsync()
        {
            if (string.IsNullOrEmpty(Owner))
            {
                Console.WriteLine("Please provide non-empty Owner.");
                return;
            }

            if (string.IsNullOrEmpty(UploadUrl))
            {
                Console.WriteLine("Creating Bucket and OSS Object");


                dynamic oauth = await GetInternalAsync();

                // 1. ensure bucket exists

                BucketsApi buckets = new BucketsApi();
                buckets.Configuration.AccessToken = oauth.access_token;
                try
                {
                    PostBucketsPayload bucketPayload = new PostBucketsPayload(BucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient);
                    dynamic            bucketsRes    = await buckets.CreateBucketAsync(bucketPayload, "US");
                }
                catch
                {
                    // in case bucket already exists
                    Console.WriteLine($"\tBucket {BucketKey} exists");
                };
                ObjectsApi objectsApi = new ObjectsApi();
                objectsApi.Configuration.AccessToken = oauth.access_token;



                //2. Upload input file and get signed URL

                long fileSize       = (new FileInfo(FilePaths.InputFile)).Length;
                long chunkSize      = 2 * 1024 * 1024; // 100Kb
                int  numberOfChunks = (int)Math.Round((double)(fileSize / chunkSize)) + 1;
                var  options        = new ProgressBarOptions
                {
                    ProgressCharacter   = '#',
                    ProgressBarOnBottom = false,
                    ForegroundColorDone = ConsoleColor.Green,
                    ForegroundColor     = ConsoleColor.White
                };

                using var pbar = new ProgressBar(numberOfChunks, $"Uploading input file {inputFileNameOSS} to {BucketKey}..... ", options);
                long start = 0;
                chunkSize = (numberOfChunks > 1 ? chunkSize : fileSize);
                long   end       = chunkSize;
                string sessionId = Guid.NewGuid().ToString();
                // upload one chunk at a time
                using BinaryReader reader = new BinaryReader(new FileStream(FilePaths.InputFile, FileMode.Open));
                for (int chunkIndex = 0; chunkIndex < numberOfChunks; chunkIndex++)
                {
                    string range = string.Format("bytes {0}-{1}/{2}", start, end, fileSize);

                    long         numberOfBytes = chunkSize + 1;
                    byte[]       fileBytes     = new byte[numberOfBytes];
                    MemoryStream memoryStream  = new MemoryStream(fileBytes);
                    reader.BaseStream.Seek((int)start, SeekOrigin.Begin);
                    int count = reader.Read(fileBytes, 0, (int)numberOfBytes);
                    memoryStream.Write(fileBytes, 0, (int)numberOfBytes);
                    memoryStream.Position = 0;

                    dynamic chunkUploadResponse = await objectsApi.UploadChunkAsyncWithHttpInfo(BucketKey, inputFileNameOSS, (int)numberOfBytes, range, sessionId, memoryStream);

                    start     = end + 1;
                    chunkSize = ((start + chunkSize > fileSize) ? fileSize - start - 1 : chunkSize);
                    end       = start + chunkSize;
                    double size       = chunkIndex == 0 ? chunkSize / 1024 : (chunkIndex * chunkSize) / 1024;
                    var    CustomText = $"{(fileSize-chunkSize)/ 1024} Kb uploaded...";
                    pbar.Tick(CustomText);
                }



                try
                {
                    PostBucketsSigned bucketsSigned = new PostBucketsSigned(60);
                    dynamic           signedResp    = await objectsApi.CreateSignedResourceAsync(BucketKey, inputFileNameOSS, bucketsSigned, "read");

                    DownloadUrl = signedResp.signedUrl;
                    signedResp  = await objectsApi.CreateSignedResourceAsync(BucketKey, outputFileNameOSS, bucketsSigned, "readwrite");

                    UploadUrl = signedResp.signedUrl;
                    Console.WriteLine($"\tSuccess: signed resource for input.zip created!\n\t{DownloadUrl}");
                    Console.WriteLine($"\tSuccess: signed resource for result.pdf created!\n\t{UploadUrl}");
                }
                catch { }
            }

            if (!await SetupOwnerAsync())
            {
                Console.WriteLine("Exiting.");
                return;
            }

            var myApp = await SetupAppBundleAsync();

            var myActivity = await SetupActivityAsync(myApp);

            await SubmitWorkItemAsync(myActivity);
        }