Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/bucket storage #36

Merged
merged 18 commits into from
May 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .github/workflows/maven.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ jobs:
contents: write
runs-on: ubuntu-latest

env:
AZURE_STORAGE_CONNECTION_STRING: ${{ secrets.AZURE_STORAGE_CONNECTION_STRING }}
AZURE_STORAGE_CONTAINER_NAME: ${{ secrets.AZURE_STORAGE_CONTAINER_NAME }}
AZURE_STORAGE_URL: ${{ secrets.AZURE_STORAGE_URL }}

steps:
- uses: actions/checkout@v3

Expand All @@ -22,6 +27,13 @@ jobs:
distribution: 'temurin'
cache: 'maven'

- name: Create application.properties
run: |
echo "azure.storage.url=${AZURE_STORAGE_URL}" > src/main/resources/application.properties
echo "azure.storage.container.name=${AZURE_STORAGE_CONTAINER_NAME}" >> src/main/resources/application.properties
echo "azure.storage.connection.string=${AZURE_STORAGE_CONNECTION_STRING}" >> src/main/resources/application.properties


- name: Build with Maven
run: mvn -B package --file pom.xml

Expand Down
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,12 @@
<version>3.2.0</version>
</dependency>

<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-storage-blob</artifactId>
<version>12.25.1</version>
</dependency>

</dependencies>

<build>
Expand Down
41 changes: 41 additions & 0 deletions src/main/java/api/educai/config/AzureBlobConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package api.educai.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.azure.storage.blob.BlobContainerClient;
import com.azure.storage.blob.BlobServiceClient;
import com.azure.storage.blob.BlobServiceClientBuilder;

