Skip to content

Commit

Permalink
Adjusting Translation Provider
Browse files Browse the repository at this point in the history
- Added 4 new model classes
- Added the new API function to NcApi
- Implemented the changes in the Repository + ViewModel
- Implemented the changes in the Activity
- Added some helper functions

Signed-off-by: Julius Linus <[email protected]>
  • Loading branch information
rapterjet2004 committed Oct 5, 2023
1 parent 0c2e0aa commit 7a60ff9
Show file tree
Hide file tree
Showing 13 changed files with 195 additions and 31 deletions.
5 changes: 5 additions & 0 deletions app/src/main/java/com/nextcloud/talk/api/NcApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
import com.nextcloud.talk.models.json.userprofile.UserProfileFieldsOverall;
import com.nextcloud.talk.models.json.userprofile.UserProfileOverall;
import com.nextcloud.talk.polls.repositories.model.PollOverall;
import com.nextcloud.talk.translate.repositories.model.LanguagesOverall;
import com.nextcloud.talk.translate.repositories.model.TranslationsOverall;

import java.util.List;
Expand Down Expand Up @@ -673,6 +674,10 @@ Observable<TranslationsOverall> translateMessage(@Header("Authorization") String
@Query("toLanguage") String toLanguage,
@Nullable @Query("fromLanguage") String fromLanguage);

@GET
Observable<LanguagesOverall> getLanguages(@Header("Authorization") String authorization,
@Url String url);

@GET
Observable<ReminderOverall> getReminder(@Header("Authorization") String authorization,
@Url String url);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,9 @@ interface TranslateRepository {
toLanguage: String,
fromLanguage: String?
): Observable<String>

fun getLanguages(
authorization: String,
url: String
): Observable<Array<String>>
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,8 @@ class TranslateRepositoryImpl @Inject constructor(private val ncApi: NcApi) : Tr
): Observable<String> {
return ncApi.translateMessage(authorization, url, text, toLanguage, fromLanguage).map { it.ocs?.data!!.text }
}

