Ejemplo n.º 1
0
        public async Task <UploadResultDto> Upload(string token, string path, Stream stream)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new BadRequestException("Missing path");
            }

            if (stream == null)
            {
                throw new BadRequestException("Missing data stream");
            }

            if (!stream.CanRead)
            {
                throw new BadRequestException("Cannot read from data stream");
            }

            var batch = await GetRunningBatchFromToken(token);

            // Check if user has enough space to upload this
            await _utils.CheckCurrentUserStorage(stream.Length);

            var entry = batch.Entries.FirstOrDefault(item => item.Path == path);

            if (entry != null)
            {
                throw new BadRequestException("Entry already uploaded");
            }

            _logger.LogInformation("Adding '{Path}' in batch '{BatchToken}'", path, batch.Token);

            var orgSlug = batch.Dataset.Organization.Slug;
            var dsSlug  = batch.Dataset.Slug;

            await _objectsManager.AddNew(orgSlug, dsSlug, path, stream);

            var info = (await _objectsManager.List(orgSlug, dsSlug, path)).FirstOrDefault();

            if (info == null)
            {
                throw new BadRequestException(
                          "Underlying object storage is not working correctly: cannot find object after adding it");
            }

            entry = new Entry
            {
                Type    = info.Type,
                Hash    = info.Hash,
                AddedOn = DateTime.Now,
                Path    = path,
                Size    = info.Size,
                Batch   = batch
            };

            await _context.AddAsync(entry);

            _logger.LogInformation("Entry added");

            await _context.SaveChangesAsync();

            _logger.LogInformation("Changes commited");

            return(new UploadResultDto
            {
                Hash = entry.Hash,
                Size = entry.Size,
                Path = entry.Path
            });
        }