Пример #1
0
        public async Task <IActionResult> AddVersion([FromForm] string request, IFormFile file)
        {
            try
            {
                if (file == null || file.Length == 0)
                {
                    return(BadRequest());
                }

                var userKey = _contextAccessor.UserKeyFromContext();
                var addVersionToFileRequest = JsonSerializer.Deserialize <AddVersionToFileRequest>(request, new JsonSerializerOptions {
                    PropertyNameCaseInsensitive = true
                });
                bool userCanAccessFile = await UserCanAccessFile(userKey, addVersionToFileRequest.Key, _hiarcDatabase, AccessLevelGroup.UploadOnlyOrHigher);

                if (userCanAccessFile)
                {
                    var originalFile = await _hiarcDatabase.GetFile(addVersionToFileRequest.Key);

                    // check that new version is the same file extension as the original
                    if (Path.GetExtension(originalFile.Name) != Path.GetExtension(file.FileName))
                    {
                        _logger.LogError("Attemped to upload new version of file with incorrect file extension");
                        return(BadRequest($"New version file extension must be '{Path.GetExtension(originalFile.Name)}'"));
                    }

                    IStorageService storageService;
                    if (addVersionToFileRequest.StorageService == null)
                    {
                        // if the request StorageService property is null then use the StorageService from the previous version (i.e. stays in the same service)
                        var latestFileVersion = await _hiarcDatabase.GetLatestVersionForFile(addVersionToFileRequest.Key);

                        storageService = _storageServiceProvider.Service(latestFileVersion.StorageService);
                    }
                    else
                    {
                        storageService = _storageServiceProvider.Service(addVersionToFileRequest.StorageService);
                    }

                    IFileInformation versionInfo = null;
                    using var stream = file.OpenReadStream();
                    versionInfo      = await storageService.StoreFile(stream);

                    var updatedFile = await _hiarcDatabase.AddVersionToFile(originalFile.Key, storageService.Name, versionInfo.StorageIdentifier, userKey);

                    var uri = $"{_hiarcSettings.BaseUri}/files/{originalFile.Key}";

                    return(Created(uri, updatedFile));
                }
                else
                {
                    return(StatusCode(StatusCodes.Status403Forbidden));
                }
            }
            catch (Exception ex)
            {
                return(BuildErrorResponse(ex, _logger));
            }
        }