public async Task <IActionResult> GetPrivateFileFromPublicId(string publicIdAndExtension) { int index = publicIdAndExtension.IndexOf('.'); if (index <= 0) { return(NotFound()); } string publicId = publicIdAndExtension.Remove(index); var fileFromRepo = await _fileRepo.GetFile(publicId); if (fileFromRepo == null) { return(NotFound()); } int userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (fileFromRepo.OwnerId != userId) { return(Unauthorized()); } // File is owned by token holder var cd = new System.Net.Mime.ContentDisposition { FileName = fileFromRepo.Name + fileFromRepo.FileExtension, Inline = true }; Response.Headers.Add("Content-Disposition", cd.ToString()); var filePath = _utilsService.GenerateFilePath(fileFromRepo.PublicId, fileFromRepo.FileExtension); return(PhysicalFile(filePath, fileFromRepo.ContentType)); }
public async Task <IActionResult> DeleteAlbum(int albumId, [FromQuery] bool removeFiles = false) { var album = await _albumRepo.GetAlbumById(albumId); if (album == null) { return(NotFound("Album with that Id was not found")); } int userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (album.OwnerId != userId) { return(Unauthorized("You dont own this album")); } if (album.UFiles.Count != 0) { // remove files if flag is set foreach (var file in album.UFiles) { if (removeFiles) { _fileRepo.Delete(file); string path = _utilsService.GenerateFilePath(file.PublicId, file.FileExtension); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } } else { file.AlbumId = null; } } if (!await _fileRepo.SaveAll()) { return(StatusCode(StatusCodes.Status500InternalServerError, new { message = "Failed saving to database" })); } } _albumRepo.Delete(album); if (!await _albumRepo.SaveAll()) { return(StatusCode(StatusCodes.Status500InternalServerError, new { message = "Failed saving to database" })); } return(Ok()); }
public async Task <IActionResult> AdminDeleteUser(int userId) { int reqUserId = this.GetRequestUserId(); if (await _userRepo.IsAdmin(reqUserId) == false) { return(Unauthorized()); } // get user var user = await _userRepo.GetUserById(userId); if (user == null) { return(NotFound()); } // Remove all files foreach (var file in user.Files) { string path = _utilsService.GenerateFilePath(file.PublicId, file.FileExtension); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } _fileRepo.Delete(file); } await _fileRepo.SaveAll(); // Remove albums foreach (var album in user.Albums) { _albumRepo.Delete(album); } await _albumRepo.SaveAll(); // Remove ApiKey await _apiKeyRepo.RemoveApiKeyByUserId(user.Id); // remove user await _userRepo.RemoveUser(user); return(Ok()); }
public async Task <ActionResult <IEnumerable <UFileReturnDto> > > UploadFiles([FromForm] UFilesReceiveDto filesReceiveDto) { if (filesReceiveDto.Files == null || filesReceiveDto.Files.Count == 0) { return(BadRequest("No files found")); } if (filesReceiveDto.Files.Count > _uploadSettings.Value.MaxFiles) { return(BadRequest($"Too many files. Max files is {_uploadSettings.Value.MaxFiles.ToString()}")); } // Serialize the info tab var infoList = filesReceiveDto.Infos == null ? null : JsonSerializer.Deserialize <List <MultiFileInfoDto> >(filesReceiveDto.Infos, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }); if (infoList != null && infoList.Count != 0 && infoList.Count != filesReceiveDto.Files.Count) { return(BadRequest("Either leave infos empty or add the same amount of info entries as files!")); } // before we do any computation or allocation foreach (var file in filesReceiveDto.Files) { if (file.Length > _uploadSettings.Value.MaxSize) { return(BadRequest( $"File too big. Maximum file size allowed is {_uploadSettings.Value.MaxSize.ToString()} bytes")); } string extension = Path.GetExtension(file.FileName); if (_uploadSettings.Value.BlockedExtensions.Any( e => e.Equals(extension, StringComparison.OrdinalIgnoreCase))) { return(BadRequest($"File extension {extension} is not allowed")); } } Album album = null; // check if specified album exists if (filesReceiveDto.AlbumId.HasValue) { album = await _albumRepo.GetAlbumById(filesReceiveDto.AlbumId.Value); if (album == null) { return(BadRequest("Album doesn't exist.")); } } int userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); // Check if user exceeded upload limit if (_limitSettings.Value.MaxFiles != 0 && await _fileRepo.GetFileCount(userId) >= _limitSettings.Value.MaxFiles) { return(BadRequest($"You have reached the maximum file limit of {_limitSettings.Value.MaxFiles.ToString()}")); } var userFromRepo = await _userRepo.GetUserById(userId); List <FileStreamData> fileStreams = new List <FileStreamData>(filesReceiveDto.Files.Count); List <UFile> dbFiles = new List <UFile>(filesReceiveDto.Files.Count); try { int index = 0; foreach (var file in filesReceiveDto.Files) { string extension = Path.GetExtension(file.FileName); string fileId = Guid.NewGuid().ToString(); string path = _utilsService.GenerateFilePath(fileId, extension); var fileData = new FileStreamData() { Path = path, CopyTask = null, FileStream = new FileStream(path, FileMode.Create) }; // begin entire file download and saving fileData.CopyTask = file.CopyToAsync(fileData.FileStream); fileStreams.Add(fileData); // create files for database bool isPublic = true; string filename = Path.GetFileNameWithoutExtension(file.FileName); string name = filename; if (infoList != null && infoList.Count != 0) { isPublic = infoList[index].IsPublic; name = infoList[index].Name ?? filename; } if (string.IsNullOrWhiteSpace(name)) { name = fileId; } var uFile = new UFile(fileId, isPublic, extension, file.ContentType, userFromRepo.Id, name); if (album != null) { uFile.AlbumId = album.Id; } dbFiles.Add(uFile); index++; } // now await the files one after another foreach (var file in fileStreams) { await file.CopyTask; } // now we know all files successfully downloaded and saved // add to the DB foreach (var dbFile in dbFiles) { _fileRepo.Add(dbFile); } if (!await _fileRepo.SaveAll()) { await UndoChanges(); return(BadRequest("Failed saving the files")); } var filesToReturn = _mapper.Map <IEnumerable <UFileReturnDto> >(dbFiles); return(Ok(filesToReturn)); } catch (Exception e) { await UndoChanges(); _logger.Log(LogLevel.Error, e, "Failed to save Files!"); return(BadRequest("Something failed sorry :(")); } finally { foreach (var data in fileStreams) { await data.FileStream.DisposeAsync(); data.CopyTask.Dispose(); } } async Task UndoChanges() { for (int i = 0; i < fileStreams.Count; i++) { var file = fileStreams[i]; var dbFile = dbFiles[i]; // wait in case its not finished yet await file.CopyTask; await file.FileStream.DisposeAsync(); file.CopyTask.Dispose(); // remove photo if it exists if (System.IO.File.Exists(file.Path)) { System.IO.File.Delete(file.Path); } // remove Db entries var fileFromDb = await _fileRepo.GetFile(dbFile.PublicId); if (fileFromDb != null) { _fileRepo.Delete(fileFromDb); } } await _fileRepo.SaveAll(); } }