Skip to content
Open
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
4 changes: 2 additions & 2 deletions .idea/gradle.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 15 additions & 1 deletion app/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import java.util.Properties

plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
Expand All @@ -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 {
Expand All @@ -38,6 +46,7 @@ android {
}
buildFeatures {
compose = true
buildConfig = true
}
}

Expand Down Expand Up @@ -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)
}
Original file line number Diff line number Diff line change
@@ -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<List<PostResponse>>

@POST("/api/posts")
suspend fun createPost(
@Query("author") author: String = "예원",
@Body request: PostCreateRequest
): BaseResponse<PostResponse>

// DELETE 요청
@DELETE("/api/posts/{id}")
suspend fun deletePost(
@Path("id") id: Long
): BaseResponse<Unit> // data에 빈 객체 반환

@GET("/api/posts/{id}")
suspend fun getPostDetail(
@Path("id") id: Long
): BaseResponse<PostResponse>

// 업데이트 요청
@PUT("/api/posts/{id}")
suspend fun updatePost(
@Path("id") id: Long,
@Body request: PostCreateRequest // 수정된 내용 전달
): BaseResponse<PostResponse> // 수정된 내용이 data에 들어가고, 반환

// Retrofit에서 이미지 파일을 multipart/form-data로 업로드
@Multipart // multipart?form-data 형식의 요청을 보냄
@POST("/api/images/upload")
suspend fun uploadImage(
@Part file: MultipartBody.Part // multipart의 한 조각(part) 타입
):BaseResponse<Map<String, String>> // 본문 data가 key-value의 Map 형식 -> ex) "url":"..."
}
Original file line number Diff line number Diff line change
@@ -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)
}
Original file line number Diff line number Diff line change
@@ -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?,
)
Original file line number Diff line number Diff line change
@@ -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?
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.example.kuit6_android_api.data.model.response

import kotlinx.serialization.SerialName

data class BaseResponse<T>(
@SerialName("success") val success: Boolean,
@SerialName("message") val message: String?,
@SerialName("data") val data: T?,
@SerialName("timestamp") val timestamp: String
)
Original file line number Diff line number Diff line change
@@ -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
)
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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"
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,26 @@ 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
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
Expand All @@ -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)
Expand All @@ -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("") }
Expand All @@ -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(
Expand Down Expand Up @@ -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)
Expand All @@ -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
)
}
}
}
}
}

Expand All @@ -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,
Expand All @@ -208,7 +297,7 @@ fun PostCreateScreen(
)
) {
Text(
"작성하기",
if (viewModel.isUploading) "업로드 중..." else "작성하기",
style = MaterialTheme.typography.titleMedium.copy(
fontWeight = FontWeight.Bold
)
Expand Down
Loading