Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Possibility to Abort Upload Process at the Initial Event #221

Open
MGAjinugrh opened this issue Jan 19, 2024 · 4 comments
Open

Possibility to Abort Upload Process at the Initial Event #221

MGAjinugrh opened this issue Jan 19, 2024 · 4 comments

Comments

@MGAjinugrh
Copy link

Hi! I am back with another question!

As the name suggest, this time I would like to know if there a way we can abort the client-initiated upload progress from the tusdotnet side. For context, I currently trying to implement functionality to check at the initial event, if the proposed upload file is already exists on the destination then we skip the entire upload process and informed the client. Client will be using the tus-js-client.

Here I attach the relevant part for the server-side (tusdotnet 3.1)

            app.UseTus(ctx =>
            {
                var uploadDir = GetUploadStoreDir(ctx.Request.Query); //composing upload destination
                string uploadEndpoint = "/upload";
                return new DefaultTusConfiguration
                {
                    UrlPath = uploadEndpoint,
                    Store = new TusDiskStore(uploadDir),
                    Events = new Events
                    {
                        OnAuthorizeAsync = authCtx => //initial event as I read in the git documentation (cmiiw)
                        {
                            if (!string.IsNullOrWhiteSpace(uploadDir))
                            {
                                if(!Directory.Exists(Path.GetFullPath(uploadDir)))
                                    Directory.CreateDirectory(uploadDir); //create the respective destination directory before all processes
                            
                                if(authCtx.HttpContext.Request.Query.TryGetValue("filename", out var filename))
                                {
                                    string uploadedFile = Path.GetFullPath($"{uploadDir}/{filename}");
                                    if (File.Exists(uploadedFile))
                                    {
                                        File.Delete(uploadedFile);

                                        MyCustomReturnClass result = new MyCustomReturnClass(){
                                            state = 2 //indicating file exists
                                            message = "File already exists on the server, skipping upload process"
                                        };
                                        
                                        //how can we return the result from here and pass it to the onSuccess event on the to the tus-js-client at the client-side?
                                    }

                                }
                            }

                            //other codes related to authentication

                            return Task.CompletedTask;
                        },
                        OnCreateCompleteAsync = createCompctx =>
                        {
                            // tusdotnet will automatically create a url in the form of "/{uploadEndpoint}/<file id>" but since we also need
                            // the query params here we need to add it to the url

                            if (createCompctx.HttpContext.Request.Query.TryGetValue("filepath", out var filepath) &&
                                createCompctx.HttpContext.Request.Query.TryGetValue("filename", out var filename))
                            {
                                createCompctx.SetUploadUrl(new Uri($"{uploadEndpoint}/{createCompctx.FileId}?filepath={filepath}&filename={filename}", UriKind.Relative));
                            }

                            return Task.CompletedTask;
                        },
                        OnFileCompleteAsync = async fileCompCtx =>
                        {
                            ResumableUploadFacade tusFacade = new ResumableUploadFacade(_logger, _configProvider, _hubContext, _constantsSettings, _httpClientFactory);
                            ITusFile file = await fileCompCtx.GetFileAsync();

                            MyCustomReturnClass result = await tusFacade.BuildFilePlacementAsync(file, uploadDir);

                            //how can we return the result from here and pass it to the onSuccess event on the to the tus-js-client at the client-side?
                        }
                    }
                };
            });
@smatsson
Copy link
Collaborator

Hi!

You can call authCtx.FailRequest(HttpStatusCode, string) in the OnAuthorize callback to return an error to the client. The same applies to all OnBeforeX callbacks. See https://github.com/tusdotnet/tusdotnet/wiki/OnAuthorizeAsync-event

It seems like you wish to use the filename as the ID instead of the generated one. If so, you could write your own file id provider that uses the filename as the key: https://github.com/tusdotnet/tusdotnet/wiki/Custom-File-Id-Provider

//how can we return the result from here and pass it to the onSuccess event on the to the tus-js-client at the client-side?

You need to pass the data as a header back to the client as the tus protocol is very strict with the status code for the PATCH request that updates the file (204 No Content i.e. no body allowed)

@MGAjinugrh
Copy link
Author

Hi! Thank you for all the suggestions. Looks like currently I am able to return the 204 response from the server with some info on the header. But I think I need to go check the events at the client-side because I've tried to capture the response on both onSuccess & onError but still unable to trigger the execution.

@MGAjinugrh
Copy link
Author

Looks like trying to return the FailRequest from the OnAuthorizeAsync event resulted in the condition that the FileId is not being recognized which leads to the result being catch by the onError event on the client-side.

From what I understand, this happen because at the OnAuthorizeAsync, the FileId has yet to be generated.

Error: tus: invalid or missing Location header, originated from request (method: POST, url: /upload?filepath=myPath&filename=myFile.zip, response code: 204, response text: , request id: n/a)

@smatsson
Copy link
Collaborator

Could you give me some code showing what you are trying to do? If you run FailRequest it will stop the execution of the current request. The error indicates that you used FailRequest with 204 as the status code. As 204 is a success code but there is no Location header returned (as you aborted the request) the client will consider this an error and fire the error event.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants