Skip to content

Commit

Permalink
[#139] fix : 플로우 컨트롤러 수정 api (미완)
Browse files Browse the repository at this point in the history
  • Loading branch information
serioushyeon committed Oct 30, 2024
1 parent aad7f2d commit 843fe80
Show file tree
Hide file tree
Showing 6 changed files with 120 additions and 211 deletions.
Original file line number Diff line number Diff line change
@@ -1,29 +1,27 @@
package com.project.balpyo.FlowController.ViewModel

import android.media.MediaPlayer
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.navigation.NavController
import com.project.balpyo.FlowController.FlowControllerPreviewFragmentDirections
import com.project.balpyo.LoadingFragmentDirections
import com.project.balpyo.MainActivity
import com.project.balpyo.StorageEditFlowControllerTimeFragmentDirections
import com.project.balpyo.Utils.PreferenceHelper
import com.project.balpyo.api.ApiClient
import com.project.balpyo.api.BaseDto
import com.project.balpyo.api.TokenManager
import com.project.balpyo.api.data.Tag
import com.project.balpyo.api.request.EditScriptRequest
import com.project.balpyo.api.request.GenerateAudioRequest
import com.project.balpyo.api.request.GenerateNoteRequest
import com.project.balpyo.api.response.EditScriptResponse
import com.project.balpyo.api.response.GenerateAudioResponse
import com.project.balpyo.api.response.SpeechMark
import com.project.balpyo.api.response.StorageListResult
import com.project.balpyo.api.toStorageListResult
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.IOException
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

Expand Down Expand Up @@ -55,49 +53,14 @@ class FlowControllerViewModel : ViewModel() {
fun setFlowControllerResult(storageListResult: StorageListResult){
flowControllerResult.value = storageListResult
setSpeechMarks(storageListResult.speechMark)
//TODO: 커스텀 필드 추가 시 추가
setCustomScript(storageListResult.content)
setCustomScript(storageListResult.content) //TODO: 커스텀 필드 추가 시 추가
setNormalScript(storageListResult.content)
setScriptId(storageListResult.id)
setAudioUrl(storageListResult.voiceFilePath!!)
setSpeed(storageListResult.speed.toInt())
setTitle(storageListResult.title)
}

fun editScript(mainActivity: MainActivity) {
val apiClient = ApiClient(mainActivity)
getAudioDuration(getAudioUrlData().value!!, { duration ->
val durationInSeconds = duration / 1000
val editScript = EditScriptRequest(getScriptIdData().value!!, getCustomScriptData().value!!, getTitleData().value!!, durationInSeconds.toLong())
apiClient.apiService.editScript("Bearer ${PreferenceHelper.getUserToken(mainActivity)}",getScriptIdData().value!!.toInt(), editScript)
.enqueue(object :
Callback<EditScriptResponse> {
override fun onResponse(call: Call<EditScriptResponse>, response: Response<EditScriptResponse>) {
if (response.isSuccessful) {
// 정상적으로 통신이 성공된 경우
val result: EditScriptResponse? = response.body()
Log.d("##", "onResponse 성공: " + result?.toString())

} else {
// 통신이 실패한 경우(응답코드 3xx, 4xx 등)
var result: EditScriptResponse? = response.body()
Log.d("##", "onResponse 실패")
Log.d("##", "onResponse 실패: " + response.code())
Log.d("##", "onResponse 실패: " + response.body())
val errorBody = response.errorBody()?.string() // 에러 응답 데이터를 문자열로 얻음
Log.d("##", "Error Response: $errorBody")
}
}

override fun onFailure(call: Call<EditScriptResponse>, t: Throwable) {
// 통신 실패
Log.d("##", "onFailure 에러: " + t.message.toString());
}
})
}, { error ->
error.printStackTrace()
})
}
suspend fun generateAudio(navController: NavController, mainActivity: MainActivity): GenerateAudioResponse? {
val apiClient = ApiClient(mainActivity)
val request = GenerateAudioRequest(getCustomScriptData().value.toString(), getSpeedData().value!!)
Expand Down Expand Up @@ -173,38 +136,57 @@ class FlowControllerViewModel : ViewModel() {
Log.d("##", "Audio URL을 가져오는 데 실패했습니다.")
}
}
fun editScriptAndCalc(mainActivity: MainActivity, baseDto: BaseDto, navController: NavController) {
val apiClient = ApiClient(mainActivity)
val actionToLoading = StorageEditFlowControllerTimeFragmentDirections.actionStorageEditFlowControllerTimeFragmentToLoadingFragment(
toolbarTitle = "발표연습",
comment = "발표 연습이 만들어지고 있어요"
)
navController.navigate(actionToLoading)
apiClient.apiService.editAndCalc("Bearer ${PreferenceHelper.getUserToken(mainActivity)}", scriptId.value!!.toInt(), baseDto )
.enqueue(object :
Callback<BaseDto> {
override fun onResponse(call: Call<BaseDto>, response: Response<BaseDto>) {
if (response.isSuccessful) {
// 정상적으로 통신이 성공된 경우
val result: BaseDto? = response.body()
Log.d("##", "onResponse 성공: " + result?.toString())
setFlowControllerResult(result!!.toStorageListResult())
val actionToResult = LoadingFragmentDirections.actionLoadingFragmentToFlowControllerResultFragment(
isNew = false
)
navController.navigate(actionToResult)
} else {
// 통신이 실패한 경우(응답코드 3xx, 4xx 등)
var result: BaseDto? = response.body()
Log.d("##", "onResponse 실패")
Log.d("##", "onResponse 실패: " + response.code())
Log.d("##", "onResponse 실패: " + response.body())
val errorBody = response.errorBody()?.string() // 에러 응답 데이터를 문자열로 얻음
Log.d("##", "Error Response: $errorBody")

}
}

private fun getAudioDuration(url: String, onDurationRetrieved: (Int) -> Unit, onError: (Exception) -> Unit) {
val mediaPlayer = MediaPlayer()
try {
mediaPlayer.setDataSource(url)
mediaPlayer.setOnPreparedListener {
val duration = it.duration
onDurationRetrieved(duration)
it.release()
}
mediaPlayer.setOnErrorListener { _, _, _ ->
onError(IOException("Failed to load media"))
true
}
mediaPlayer.prepareAsync()
} catch (e: IOException) {
onError(e)
}
override fun onFailure(call: Call<BaseDto>, t: Throwable) {
// 통신 실패
Log.d("##", "onFailure 에러: " + t.message.toString());
}
})
}


fun getTitleData(): MutableLiveData<String> = title
fun getNormalScriptData(): MutableLiveData<String> = normalScript
fun getCustomScriptData(): MutableLiveData<String> = customScript
fun getSpeedData(): MutableLiveData<Int> = speed
fun getIsEditData():MutableLiveData<Boolean> = isEdit

fun getScriptIdData():MutableLiveData<Long> = scriptId

fun getSplitScriptToSentencesData() : MutableLiveData<List<String>> = splitScriptToSentences
fun getAudioUrlData() : MutableLiveData<String> = audioUrl
fun getSpeechMarks() : MutableLiveData<List<SpeechMark>> = speechMarks

fun getFlowControllerResultData(): MutableLiveData<StorageListResult> = flowControllerResult
fun setTitle(text: String) {
title.value = text
}
Expand All @@ -222,10 +204,6 @@ class FlowControllerViewModel : ViewModel() {
fun setSpeed(value: Int){
speed.value = value
}
fun setIsEdit(value: Boolean){
isEdit.value = value
}

fun setScriptId(value: Long){
scriptId.value = value
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ class StorageEditFlowControllerScriptFragment : Fragment() {
val splitter = SentenceSplitter()
val paragraph = splitter.sentences(flowControllerViewModel.getNormalScriptData().value.toString())
flowControllerViewModel.setSplitScriptToSentences(paragraph)
findNavController().navigate(R.id.flowControllerAddTimeFragment)
findNavController().navigate(R.id.storageEditFlowControllerTimeFragment)
}
private fun observeKeyboardState() {
binding.root.viewTreeObserver.addOnGlobalLayoutListener {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,13 @@ import androidx.recyclerview.widget.LinearLayoutManager
import com.project.balpyo.FlowController.AddTime.CustomDragShadowBuilder
import com.project.balpyo.FlowController.AddTime.MultiTypeAdapter
import com.project.balpyo.FlowController.AddTime.data.MultiTypeItem
import com.project.balpyo.FlowController.FlowControllerPreviewFragmentDirections
import com.project.balpyo.FlowController.ViewModel.FlowControllerViewModel
import com.project.balpyo.databinding.FragmentStorageEditFlowControllerTimeBinding
import com.project.balpyo.api.BaseDto
import com.project.balpyo.databinding.FragmentFlowControllerAddTimeBinding

class StorageEditFlowControllerTimeFragment : Fragment() {
private lateinit var binding: FragmentStorageEditFlowControllerTimeBinding
private lateinit var binding: FragmentFlowControllerAddTimeBinding
lateinit var mainActivity: MainActivity
private lateinit var flowControllerViewModel: FlowControllerViewModel
private val items = mutableListOf<MultiTypeItem>()

Expand All @@ -32,32 +33,50 @@ class StorageEditFlowControllerTimeFragment : Fragment() {
savedInstanceState: Bundle?
): View {
flowControllerViewModel = ViewModelProvider(requireActivity())[FlowControllerViewModel::class.java]
binding = FragmentStorageEditFlowControllerTimeBinding.inflate(inflater, container, false)
binding = FragmentFlowControllerAddTimeBinding.inflate(inflater, container, false)
mainActivity = activity as MainActivity

initToolBar()

initToolBar()
initMultiTypeRecyclerView()

setupLongClickListener(binding.btnFlowControllerBreathStorageFlowControllerEditTime, R.layout.layout_custom_shadow_breath)
setupLongClickListener(binding.btnFlowControllerPptStorageFlowControllerEditTime, R.layout.layout_custom_shadow_ppt)
setupLongClickListener(binding.btnFlowControllerBreath, R.layout.layout_custom_shadow_breath)
setupLongClickListener(binding.btnFlowControllerPpt, R.layout.layout_custom_shadow_ppt)
setupDragListener()

// '다음' 버튼 클릭 리스너 설정
binding.btnFlowControllerNextStorageFlowControllerEditTime.setOnClickListener {
val items = (binding.rvScriptStorageFlowControllerEditTime.adapter as MultiTypeAdapter).getList()
flowControllerViewModel.setCustomScript(concatenateTexts(items))
//api 호출 하면서 하단 액션 추가
/*val action = StorageEditFlowControllerTimeFragmentDirections.actionStorageEditFlowControllerTimeFragmentToLoadingFragment(
toolbarTitle = "발표연습",
comment = "발표 연습이 만들어지고 있어요"
)
findNavController().navigate(action)*/
binding.btnFlowControllerNext.setOnClickListener {
flowControllerViewModel.run {
val items =
(binding.rvScript.adapter as MultiTypeAdapter).getList()
setCustomScript(concatenateTexts(items))
val baseDto = BaseDto(
id = getScriptIdData().value!!,
content = getNormalScriptData().value,
title = getTitleData().value!!,
secTime = null,
voiceFilePath = null,
isGenerating = null,
playTime = null,
originalScript = getNormalScriptData().value,
speed = (getSpeedData().value ?: 0).toLong(),
useAi = null,
tags = null,
topic = null,
keywords = null,
fcmToken = null,
speechMark = null
)

flowControllerViewModel.editScriptAndCalc(mainActivity, baseDto, findNavController())
}
}
return binding.root
}

private fun setupDragListeners() {
val buttons = listOf(binding.btnFlowControllerBreathStorageFlowControllerEditTime, binding.btnFlowControllerPptStorageFlowControllerEditTime)
val buttons = listOf(binding.btnFlowControllerBreath, binding.btnFlowControllerPpt)
buttons.forEach { button ->
button.setOnLongClickListener { view ->
val item = ClipData.Item(view.tag as? CharSequence)
Expand All @@ -79,10 +98,10 @@ class StorageEditFlowControllerTimeFragment : Fragment() {
items.addAll(scriptData.map { MultiTypeItem.TextItem(it) })

// RecyclerView 및 어댑터 설정
val recyclerView = binding.rvScriptStorageFlowControllerEditTime
val recyclerView = binding.rvScript
recyclerView.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)

val multiTypeRecyclerViewAdapter = MultiTypeAdapter(items, binding.rvScriptStorageFlowControllerEditTime)
val multiTypeRecyclerViewAdapter = MultiTypeAdapter(items, binding.rvScript)
recyclerView.adapter = multiTypeRecyclerViewAdapter
}

Expand All @@ -109,7 +128,7 @@ class StorageEditFlowControllerTimeFragment : Fragment() {
val scrollRunnableTop = object : Runnable {
override fun run() {
if (isScrolling) {
binding.rvScriptStorageFlowControllerEditTime.scrollBy(0, -30)
binding.rvScript.scrollBy(0, -30)
handler.postDelayed(this, 50)
}
}
Expand All @@ -118,7 +137,7 @@ class StorageEditFlowControllerTimeFragment : Fragment() {
val scrollRunnableBottom = object : Runnable {
override fun run() {
if (isScrolling) {
binding.rvScriptStorageFlowControllerEditTime.scrollBy(0, 30)
binding.rvScript.scrollBy(0, 30)
handler.postDelayed(this, 50)
}
}
Expand Down
5 changes: 5 additions & 0 deletions app/src/main/java/com/project/balpyo/api/ApiService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.PATCH
import retrofit2.http.POST
import retrofit2.http.PUT
import retrofit2.http.Path
import retrofit2.http.Query

Expand Down Expand Up @@ -107,4 +108,8 @@ interface ApiService {
@GET("scripts/search")
fun search(@Header("Authorization") token: String, @Query("tag") tag: String?, @Query("isGenerating") isGenerating: Boolean?, @Query("searchValue") searchValue: String?): Call<List<StorageListResult>>

//검색
@PUT("scripts/{id}/cal")
fun editAndCalc(@Header("Authorization") token: String, @Path("id") id: Int, @Body parameters: BaseDto): Call<BaseDto>

}
48 changes: 34 additions & 14 deletions app/src/main/java/com/project/balpyo/api/BaseDto.kt
Original file line number Diff line number Diff line change
@@ -1,21 +1,41 @@
package com.project.balpyo.api

import com.project.balpyo.api.response.SpeechMark
import com.project.balpyo.api.response.StorageListResult

data class BaseDto (
val id: Long,
val id: Long?,
val content: String?,
val title: String,
val secTime: Long,
val title: String?,
val secTime: Long?,
val voiceFilePath: String?,
val isGenerating :Boolean,
val playTime : Long,
val originalScript : String,
val speed : Long,
val useAi: Boolean,
val tags : List<String>,
val topic : String,
val keywords : String,
val fcmToken : String,
val speechMark : List<SpeechMark>
)
val isGenerating :Boolean?,
val playTime : Long?,
val originalScript : String?,
val speed : Long?,
val useAi: Boolean?,
val tags : List<String>?,
val topic : String?,
val keywords : String?,
val fcmToken : String?,
val speechMark : List<SpeechMark>?
)
fun BaseDto.toStorageListResult(): StorageListResult {
return StorageListResult(
id = this.id ?: -1,
content = this.content ?: "",
title = this.title.orEmpty(),
secTime = this.secTime ?: 0,
voiceFilePath = this.voiceFilePath,
isGenerating = this.isGenerating ?: false,
playTime = this.playTime ?: 0,
originalScript = this.originalScript.orEmpty(),
speed = this.speed?: 0,
useAi = this.useAi?: false,
tags = this.tags.orEmpty(),
topic = this.topic.orEmpty(),
keywords = this.keywords.orEmpty(),
fcmToken = this.fcmToken.orEmpty(),
speechMark = this.speechMark.orEmpty()
)
}
Loading

0 comments on commit 843fe80

Please sign in to comment.