override fun getLanguages(authorization: String, url: String): Observable<Array<String>> {
return ncApi.getLanguages(authorization, url).map { it.ocs?.data?.languages }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Nextcloud Talk application
*
* @author Julius Linus
* Copyright (C) 2023 Julius Linus <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.talk.translate.repositories.model

import android.os.Parcelable
import com.bluelinelabs.logansquare.annotation.JsonField
import com.bluelinelabs.logansquare.annotation.JsonObject
import kotlinx.parcelize.Parcelize

@Parcelize
@JsonObject
data class LanguagesData(
@JsonField(name = ["languageDetection"])
var languageDetection: Boolean?,
@JsonField(name = ["languages"])
var languages: Array<String>?
) : Parcelable {
// This constructor is added to work with the 'com.bluelinelabs.logansquare.annotation.JsonObject'
constructor() : this(null, null)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* Nextcloud Talk application
*
* @author Julius Linus
* Copyright (C) 2023 Julius Linus <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.talk.translate.repositories.model

import android.os.Parcelable
import com.bluelinelabs.logansquare.annotation.JsonField
import com.bluelinelabs.logansquare.annotation.JsonObject
import com.nextcloud.talk.models.json.generic.GenericMeta
import kotlinx.parcelize.Parcelize

@Parcelize
@JsonObject
data class LanguagesOCS(
@JsonField(name = ["meta"])
var meta: GenericMeta?,
@JsonField(name = ["data"])
var data: LanguagesData?
) : Parcelable {
// This constructor is added to work with the 'com.bluelinelabs.logansquare.annotation.JsonObject'
constructor() : this(null, LanguagesData())
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Nextcloud Talk application
*
* @author Julius Linus
* Copyright (C) 2023 Julius Linus <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.talk.translate.repositories.model

import android.os.Parcelable
import com.bluelinelabs.logansquare.annotation.JsonField
import com.bluelinelabs.logansquare.annotation.JsonObject
import kotlinx.parcelize.Parcelize

@Parcelize
@JsonObject
class LanguagesOverall(
@JsonField(name = ["ocs"])
var ocs: LanguagesOCS?
) : Parcelable {
// This constructor is added to work with the 'com.bluelinelabs.logansquare.annotation.JsonObject'
constructor() : this(null)
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import kotlinx.parcelize.Parcelize

@Parcelize
@JsonObject
data class TranslateOCS( // TODO finish this model
data class TranslateOCS(
@JsonField(name = ["meta"])
var meta: GenericMeta?,
@JsonField(name = ["data"])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ import com.nextcloud.talk.databinding.ActivityTranslateBinding
import com.nextcloud.talk.translate.viewmodels.TranslateViewModel
import com.nextcloud.talk.users.UserManager
import com.nextcloud.talk.utils.bundle.BundleKeys
import com.nextcloud.talk.utils.database.user.CapabilitiesUtilNew
import org.json.JSONArray
import java.util.Locale
import javax.inject.Inject
Expand All @@ -60,6 +59,7 @@ class TranslateActivity : BaseActivity() {

private var toLanguages: Array<String>? = null
private var fromLanguages: Array<String>? = null
private var languages: Array<String>? = null

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Expand All @@ -79,15 +79,24 @@ class TranslateActivity : BaseActivity() {
onTranslatedState(state.msg)
}

is TranslateViewModel.ErrorState -> {
onErrorState()
is TranslateViewModel.TranslationErrorState -> {
onTranslationErrorState()
}

is TranslateViewModel.LanguagesErrorState -> {
onLanguagesErrorState()
}

is TranslateViewModel.LanguagesRetrievedState -> {
languages = state.array
}
}
}
setupActionBar()
setContentView(binding.root)
setupSystemColors()
setupTextViews()
viewModel.getLanguages()
getLanguageOptions()
setupSpinners()
setupCopyButton()
Expand Down Expand Up @@ -156,7 +165,7 @@ class TranslateActivity : BaseActivity() {

private fun getLanguageOptions() {
val currentUser = userManager.currentUser.blockingGet()
val json = JSONArray((CapabilitiesUtilNew.getLanguages(currentUser) as ArrayList<*>).toArray())
val json = JSONArray(languages)

val fromLanguagesSet = mutableSetOf(resources.getString(R.string.translation_detect_language))
val toLanguagesSet = mutableSetOf(resources.getString(R.string.translation_device_settings))
Expand All @@ -179,16 +188,16 @@ class TranslateActivity : BaseActivity() {
binding.toLanguageInputLayout.isEnabled = value
}

private fun showDialog() {
private fun showDialog(titleInt: Int, messageInt: Int) {
val dialogBuilder = MaterialAlertDialogBuilder(this@TranslateActivity)
.setIcon(
viewThemeUtils.dialog.colorMaterialAlertDialogIcon(
context,
R.drawable.ic_warning_white
)
)
.setTitle(R.string.translation_error_title)
.setMessage(R.string.translation_error_message)
.setTitle(titleInt)
.setMessage(messageInt)
.setPositiveButton(R.string.nc_ok) { dialog, _ ->
dialog.dismiss()
}
Expand All @@ -212,7 +221,7 @@ class TranslateActivity : BaseActivity() {

private fun getISOFromServer(language: String): String {
val currentUser = userManager.currentUser.blockingGet()
val json = JSONArray((CapabilitiesUtilNew.getLanguages(currentUser) as ArrayList<*>).toArray())
val json = JSONArray(languages)

for (i in 0 until json.length()) {
val current = json.getJSONObject(i)
Expand Down Expand Up @@ -279,10 +288,16 @@ class TranslateActivity : BaseActivity() {
enableSpinners(true)
}

private fun onErrorState() {
private fun onTranslationErrorState() {
binding.progressBar.visibility = View.GONE
enableSpinners(true)
showDialog(R.string.translation_error_title, R.string.translation_error_message)
}

private fun onLanguagesErrorState() {
binding.progressBar.visibility = View.GONE
enableSpinners(true)
showDialog()
showDialog(R.string.languages_error_title, R.string.languages_error_message)
}

companion object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,14 @@ class TranslateViewModel @Inject constructor(

sealed interface ViewState

object StartState : ViewState
data object StartState : ViewState
class TranslatedState(val msg: String) : ViewState
object ErrorState : ViewState

class LanguagesRetrievedState(val array: Array<String>) : ViewState

data object LanguagesErrorState : ViewState

data object TranslationErrorState : ViewState

private val _viewState: MutableLiveData<ViewState> = MutableLiveData(StartState)
val viewState: LiveData<ViewState>
Expand All @@ -47,6 +52,33 @@ class TranslateViewModel @Inject constructor(
?.subscribe(TranslateObserver())
}

fun getLanguages() {
val currentUser: User = userManager.currentUser.blockingGet()
val authorization: String = ApiUtils.getCredentials(currentUser.username, currentUser.token)
val url: String = ApiUtils.getUrlForLanguages(currentUser.baseUrl)
repository.getLanguages(authorization, url)
.subscribeOn(Schedulers.io())
?.observeOn(AndroidSchedulers.mainThread())
?.subscribe(object : Observer<Array<String>> {
override fun onSubscribe(d: Disposable) {
// unused atm
}

override fun onError(e: Throwable) {
_viewState.value = LanguagesErrorState
Log.e(TAG, "Error while retrieving languages")
}

override fun onComplete() {
// unused atm
}

override fun onNext(array: Array<String>) {
_viewState.value = LanguagesRetrievedState(array)
}
})
}

inner class TranslateObserver : Observer<String> {
override fun onSubscribe(d: Disposable) {
_viewState.value = StartState
Expand All @@ -57,7 +89,7 @@ class TranslateViewModel @Inject constructor(
}

override fun onError(e: Throwable) {
_viewState.value = ErrorState
_viewState.value = TranslationErrorState
Log.e(TAG, "Error while translating message", e)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import org.json.JSONArray
import javax.inject.Inject

@AutoInjector(NextcloudTalkApplication::class)
Expand Down Expand Up @@ -94,8 +93,7 @@ class MessageActionsDialog(
initMenuItemTranslate(
!message.isDeleted &&
ChatMessage.MessageType.REGULAR_TEXT_MESSAGE == message.getCalculateMessageType() &&
CapabilitiesUtilNew.isTranslationsSupported(user) &&
JSONArray((CapabilitiesUtilNew.getLanguages(user) as ArrayList<*>).toArray()).length() > 0
CapabilitiesUtilNew.isTranslationsSupported(user)
)
initMenuReplyToMessage(message.replyable && hasChatPermission)
initMenuReplyPrivately(
Expand Down
4 changes: 4 additions & 0 deletions app/src/main/java/com/nextcloud/talk/utils/ApiUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -531,6 +531,10 @@ public static String getUrlForTranslation(String baseUrl) {
return baseUrl + ocsApiVersion + "/translation/translate";
}

public static String getUrlForLanguages(String baseUrl) {
return baseUrl + ocsApiVersion + "/translation/languages";
}

public static String getUrlForReminder(User user, String roomToken, String messageId, int version) {
String url = ApiUtils.getUrlForChatMessage(version, user.getBaseUrl(), roomToken, messageId);
return url + "/reminder";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -214,33 +214,22 @@ object CapabilitiesUtilNew {

@JvmStatic
fun isLinkPreviewAvailable(user: User): Boolean {
if (user.capabilities?.coreCapability?.referenceApi != null &&
return user.capabilities?.coreCapability?.referenceApi != null &&
user.capabilities?.coreCapability?.referenceApi == "true"
) {
return true
}
return false
}

fun isTranslationsSupported(user: User?): Boolean {
if (user?.capabilities != null) {
val capabilities = user.capabilities
return capabilities?.spreedCapability?.config?.containsKey("chat") == true &&
capabilities.spreedCapability!!.config!!["chat"] != null &&
capabilities.spreedCapability!!.config!!["chat"]!!.containsKey("translations")
capabilities.spreedCapability!!.config!!["chat"]!!.containsKey("has-translation-providers") &&
capabilities.spreedCapability!!.config!!["chat"]!!["has-translation-providers"] == true
}

return false
}

fun getLanguages(user: User?): Any? {
return if (isTranslationsSupported(user)) {
user!!.capabilities!!.spreedCapability!!.config!!["chat"]!!["translations"]
} else {
null
}
}

fun isRemindSupported(user: User?): Boolean {
if (user?.capabilities != null) {
val capabilities = user.capabilities
Expand Down
2 changes: 2 additions & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -710,5 +710,7 @@ How to translate with transifex:
<string name="audio_call">Audio Call</string>
<string name="started_a_call">started a call</string>
<string name="nc_settings_phone_book_integration_phone_number_dialog_429">Error 429 Too Many Requests</string>
<string name="languages_error_title">Retrieval failed</string>
<string name="languages_error_message">Languages could not be retrieved</string>

</resources>

0 comments on commit 7a60ff9

Please sign in to comment.