@Configuration
public class AzureBlobConfig {

@Value("${azure.storage.connection.string}")
private String connectionString;

@Value("${azure.storage.container.name}")
private String containerName;

@Bean
public BlobServiceClient blobServiceClient() {

BlobServiceClient blobServiceClient =
new BlobServiceClientBuilder()
.connectionString(connectionString)
.buildClient();

return blobServiceClient;

}

@Bean
public BlobContainerClient blobContainerClient() {

BlobContainerClient blobContainerClient =
blobServiceClient()
.getBlobContainerClient(containerName);

return blobContainerClient;

}
}
6 changes: 3 additions & 3 deletions src/main/java/api/educai/controllers/PostController.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ public class PostController {
@Secured("ROLE_TEACHER")
@PostMapping
@Operation(summary = "Cria um post")
@GetMapping("/{classroomId}")
public ResponseEntity<Post> createPost(@RequestBody @Valid PostDTO post, @PathVariable String classroomId){
return ResponseEntity.status(201).body(postService.createPost(post,classroomId));
@PostMapping
public ResponseEntity<Post> createPost(@RequestBody @Valid PostDTO post, @PathVariable String id){
return ResponseEntity.status(201).body(postService.createPost(post, id));
}

@Operation(summary = "Retorna todos os posts")
Expand Down
25 changes: 25 additions & 0 deletions src/main/java/api/educai/controllers/UserController.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,13 @@
import jakarta.validation.constraints.NotBlank;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;

import static org.springframework.http.ResponseEntity.status;
Expand Down Expand Up @@ -113,4 +117,25 @@ public ResponseEntity<Void> logoff(

return status(200).build();
}

@Operation(summary = "Adiciona imagem de perfil do usuário")
@PostMapping("/{userId}/picture")
public ResponseEntity<Void> uploadProfilePicture(@RequestParam MultipartFile file, @PathVariable ObjectId userId) {
userService.uploadFile(file, userId);
return status(200).build();
}

@Operation(summary = "Busca imagem de perfil do usuário")
@GetMapping(value = "/{userId}/picture", produces = MediaType.ALL_VALUE)
public ResponseEntity<byte[]> getProfilePicture(@PathVariable ObjectId userId) throws URISyntaxException {
byte[] image = userService.getProfilePicture(userId);
return status(200).body(image);
}

@Operation(summary = "Busca URL de imagem de perfil do usuário")
@GetMapping(value = "/{userId}/picture-url")
public ResponseEntity<String> getProfilePictureUrl(@PathVariable ObjectId userId) throws URISyntaxException {
return status(200).body(userService.getProfilePictureUrl(userId));
}

}
73 changes: 73 additions & 0 deletions src/main/java/api/educai/services/AzureBlobService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package api.educai.services;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.azure.core.http.rest.PagedIterable;
import com.azure.storage.blob.BlobClient;
import com.azure.storage.blob.BlobContainerClient;
import com.azure.storage.blob.models.BlobItem;

@Service
public class AzureBlobService {

@Autowired
BlobContainerClient blobContainerClient;

@Value("${azure.storage.url}")
private String storageUrl;

public String upload(MultipartFile file)
throws IOException {

String uuid = String.valueOf(UUID.randomUUID());
BlobClient blob = blobContainerClient
.getBlobClient(uuid);
blob.upload(file.getInputStream(),
file.getSize(), true);

return storageUrl + uuid;
}

public String getBlobUrl(String fileName){
BlobClient blob = blobContainerClient.getBlobClient(fileName);
return blob.getBlobUrl();
}

public byte[] download(String fileName)
throws URISyntaxException {

BlobClient blob = blobContainerClient.getBlobClient(fileName);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
blob.download(outputStream);
return outputStream.toByteArray();

}

public List<String> listBlobs() {

PagedIterable<BlobItem> items = blobContainerClient.listBlobs();
List<String> names = new ArrayList<String>();
for (BlobItem item : items) {
names.add(item.getName());
}
return names;

}

public Boolean deleteBlob(String blobName) {

BlobClient blob = blobContainerClient.getBlobClient(blobName);
blob.delete();
return true;
}

}
33 changes: 33 additions & 0 deletions src/main/java/api/educai/services/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,11 @@
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
Expand All @@ -33,6 +36,8 @@ public class UserService {
private Token token;
@Autowired
private RefreshToken refreshToken;
@Autowired
private AzureBlobService azureBlobService;

public UserDTO createUser(User user) {
validateUserEmail(user.getEmail());
Expand Down Expand Up @@ -180,4 +185,32 @@ public void updateScore(Integer score, User user) {
public List<User> getUsersScore(ObjectId classroomId) {
return userRespository.findByRoleAndClassroomsIdOrderByScoreDesc(Role.STUDENT, classroomId);
}

public void uploadFile(MultipartFile file, ObjectId userId) {
try {
User user = getUserById(userId);
String path = azureBlobService.upload(file);
user.setProfilePicture(path);
userRespository.save(user);
} catch (IOException ex) {
throw new ResponseStatusException(HttpStatusCode.valueOf(500), "Error while trying to upload user picture!");
}
}

public byte[] getProfilePicture(ObjectId userId) throws URISyntaxException {
User user = getUserById(userId);
String path = user.getProfilePicture();
String[] parts = path.split("/");
String fileName = parts[parts.length - 1];
return azureBlobService.download(fileName);
}

public String getProfilePictureUrl(ObjectId userId) throws URISyntaxException {
User user = getUserById(userId);
String path = user.getProfilePicture();
String[] parts = path.split("/");
String fileName = parts[parts.length - 1];
return azureBlobService.getBlobUrl(fileName);
}

}
17 changes: 17 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# database
spring.data.mongodb.port=27017
spring.data.mongodb.host=20.51.193.153
spring.data.mongodb.database=db_educai
Expand All @@ -7,5 +8,21 @@ spring.data.mongodb.password=i9lnkPC9U46sOg0

server.error.include-message=always
server.error.include-binding-errors=always

# Tamanho de arquivos aceitos
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
server.tomcat.max-http-form-post-size=10MB

# Habilitar CORS globalmente
spring.mvc.cors.allowed-origins=*
spring.mvc.cors.allowed-methods=GET,POST,PUT,DELETE
spring.mvc.cors.allowed-headers=*

# Azure
azure.storage.connection.string=${{ secrets.AZURE_STORAGE_CONNECTION_STRING }}
azure.storage.container.name=${{ secrets.AZURE_STORAGE_CONTAINER_NAME }}

# JWT
jwt.token.secret=07BFq1GxbCm49YnsEQte9lk0z9hte8db7rG5wSERMaPZlqM3dGwvvbAYqUZ6WDNQQLzTSUCx7elIYGiTIbDgbYt6kX4IxQ3F9Ugs
jwt.refreshToken.secret=sItiZWQUIadPUidgxsR8EjjbRwe52CM0q2jcv4xzgl23EdWGrdrn73NzE2OBZ0duc38mBjnfzwNM1UHA2TNFngmJNpFULQx2TxUr
13 changes: 0 additions & 13 deletions src/test/java/api/educai/EducaiApplicationTests.java

This file was deleted.

Loading