diff --git a/.idea/gradle.xml b/.idea/gradle.xml index a2cf405..639c779 100644 --- a/.idea/gradle.xml +++ b/.idea/gradle.xml @@ -9,8 +9,8 @@ diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 0c6dbbc..92c84d3 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -1,3 +1,5 @@ +import java.util.Properties + plugins { alias(libs.plugins.android.application) alias(libs.plugins.kotlin.android) @@ -17,7 +19,13 @@ android { versionName = "1.0" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - + val properties = Properties() + val localPropertiesFile = rootProject.file("local.properties") + if (localPropertiesFile.exists()) { + properties.load(localPropertiesFile.inputStream()) + } + val baseUrl = properties.getProperty("BASE_URL") ?: "http://10.0.2.2:8080/" + buildConfigField("String", "BASE_URL", "\"$baseUrl\"") } buildTypes { @@ -38,6 +46,7 @@ android { } buildFeatures { compose = true + buildConfig = true } } @@ -74,4 +83,9 @@ dependencies { androidTestImplementation(libs.androidx.espresso.core) debugImplementation(libs.androidx.compose.ui.tooling) debugImplementation(libs.androidx.compose.ui.test.manifest) + + implementation(libs.retrofit) + implementation(libs.retrofit.converter.gson) + implementation(libs.okhttp) + implementation(libs.okhttp.logging.interceptor) } diff --git a/app/src/main/java/com/example/kuit6_android_api/data/api/ApiService.kt b/app/src/main/java/com/example/kuit6_android_api/data/api/ApiService.kt new file mode 100644 index 0000000..dbe79b4 --- /dev/null +++ b/app/src/main/java/com/example/kuit6_android_api/data/api/ApiService.kt @@ -0,0 +1,51 @@ +package com.example.kuit6_android_api.data.api + +import com.example.kuit6_android_api.data.model.request.PostCreateRequest +import com.example.kuit6_android_api.data.model.response.BaseResponse +import com.example.kuit6_android_api.data.model.response.PostResponse +import okhttp3.MultipartBody +import retrofit2.http.Body +import retrofit2.http.DELETE +import retrofit2.http.GET +import retrofit2.http.Multipart +import retrofit2.http.POST +import retrofit2.http.PUT +import retrofit2.http.Part +import retrofit2.http.Path +import retrofit2.http.Query + +interface ApiService { + @GET("/api/posts") + suspend fun getPosts(): BaseResponse> + + @POST("/api/posts") + suspend fun createPost( + @Query("author") author: String = "예원", + @Body request: PostCreateRequest + ): BaseResponse + + // DELETE 요청 + @DELETE("/api/posts/{id}") + suspend fun deletePost( + @Path("id") id: Long + ): BaseResponse // data에 빈 객체 반환 + + @GET("/api/posts/{id}") + suspend fun getPostDetail( + @Path("id") id: Long + ): BaseResponse + + // 업데이트 요청 + @PUT("/api/posts/{id}") + suspend fun updatePost( + @Path("id") id: Long, + @Body request: PostCreateRequest // 수정된 내용 전달 + ): BaseResponse // 수정된 내용이 data에 들어가고, 반환 + + // Retrofit에서 이미지 파일을 multipart/form-data로 업로드 + @Multipart // multipart?form-data 형식의 요청을 보냄 + @POST("/api/images/upload") + suspend fun uploadImage( + @Part file: MultipartBody.Part // multipart의 한 조각(part) 타입 + ):BaseResponse> // 본문 data가 key-value의 Map 형식 -> ex) "url":"..." +} \ No newline at end of file diff --git a/app/src/main/java/com/example/kuit6_android_api/data/api/RetrofitClient.kt b/app/src/main/java/com/example/kuit6_android_api/data/api/RetrofitClient.kt new file mode 100644 index 0000000..897b8b7 --- /dev/null +++ b/app/src/main/java/com/example/kuit6_android_api/data/api/RetrofitClient.kt @@ -0,0 +1,30 @@ +package com.example.kuit6_android_api.data.api + +import com.example.kuit6_android_api.BuildConfig +import okhttp3.OkHttpClient +import okhttp3.logging.HttpLoggingInterceptor +import retrofit2.Retrofit +import retrofit2.converter.gson.GsonConverterFactory +import java.util.concurrent.TimeUnit + +object RetrofitClient { + + private val loggingInterceptor = HttpLoggingInterceptor().apply { + level = HttpLoggingInterceptor.Level.BODY + } + + private val okHttpClient = OkHttpClient.Builder() + .addInterceptor(loggingInterceptor) + .connectTimeout(30, TimeUnit.SECONDS) + .readTimeout(30, TimeUnit.SECONDS) + .writeTimeout(30, TimeUnit.SECONDS) + .build() + + private val retrofit: Retrofit = Retrofit.Builder() + .baseUrl(BuildConfig.BASE_URL) + .client(okHttpClient) + .addConverterFactory(GsonConverterFactory.create()) + .build() + + val apiService: ApiService = retrofit.create(ApiService::class.java) +} \ No newline at end of file diff --git a/app/src/main/java/com/example/kuit6_android_api/data/model/request/PostCreateRequest.kt b/app/src/main/java/com/example/kuit6_android_api/data/model/request/PostCreateRequest.kt new file mode 100644 index 0000000..5e4e011 --- /dev/null +++ b/app/src/main/java/com/example/kuit6_android_api/data/model/request/PostCreateRequest.kt @@ -0,0 +1,9 @@ +package com.example.kuit6_android_api.data.model.request + +import kotlinx.serialization.SerialName + +data class PostCreateRequest( + @SerialName("title") val title: String, + @SerialName("content") val content: String, + @SerialName("imageUrl") val imageUrl: String?, +) \ No newline at end of file diff --git a/app/src/main/java/com/example/kuit6_android_api/data/model/response/AuthorResponse.kt b/app/src/main/java/com/example/kuit6_android_api/data/model/response/AuthorResponse.kt new file mode 100644 index 0000000..9d55ecd --- /dev/null +++ b/app/src/main/java/com/example/kuit6_android_api/data/model/response/AuthorResponse.kt @@ -0,0 +1,9 @@ +package com.example.kuit6_android_api.data.model.response + +import kotlinx.serialization.SerialName + +data class AuthorResponse( + @SerialName("id") val id: Long, + @SerialName("username") val username: String, + @SerialName("profileImageUrl") val profileImageUrl: String? +) \ No newline at end of file diff --git a/app/src/main/java/com/example/kuit6_android_api/data/model/response/BaseResponse.kt b/app/src/main/java/com/example/kuit6_android_api/data/model/response/BaseResponse.kt new file mode 100644 index 0000000..cbec036 --- /dev/null +++ b/app/src/main/java/com/example/kuit6_android_api/data/model/response/BaseResponse.kt @@ -0,0 +1,10 @@ +package com.example.kuit6_android_api.data.model.response + +import kotlinx.serialization.SerialName + +data class BaseResponse( + @SerialName("success") val success: Boolean, + @SerialName("message") val message: String?, + @SerialName("data") val data: T?, + @SerialName("timestamp") val timestamp: String +) \ No newline at end of file diff --git a/app/src/main/java/com/example/kuit6_android_api/data/model/response/PostResponse.kt b/app/src/main/java/com/example/kuit6_android_api/data/model/response/PostResponse.kt new file mode 100644 index 0000000..64319b1 --- /dev/null +++ b/app/src/main/java/com/example/kuit6_android_api/data/model/response/PostResponse.kt @@ -0,0 +1,13 @@ +package com.example.kuit6_android_api.data.model.response + +import kotlinx.serialization.SerialName + +data class PostResponse( + @SerialName("id") val id: Long, + @SerialName("title") val title: String, + @SerialName("content") val content: String, + @SerialName("imageUrl") val imageUrl: String?, + @SerialName("author") val author: AuthorResponse, + @SerialName("createdAt") val createdAt: String, + @SerialName("updatedAt") val updatedAt: String +) \ No newline at end of file diff --git a/app/src/main/java/com/example/kuit6_android_api/ui/post/component/PostItem.kt b/app/src/main/java/com/example/kuit6_android_api/ui/post/component/PostItem.kt index df2e5fe..b5344a8 100644 --- a/app/src/main/java/com/example/kuit6_android_api/ui/post/component/PostItem.kt +++ b/app/src/main/java/com/example/kuit6_android_api/ui/post/component/PostItem.kt @@ -29,13 +29,13 @@ import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import coil.compose.AsyncImage -import com.example.kuit6_android_api.data.model.Author -import com.example.kuit6_android_api.data.model.Post +import com.example.kuit6_android_api.data.model.response.AuthorResponse +import com.example.kuit6_android_api.data.model.response.PostResponse import com.example.kuit6_android_api.util.formatDateTime @Composable fun PostItem( - post: Post, + post: PostResponse, onClick: () -> Unit ) { Card( @@ -153,12 +153,12 @@ fun PostItem( fun PostItemPreview() { MaterialTheme { PostItem( - post = Post( + post = PostResponse( id = 1, title = "샘플 게시글 제목", content = "이것은 샘플 게시글 내용입니다. 미리보기에서는 두 줄까지만 표시됩니다.", imageUrl = null, - author = Author(1, "testuser", null), + author = AuthorResponse(1, "testuser", null), createdAt = "2025-10-03T12:00:00", updatedAt = "2025-10-03T12:00:00" ), diff --git a/app/src/main/java/com/example/kuit6_android_api/ui/post/screen/PostCreateScreen.kt b/app/src/main/java/com/example/kuit6_android_api/ui/post/screen/PostCreateScreen.kt index 57ea2ab..68d7c96 100644 --- a/app/src/main/java/com/example/kuit6_android_api/ui/post/screen/PostCreateScreen.kt +++ b/app/src/main/java/com/example/kuit6_android_api/ui/post/screen/PostCreateScreen.kt @@ -5,6 +5,7 @@ import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer @@ -12,15 +13,18 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Close import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults +import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FilledTonalButton import androidx.compose.material3.Icon @@ -39,10 +43,14 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel +import coil.compose.AsyncImage import com.example.kuit6_android_api.ui.post.viewmodel.PostViewModel @OptIn(ExperimentalMaterial3Api::class) @@ -52,6 +60,7 @@ fun PostCreateScreen( onPostCreated: () -> Unit, viewModel: PostViewModel = viewModel() ) { + val context = LocalContext.current var author by remember { mutableStateOf("") } var title by remember { mutableStateOf("") } var content by remember { mutableStateOf("") } @@ -60,7 +69,20 @@ fun PostCreateScreen( val imagePickerLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.GetContent() ) { uri: Uri? -> - selectedImageUri = uri + uri?.let { + selectedImageUri = it + // 이미지 선택 시 자동으로 업로드 + viewModel.uploadImage( + context = context, + uri = it, + onSuccess = { imageUrl -> + // 업로드 성공 처리는 ViewModel에서 자동으로 됨 + }, + onError = { error -> + // 에러 처리 (필요시 Toast 등으로 표시) + } + ) + } } Scaffold( @@ -171,7 +193,7 @@ fun PostCreateScreen( color = MaterialTheme.colorScheme.onSurface ) - if (selectedImageUri == null) { + if (selectedImageUri == null && !viewModel.isUploading) { FilledTonalButton( onClick = { imagePickerLauncher.launch("image/*") }, shape = RoundedCornerShape(10.dp) @@ -180,6 +202,68 @@ fun PostCreateScreen( } } } + + // 업로드 중 표시 + if (viewModel.isUploading) { + Spacer(modifier = Modifier.height(16.dp)) + Box( + modifier = Modifier.fillMaxWidth(), + contentAlignment = Alignment.Center + ) { + Column( + horizontalAlignment = Alignment.CenterHorizontally + ) { + CircularProgressIndicator( + modifier = Modifier.size(40.dp) + ) + Spacer(modifier = Modifier.height(8.dp)) + Text( + text = "업로드 중...", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } + + // 이미지 미리보기 + if (selectedImageUri != null && viewModel.uploadedImageUrl != null) { + Spacer(modifier = Modifier.height(16.dp)) + Box( + modifier = Modifier.fillMaxWidth() + ) { + AsyncImage( + model = selectedImageUri, + contentDescription = "선택된 이미지", + modifier = Modifier + .fillMaxWidth() + .height(200.dp) + .clip(RoundedCornerShape(12.dp)), + contentScale = ContentScale.Crop + ) + + // 삭제 버튼 + IconButton( + onClick = { + selectedImageUri = null + viewModel.clearUploadedImageUrl() + }, + modifier = Modifier + .align(Alignment.TopEnd) + .padding(8.dp) + .background( + MaterialTheme.colorScheme.surface.copy(alpha = 0.8f), + RoundedCornerShape(20.dp) + ) + ) { + Icon( + Icons.Default.Close, + contentDescription = "이미지 제거", + tint = MaterialTheme.colorScheme.onSurface + ) + } + } + } } } @@ -188,14 +272,19 @@ fun PostCreateScreen( Button( onClick = { val finalAuthor = author.ifBlank { "anonymous" } - viewModel.createPost(finalAuthor, title, content, null) { + viewModel.createPost( + author = finalAuthor, + title = title, + content = content, + imageUrl = viewModel.uploadedImageUrl + ) { onPostCreated() } }, modifier = Modifier .fillMaxWidth() .height(56.dp), - enabled = title.isNotBlank() && content.isNotBlank(), + enabled = title.isNotBlank() && content.isNotBlank() && !viewModel.isUploading, shape = RoundedCornerShape(16.dp), elevation = ButtonDefaults.buttonElevation( defaultElevation = 4.dp, @@ -208,7 +297,7 @@ fun PostCreateScreen( ) ) { Text( - "작성하기", + if (viewModel.isUploading) "업로드 중..." else "작성하기", style = MaterialTheme.typography.titleMedium.copy( fontWeight = FontWeight.Bold ) diff --git a/app/src/main/java/com/example/kuit6_android_api/ui/post/screen/PostDetailScreen.kt b/app/src/main/java/com/example/kuit6_android_api/ui/post/screen/PostDetailScreen.kt index 6635ced..94048c1 100644 --- a/app/src/main/java/com/example/kuit6_android_api/ui/post/screen/PostDetailScreen.kt +++ b/app/src/main/java/com/example/kuit6_android_api/ui/post/screen/PostDetailScreen.kt @@ -1,5 +1,6 @@ package com.example.kuit6_android_api.ui.post.screen +import android.widget.Toast import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row @@ -75,7 +76,7 @@ fun PostDetailScreen( IconButton(onClick = { onEditClick(postId) }) { Icon(Icons.Default.Edit, contentDescription = "수정") } - IconButton(onClick = { showDeleteDialog = true }) { + IconButton(onClick = {showDeleteDialog = true }) { Icon(Icons.Default.Delete, contentDescription = "삭제") } } diff --git a/app/src/main/java/com/example/kuit6_android_api/ui/post/screen/PostEditScreen.kt b/app/src/main/java/com/example/kuit6_android_api/ui/post/screen/PostEditScreen.kt index 0e5eaca..748b038 100644 --- a/app/src/main/java/com/example/kuit6_android_api/ui/post/screen/PostEditScreen.kt +++ b/app/src/main/java/com/example/kuit6_android_api/ui/post/screen/PostEditScreen.kt @@ -30,9 +30,9 @@ import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar -import androidx.compose.ui.tooling.preview.Preview import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -40,7 +40,9 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import coil.compose.AsyncImage @@ -54,8 +56,8 @@ fun PostEditScreen( onPostUpdated: () -> Unit, viewModel: PostViewModel = viewModel() ) { - val post = viewModel.postDetail - + val post by remember { derivedStateOf { viewModel.postDetail } } + val context = LocalContext.current var title by remember { mutableStateOf("") } var content by remember { mutableStateOf("") } var selectedImageUri by remember { mutableStateOf(null) } @@ -64,7 +66,15 @@ fun PostEditScreen( val imagePickerLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.GetContent() ) { uri: Uri? -> - selectedImageUri = uri + uri?.let { + selectedImageUri = it + viewModel.uploadImage( + context = context, + uri = it, + onSuccess = { /* 업로드 성공 시 uploadedImageUrl 갱신됨 */ }, + onError = { /* 에러 처리 */ } + ) + } } LaunchedEffect(postId) { @@ -72,13 +82,16 @@ fun PostEditScreen( } LaunchedEffect(post) { - if (post != null && !isLoaded) { - title = post.title - content = post.content + val currentPost = post + if (currentPost != null && !isLoaded) { + title = currentPost.title + content = currentPost.content isLoaded = true } } + val imageUrl = viewModel.uploadedImageUrl ?: post?.imageUrl + Scaffold( topBar = { TopAppBar( @@ -151,14 +164,14 @@ fun PostEditScreen( Spacer(modifier = Modifier.height(12.dp)) - if (selectedImageUri != null || post.imageUrl != null) { + if (selectedImageUri != null || post?.imageUrl != null) { Box( modifier = Modifier .fillMaxWidth() .height(200.dp) ) { AsyncImage( - model = selectedImageUri ?: post.imageUrl, + model = selectedImageUri ?: post?.imageUrl, contentDescription = "선택된 이미지", modifier = Modifier .fillMaxWidth() @@ -171,7 +184,10 @@ fun PostEditScreen( contentScale = ContentScale.Crop ) IconButton( - onClick = { selectedImageUri = null }, + onClick = { selectedImageUri = null + viewModel.clearUploadedImageUrl() + viewModel.clearPostImage() + }, modifier = Modifier .align(Alignment.TopEnd) .padding(8.dp) @@ -202,7 +218,7 @@ fun PostEditScreen( Button( onClick = { - viewModel.updatePost(postId, title, content, null) { + viewModel.updatePost(postId, title, content, imageUrl) { onPostUpdated() } }, diff --git a/app/src/main/java/com/example/kuit6_android_api/ui/post/screen/PostListScreen.kt b/app/src/main/java/com/example/kuit6_android_api/ui/post/screen/PostListScreen.kt index 8522d79..e794d07 100644 --- a/app/src/main/java/com/example/kuit6_android_api/ui/post/screen/PostListScreen.kt +++ b/app/src/main/java/com/example/kuit6_android_api/ui/post/screen/PostListScreen.kt @@ -23,7 +23,8 @@ import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import com.example.kuit6_android_api.ui.post.component.PostItem import com.example.kuit6_android_api.ui.post.viewmodel.PostViewModel - +import com.example.kuit6_android_api.data.model.response.AuthorResponse +import com.example.kuit6_android_api.data.model.response.PostResponse @OptIn(ExperimentalMaterial3Api::class) @Composable fun PostListScreen( @@ -33,6 +34,7 @@ fun PostListScreen( ) { val posts = viewModel.posts + // 화면이 리컴포즈될 때마다 getPost 실행 LaunchedEffect(Unit) { viewModel.getPosts() } diff --git a/app/src/main/java/com/example/kuit6_android_api/ui/post/viewmodel/PostViewModel.kt b/app/src/main/java/com/example/kuit6_android_api/ui/post/viewmodel/PostViewModel.kt index 444229c..4f51e2a 100644 --- a/app/src/main/java/com/example/kuit6_android_api/ui/post/viewmodel/PostViewModel.kt +++ b/app/src/main/java/com/example/kuit6_android_api/ui/post/viewmodel/PostViewModel.kt @@ -1,72 +1,60 @@ package com.example.kuit6_android_api.ui.post.viewmodel +import android.content.Context +import android.net.Uri +import android.provider.OpenableColumns import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope -import com.example.kuit6_android_api.data.model.Author -import com.example.kuit6_android_api.data.model.Post -import kotlinx.coroutines.delay +import com.example.kuit6_android_api.data.api.RetrofitClient +import com.example.kuit6_android_api.data.model.request.PostCreateRequest +import com.example.kuit6_android_api.data.model.response.PostResponse import kotlinx.coroutines.launch +import okhttp3.MediaType.Companion.toMediaTypeOrNull +import okhttp3.MultipartBody +import okhttp3.RequestBody.Companion.asRequestBody +import java.io.File +import java.io.FileOutputStream import java.time.LocalDateTime class PostViewModel : ViewModel() { - // 더미 데이터 - private val dummyPosts = mutableStateListOf( - Post( - id = 1, - title = "Jetpack Compose 시작하기", - content = "Jetpack Compose는 Android의 최신 UI 툴킷입니다. 선언형 UI로 더 쉽고 빠르게 UI를 만들 수 있습니다.", - imageUrl = null, - author = Author(1, "개발자A", null), - createdAt = "2025-10-05T10:00:00", - updatedAt = "2025-10-05T10:00:00" - ), - Post( - id = 2, - title = "Kotlin Coroutines 완벽 가이드", - content = "비동기 프로그래밍을 쉽게! Coroutines를 사용하면 복잡한 비동기 코드를 간단하게 작성할 수 있습니다.", - imageUrl = null, - author = Author(2, "개발자B", null), - createdAt = "2025-10-05T11:30:00", - updatedAt = "2025-10-05T11:30:00" - ), - Post( - id = 3, - title = "Android MVVM 아키텍처", - content = "MVVM 패턴으로 코드를 구조화하면 테스트와 유지보수가 쉬워집니다. ViewModel과 LiveData/StateFlow를 활용해봅시다.", - imageUrl = null, - author = Author(1, "개발자A", null), - createdAt = "2025-10-05T14:20:00", - updatedAt = "2025-10-05T14:20:00" - ) - ) - private var nextId = 4L - var posts by mutableStateOf>(emptyList()) + var posts by mutableStateOf>(emptyList()) private set - var postDetail by mutableStateOf(null) + var postDetail by mutableStateOf(null) private set var uploadedImageUrl by mutableStateOf(null) private set + var isUploading by mutableStateOf(false) + private set + + private val apiService = RetrofitClient.apiService fun getPosts() { - viewModelScope.launch { - delay(500) // 네트워크 시뮬레이션 - posts = dummyPosts.toList() + viewModelScope.launch{ + runCatching { + apiService.getPosts() + }.onSuccess { response -> + if(response.success && response.data != null) + posts = response.data + } } } fun getPostDetail(postId: Long) { viewModelScope.launch { - delay(300) - postDetail = dummyPosts.find { it.id == postId } + runCatching { + apiService.getPostDetail(postId) + }.onSuccess { response -> + if(response.success && response.data != null) + postDetail = response.data + } } } @@ -78,22 +66,21 @@ class PostViewModel : ViewModel() { onSuccess: () -> Unit = {} ) { viewModelScope.launch { - delay(500) - val newPost = Post( - id = nextId++, - title = title, - content = content, - imageUrl = imageUrl, - author = Author(nextId, author, null), - createdAt = getCurrentDateTime(), - updatedAt = getCurrentDateTime() - ) - dummyPosts.add(0, newPost) - posts = dummyPosts.toList() - onSuccess() + runCatching { + val finalImageUrl = imageUrl ?: uploadedImageUrl + val request = PostCreateRequest(title, content, finalImageUrl) + apiService.createPost(author, request) + }.onSuccess { response -> + if (response.success) { + // 이미지 업로드 관련 코드 + clearUploadedImageUrl() + onSuccess() + } + } } } + // 게시물 수정 시 호출 fun updatePost( postId: Long, title: String, @@ -102,37 +89,121 @@ class PostViewModel : ViewModel() { onSuccess: () -> Unit = {} ) { viewModelScope.launch { - delay(500) - val index = dummyPosts.indexOfFirst { it.id == postId } - if (index != -1) { - val oldPost = dummyPosts[index] - val updatedPost = oldPost.copy( - title = title, - content = content, - imageUrl = imageUrl, - updatedAt = getCurrentDateTime() - ) - dummyPosts[index] = updatedPost - postDetail = updatedPost - posts = dummyPosts.toList() - onSuccess() + runCatching { + val finalImageUrl = imageUrl ?: uploadedImageUrl // imageUrl이 없으면 uploadImage()에서 정해진 uploadedImageUrl 가져옴 + // 요청 body로 보낼 DTO 인스턴스 만들기 + val request = PostCreateRequest(title, content, finalImageUrl) + apiService.updatePost(postId, request) + }.onSuccess { response -> + if(response.success && response.data != null){ + // 변경된 새 리스트를 posts에 대입 + posts = posts.map{ + // 순회 중인 원소의 id == postId면 갱신된 객체 response.data로 교체 + if(it.id == postId) response.data else it + } + postDetail = response.data // postDetail을 갱신된 객체로 바꾸기 + onSuccess() + } + } + } + } + + // 삭제 시 호출 + fun deletePost( + postId: Long, + onSuccess: () -> Unit = {} + ) { + viewModelScope.launch { + runCatching { + apiService.deletePost(postId) + }.onSuccess { response -> + if(response.success){ + posts = posts.filterNot { it.id == postId } + onSuccess() + } } } } - fun deletePost(postId: Long, onSuccess: () -> Unit = {}) { + private fun uriToFile(context: Context, uri: Uri): File? { + return try { + val contentResolver = context.contentResolver + val fileName = getFileName(context, uri) ?: "image_${System.currentTimeMillis()}.jpg" + val tempFile = File(context.cacheDir, fileName) + + contentResolver.openInputStream(uri)?.use { input -> + FileOutputStream(tempFile).use { output -> + input.copyTo(output) + } + } + tempFile + } catch (e: Exception) { + e.printStackTrace() + null + } + } + + // URI로부터 파일 이름 가져오기 + private fun getFileName(context: Context, uri: Uri): String? { + var fileName: String? = null + val cursor = context.contentResolver.query(uri, null, null, null, null) + cursor?.use { + if (it.moveToFirst()) { + val nameIndex = it.getColumnIndex(OpenableColumns.DISPLAY_NAME) + if (nameIndex != -1) { + fileName = it.getString(nameIndex) + } + } + } + return fileName + } + + // 이미지 업로드 시 호출 + fun uploadImage( + context: Context, + uri: Uri, + onSuccess: (String) -> Unit = {}, + onError: (String) -> Unit = {} + ) { viewModelScope.launch { - delay(300) - dummyPosts.removeIf { it.id == postId } - posts = dummyPosts.toList() - onSuccess() + isUploading = true + runCatching { + val file = uriToFile(context, uri) // uri를 실제 파일로 변환 + if (file == null) { + throw Exception("파일 변환 실패") + } + + // 파일 내용을 RequestBody로 감쌈 + val requestFile = file.asRequestBody("image/*".toMediaTypeOrNull()) + // Part 생성 + val body = MultipartBody.Part.createFormData("file", file.name, requestFile) + + apiService.uploadImage(body) + }.onSuccess { response -> + isUploading = false + if (response.success && response.data != null) { + val imageUrl = response.data["imageUrl"] + if (imageUrl != null) { + uploadedImageUrl = imageUrl + onSuccess(imageUrl) + } + } + }.onFailure { error -> + isUploading = false + onError(error.message ?: "업로드 실패") + } } } + //이미지 삭제 버튼 누를 시 호출 fun clearUploadedImageUrl() { uploadedImageUrl = null } + fun clearPostImage() { + postDetail = postDetail?.copy(imageUrl = null) + } + private fun getCurrentDateTime(): String { return LocalDateTime.now().toString() } diff --git a/app/src/main/java/com/example/kuit6_android_api/util/FileUtil.kt b/app/src/main/java/com/example/kuit6_android_api/util/FileUtil.kt new file mode 100644 index 0000000..c0bf440 --- /dev/null +++ b/app/src/main/java/com/example/kuit6_android_api/util/FileUtil.kt @@ -0,0 +1,43 @@ +package com.example.kuit6_android_api.util + +import android.content.Context +import android.net.Uri +import android.provider.OpenableColumns +import java.io.File +import java.io.FileOutputStream + +object FileUtil { + + fun getFileFromUri(context: Context, uri: Uri): File? { + return try { + val fileName = getFileName(context, uri) + val tempFile = File(context.cacheDir, fileName) + + context.contentResolver.openInputStream(uri)?.use { inputStream -> + FileOutputStream(tempFile).use { outputStream -> + inputStream.copyTo(outputStream) + } + } + + tempFile + } catch (e: Exception) { + e.printStackTrace() + null + } + } + + private fun getFileName(context: Context, uri: Uri): String { + var fileName = "image_${System.currentTimeMillis()}.jpg" + + context.contentResolver.query(uri, null, null, null, null)?.use { cursor -> + if (cursor.moveToFirst()) { + val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) + if (nameIndex != -1) { + fileName = cursor.getString(nameIndex) + } + } + } + + return fileName + } +} \ No newline at end of file