From 5d3a11f486cd11650305999bbd6240c73b205b2b Mon Sep 17 00:00:00 2001 From: Vincent TE Date: Thu, 11 Jul 2024 14:46:57 +0200 Subject: [PATCH] Code review --- .../mail/ui/newMessage/AiViewModel.kt | 46 +++++++++++-------- 1 file changed, 27 insertions(+), 19 deletions(-) diff --git a/app/src/main/java/com/infomaniak/mail/ui/newMessage/AiViewModel.kt b/app/src/main/java/com/infomaniak/mail/ui/newMessage/AiViewModel.kt index b391404620..eecde5d44d 100644 --- a/app/src/main/java/com/infomaniak/mail/ui/newMessage/AiViewModel.kt +++ b/app/src/main/java/com/infomaniak/mail/ui/newMessage/AiViewModel.kt @@ -19,6 +19,7 @@ package com.infomaniak.mail.ui.newMessage import android.os.Build import androidx.annotation.IdRes +import androidx.annotation.RequiresApi import androidx.annotation.StringRes import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel @@ -91,29 +92,36 @@ class AiViewModel @Inject constructor( } fun splitBodyAndSubject(proposition: String): Pair { - return getSubjectAndContent(MATCH_SUBJECT_REGEX.find(proposition), proposition) - } - - private fun getSubjectAndContent(match: MatchResult?, proposition: String): Pair { - val (subject, content) = match?.let { - // The method get on MatchGroupCollection is not available on API25 - if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N_MR1) { - val destructuredList = it.destructured.toList() - destructuredList[INDEX_AI_PROPOSITION_SUBJECT] to destructuredList[INDEX_AI_PROPOSITION_CONTENT].trim() - } else { - val subject = it.groups["subject"]?.value?.trim() - val content = it.groups["content"]?.value - subject to content - } - } ?: (null to proposition) - - return if (subject.isNullOrBlank() || content == null) { - null to proposition + // The method get on MatchGroupCollection is not available on API25 + return if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N_MR1) { + splitBodyAndSubjectForAPI25(proposition) } else { - subject to content + splitBodyAndSubjectAfterAPI25(proposition) } } + private fun splitBodyAndSubjectForAPI25(proposition: String): Pair { + val match = MATCH_SUBJECT_REGEX.find(proposition) + val destructuredList = match?.destructured?.toList() + val content = destructuredList?.getOrNull(INDEX_AI_PROPOSITION_CONTENT) ?: return null to proposition + val subject = destructuredList.getOrNull(INDEX_AI_PROPOSITION_SUBJECT)?.trim() + + if (subject.isNullOrBlank()) return null to proposition + + return subject to content + } + + @RequiresApi(Build.VERSION_CODES.O) + private fun splitBodyAndSubjectAfterAPI25(proposition: String): Pair { + val match = MATCH_SUBJECT_REGEX.find(proposition) + val content = match?.groups?.get("content")?.value ?: return null to proposition + val subject = match.groups["subject"]?.value?.trim() + + if (subject.isNullOrBlank()) return null to proposition + + return subject to content + } + private fun handleAiResult( apiResponse: ApiResponse, promptMessage: AiMessage?,