Esempio n. 1
0
        public async Task <IActionResult> Upload(string filename)
        {
            if (string.IsNullOrWhiteSpace(filename))
            {
                return(BadRequest("`filename` query parameter must be supplied"));
            }

            var name      = Path.GetFileNameWithoutExtension(filename);
            var extension = Path.GetExtension(filename);

            var upload = new Upload
            {
                Id        = await _slugGenerator.GenerateSlugAsync(Request.HttpContext.RequestAborted),
                Name      = name,
                Extension = extension,
                OriginalFileNameWithExtension = Path.GetFileName(filename),
                MediaType    = MediaTypeHelpers.GetMediaTypeFromExtension(extension),
                CodeLanguage = CodeLanguageHelpers.GetLanageFromExtension(extension),
                Length       = Request.ContentLength.GetValueOrDefault(),
                UserId       = _userManager.GetUserId(User),
                CreatedBy    = _userManager.GetUserName(User)
            };

            await _context.Uploads.AddAsync(upload, Request.HttpContext.RequestAborted);

            await _context.SaveChangesAsync(Request.HttpContext.RequestAborted);

            await _store.WriteAllBytesAsync(upload, Request.Body, Request.HttpContext.RequestAborted);

            upload.Status = UploadStatus.Complete;

            // File is fully uploaded, don't let the user cancel this request
            await _context.SaveChangesAsync();

            return
                (new JsonResult(
                     new
            {
                id = upload.Id,
                path = Url.Page("/Upload", values: new { id = upload.Id }),
                url = Url.PageLink("/Upload", values: new { id = upload.Id }),
                delete = Url.ActionLink("DeleteUpload", values: new { id = upload.Id }),
                raw = Url.ActionLink("Raw", values: new { id = upload.Id }),
                download = Url.ActionLink("Download", values: new { id = upload.Id })
            }));
        }
Esempio n. 2
0
        private Func <IServiceProvider, DefaultTusConfiguration> CreateTusConfiguration(StorageType storageType)
        => (serviceProvider) =>
        {
            var logger = serviceProvider.GetService <ILoggerFactory>().CreateLogger <Startup>();

            return(new DefaultTusConfiguration
            {
                Store = new HoneydewTusStore(serviceProvider),
                UrlPath = "/api/tusupload",
                MetadataParsingStrategy = MetadataParsingStrategy.AllowEmptyValues,
                Events = new Events
                {
                    OnAuthorizeAsync = ctx =>
                    {
                        if (!ctx.HttpContext.User.Identity.IsAuthenticated)
                        {
                            ctx.FailRequest(HttpStatusCode.Unauthorized);
                        }

                        return Task.CompletedTask;
                    },
                    OnBeforeCreateAsync = ctx =>
                    {
                        // Partial files are not complete so we do not need to validate
                        // the metadata in our example.
                        if (ctx.FileConcatenation is FileConcatPartial)
                        {
                            return Task.CompletedTask;
                        }

                        if (!ctx.Metadata.ContainsKey("name") || ctx.Metadata["name"].HasEmptyValue || string.IsNullOrWhiteSpace(ctx.Metadata["name"].GetString(Encoding.UTF8)))
                        {
                            ctx.FailRequest("name metadata must be specified.");
                        }

                        return Task.CompletedTask;
                    },
                    OnCreateCompleteAsync = async ctx =>
                    {
                        logger.LogInformation($"Created file {ctx.FileId} using {ctx.Store.GetType().FullName}");

                        var name = ctx.Metadata["name"].GetString(Encoding.UTF8);
                        var mediaType = MediaTypeHelpers.GetMediaTypeFromMetadata(ctx.Metadata);

                        var filename = Path.GetFileNameWithoutExtension(name);
                        var extension = Path.GetExtension(name);

                        var scope = serviceProvider.CreateScope();

                        var userManager =
                            scope
                            .ServiceProvider
                            .GetService <UserManager <User> >();

                        await using var context =
                                        scope
                                        .ServiceProvider
                                        .GetService <ApplicationDbContext>();

                        await context.Uploads.AddAsync(
                            new Upload
                        {
                            Id = ctx.FileId,
                            Name = filename,
                            Extension = extension,
                            OriginalFileNameWithExtension = Path.GetFileName(name),
                            MediaType = mediaType,
                            CodeLanguage = CodeLanguageHelpers.GetLanageFromExtension(extension),
                            Length = ctx.UploadLength,
                            Metadata = ctx.HttpContext.Request.Headers[HeaderConstants.UploadMetadata],
                            UserId = userManager.GetUserId(ctx.HttpContext.User),
                            CreatedBy = userManager.GetUserName(ctx.HttpContext.User)
                        }, ctx.CancellationToken);

                        await context.SaveChangesAsync(ctx.CancellationToken);
                    },
                    OnBeforeDeleteAsync = ctx =>
                    {
                        // Can the file be deleted? If not call ctx.FailRequest(<message>);
                        return Task.CompletedTask;
                    },
                    OnDeleteCompleteAsync = ctx =>
                    {
                        logger.LogInformation($"Deleted file {ctx.FileId} using {ctx.Store.GetType().FullName}");
                        return Task.CompletedTask;
                    },
                    OnFileCompleteAsync = async ctx =>
                    {
                        logger.LogInformation($"Upload of {ctx.FileId} completed using {ctx.Store.GetType().FullName}");

                        await using var context =
                                        serviceProvider
                                        .CreateScope()
                                        .ServiceProvider
                                        .GetService <ApplicationDbContext>();

                        var upload = await context.Uploads.FindAsync(ctx.FileId);

                        upload.Status = UploadStatus.Complete;

                        // Don't want the user to be able to cancel
                        await context.SaveChangesAsync();
                    }
                },