Example #1
0
        public async Task <ActionResult <Upload> > ReceiveUploadAsync([FromHeader] string filename = null, [FromHeader] bool generateName = false)
        {
            if (string.IsNullOrWhiteSpace(filename) && string.IsNullOrWhiteSpace(Request.ContentType))
            {
                return(BadRequest());
            }

            string extension = null;
            string name      = null;

            if (string.IsNullOrWhiteSpace(filename))
            {
                if (!TryGetExtension(Request.ContentType, out extension))
                {
                    return(BadRequest());
                }

                name = GeneratorService.GenerateNextName();
            }
            else
            {
                if (!TryGetContentType(filename, out string ctype, out name, out extension))
                {
                    return(BadRequest());
                }

                if (string.IsNullOrWhiteSpace(Request.ContentType))
                {
                    Request.ContentType = ctype;
                }

                bool nameUsed = await DbContext.Uploads.AnyAsync(x => x.Name == name);

                if (nameUsed)
                {
                    if (!generateName)
                    {
                        return(Conflict("The fileName is already being used!"));
                    }

                    name = GeneratorService.GenerateNextName();
                }
            }

            var content = new MemoryStream();
            await Request.Body.CopyToAsync(content);

            string checksum  = content.GenerateChecksum();
            var    localFile = await DbContext.LocalFiles.Where(x => x.Checksum == checksum)
                               .FirstOrDefaultAsync();

            if (localFile == null)
            {
                localFile = await DataService.StoreUploadDataAsync(content);

                DbContext.Add(localFile);
            }

            var userId = Guid.Parse(User.FindFirstValue("UserId"));
            var upload = new Upload(userId, localFile.Id, name, extension, Request.ContentType);

            DbContext.Add(upload);

            await DbContext.SaveChangesAsync();

            WebhookService.QueueUpload(upload);

            return(upload);
        }