android: alerts on connection errors (#1087)

This commit is contained in:
JRoberts
2022-09-22 11:55:11 +04:00
committed by GitHub
parent ba25850b73
commit 36d93f5b0e
7 changed files with 137 additions and 29 deletions
@@ -1442,6 +1442,9 @@ enum class FormatColor(val color: String) {
@Serializable
class SndFileTransfer() {}
@Serializable
class RcvFileTransfer() {}
@Serializable
class FileTransferMeta() {}
@@ -385,9 +385,15 @@ open class ChatController(var ctrl: ChatCtrl?, val ntfManager: NtfManager, val a
suspend fun apiSendMessage(type: ChatType, id: Long, file: String? = null, quotedItemId: Long? = null, mc: MsgContent): AChatItem? {
val cmd = CC.ApiSendMessage(type, id, file, quotedItemId, mc)
val r = sendCmd(cmd)
if (r is CR.NewChatItem ) return r.chatItem
Log.e(TAG, "apiSendMessage bad response: ${r.responseType} ${r.details}")
return null
return when (r) {
is CR.NewChatItem -> r.chatItem
else -> {
if (!(networkErrorAlert(r))) {
apiErrorAlert("apiSendMessage", generalGetString(R.string.error_sending_message), r)
}
null
}
}
}
suspend fun apiUpdateChatItem(type: ChatType, id: Long, itemId: Long, mc: MsgContent): AChatItem? {
@@ -475,9 +481,15 @@ open class ChatController(var ctrl: ChatCtrl?, val ntfManager: NtfManager, val a
suspend fun apiAddContact(): String? {
val r = sendCmd(CC.AddContact())
if (r is CR.Invitation) return r.connReqInvitation
Log.e(TAG, "apiAddContact bad response: ${r.responseType} ${r.details}")
return null
return when (r) {
is CR.Invitation -> r.connReqInvitation
else -> {
if (!(networkErrorAlert(r))) {
apiErrorAlert("apiAddContact", generalGetString(R.string.connection_error), r)
}
null
}
}
}
suspend fun apiConnect(connReq: String): Boolean {
@@ -509,7 +521,9 @@ open class ChatController(var ctrl: ChatCtrl?, val ntfManager: NtfManager, val a
return false
}
else -> {
apiErrorAlert("apiConnect", "Connection error", r)
if (!(networkErrorAlert(r))) {
apiErrorAlert("apiConnect", generalGetString(R.string.connection_error), r)
}
return false
}
}
@@ -526,7 +540,7 @@ open class ChatController(var ctrl: ChatCtrl?, val ntfManager: NtfManager, val a
if (e is ChatError.ChatErrorChat && e.errorType is ChatErrorType.ContactGroups) {
AlertManager.shared.showAlertMsg(
generalGetString(R.string.cannot_delete_contact),
String.format(generalGetString(R.string.contact_cannot_be_deleted_as_they_are_in_groups), e.errorType.contact.displayName, e.errorType.groupNames)
String.format(generalGetString(R.string.contact_cannot_be_deleted_as_they_are_in_groups), e.errorType.contact.displayName, e.errorType.groupNames.joinToString(", "))
)
}
}
@@ -581,9 +595,15 @@ open class ChatController(var ctrl: ChatCtrl?, val ntfManager: NtfManager, val a
suspend fun apiCreateUserAddress(): String? {
val r = sendCmd(CC.CreateMyAddress())
if (r is CR.UserContactLinkCreated) return r.connReqContact
Log.e(TAG, "apiCreateUserAddress bad response: ${r.responseType} ${r.details}")
return null
return when (r) {
is CR.UserContactLinkCreated -> r.connReqContact
else -> {
if (!(networkErrorAlert(r))) {
apiErrorAlert("apiCreateUserAddress", generalGetString(R.string.error_creating_address), r)
}
null
}
}
}
suspend fun apiDeleteUserAddress(): Boolean {
@@ -606,9 +626,24 @@ open class ChatController(var ctrl: ChatCtrl?, val ntfManager: NtfManager, val a
suspend fun apiAcceptContactRequest(contactReqId: Long): Contact? {
val r = sendCmd(CC.ApiAcceptContact(contactReqId))
if (r is CR.AcceptingContactRequest) return r.contact
Log.e(TAG, "apiAcceptContactRequest bad response: ${r.responseType} ${r.details}")
return null
return when {
r is CR.AcceptingContactRequest -> r.contact
r is CR.ChatCmdError && r.chatError is ChatError.ChatErrorAgent
&& r.chatError.agentError is AgentErrorType.SMP
&& r.chatError.agentError.smpErr is SMPErrorType.AUTH -> {
AlertManager.shared.showAlertMsg(
generalGetString(R.string.connection_error_auth),
generalGetString(R.string.sender_may_have_deleted_the_connection_request)
)
null
}
else -> {
if (!(networkErrorAlert(r))) {
apiErrorAlert("apiAcceptContactRequest", generalGetString(R.string.error_accepting_contact_request), r)
}
null
}
}
}
suspend fun apiRejectContactRequest(contactReqId: Long): Boolean {
@@ -666,9 +701,22 @@ open class ChatController(var ctrl: ChatCtrl?, val ntfManager: NtfManager, val a
suspend fun apiReceiveFile(fileId: Long): AChatItem? {
val r = sendCmd(CC.ReceiveFile(fileId))
if (r is CR.RcvFileAccepted) return r.chatItem
Log.e(TAG, "apiReceiveFile bad response: ${r.responseType} ${r.details}")
return null
return when (r) {
is CR.RcvFileAccepted -> r.chatItem
is CR.RcvFileAcceptedSndCancelled -> {
AlertManager.shared.showAlertMsg(
generalGetString(R.string.cannot_receive_file),
generalGetString(R.string.sender_cancelled_file_transfer)
)
null
}
else -> {
if (!(networkErrorAlert(r))) {
apiErrorAlert("apiReceiveFile", generalGetString(R.string.error_receiving_file), r)
}
null
}
}
}
suspend fun apiNewGroup(p: GroupProfile): GroupInfo? {
@@ -680,9 +728,15 @@ open class ChatController(var ctrl: ChatCtrl?, val ntfManager: NtfManager, val a
suspend fun apiAddMember(groupId: Long, contactId: Long, memberRole: GroupMemberRole): GroupMember? {
val r = sendCmd(CC.ApiAddMember(groupId, contactId, memberRole))
if (r is CR.SentGroupInvitation) return r.member
Log.e(TAG, "apiAddMember bad response: ${r.responseType} ${r.details}")
return null
return when (r) {
is CR.SentGroupInvitation -> r.member
else -> {
if (!(networkErrorAlert(r))) {
apiErrorAlert("apiAddMember", generalGetString(R.string.error_adding_members), r)
}
null
}
}
}
suspend fun apiJoinGroup(groupId: Long) {
@@ -699,11 +753,11 @@ open class ChatController(var ctrl: ChatCtrl?, val ntfManager: NtfManager, val a
} else if (e is ChatError.ChatErrorStore && e.storeError is StoreError.GroupNotFound) {
deleteGroup()
AlertManager.shared.showAlertMsg(generalGetString(R.string.alert_title_no_group), generalGetString(R.string.alert_message_no_group))
} else {
AlertManager.shared.showAlertMsg(generalGetString(R.string.alert_title_join_group_error), "$e")
} else if (!(networkErrorAlert(r))) {
apiErrorAlert("apiJoinGroup", generalGetString(R.string.error_joining_group), r)
}
}
else -> Log.e(TAG, "apiJoinGroup bad response: ${r.responseType} ${r.details}")
else -> apiErrorAlert("apiJoinGroup", generalGetString(R.string.error_joining_group), r)
}
}
@@ -746,6 +800,30 @@ open class ChatController(var ctrl: ChatCtrl?, val ntfManager: NtfManager, val a
}
}
private fun networkErrorAlert(r: CR): Boolean {
return when {
r is CR.ChatCmdError && r.chatError is ChatError.ChatErrorAgent
&& r.chatError.agentError is AgentErrorType.BROKER
&& r.chatError.agentError.brokerErr is BrokerErrorType.TIMEOUT -> {
AlertManager.shared.showAlertMsg(
generalGetString(R.string.connection_timeout),
generalGetString(R.string.network_error_desc)
)
true
}
r is CR.ChatCmdError && r.chatError is ChatError.ChatErrorAgent
&& r.chatError.agentError is AgentErrorType.BROKER
&& r.chatError.agentError.brokerErr is BrokerErrorType.NETWORK -> {
AlertManager.shared.showAlertMsg(
generalGetString(R.string.connection_error),
generalGetString(R.string.network_error_desc)
)
true
}
else -> false
}
}
fun apiErrorAlert(method: String, title: String, r: CR) {
val errMsg = "${r.responseType}: ${r.details}"
Log.e(TAG, "$method bad response: $errMsg")
@@ -1592,6 +1670,7 @@ sealed class CR {
@Serializable @SerialName("groupUpdated") class GroupUpdated(val toGroup: GroupInfo): CR()
// receiving file events
@Serializable @SerialName("rcvFileAccepted") class RcvFileAccepted(val chatItem: AChatItem): CR()
@Serializable @SerialName("rcvFileAcceptedSndCancelled") class RcvFileAcceptedSndCancelled(val rcvFileTransfer: RcvFileTransfer): CR()
@Serializable @SerialName("rcvFileStart") class RcvFileStart(val chatItem: AChatItem): CR()
@Serializable @SerialName("rcvFileComplete") class RcvFileComplete(val chatItem: AChatItem): CR()
// sending file events
@@ -1676,6 +1755,7 @@ sealed class CR {
is ConnectedToGroupMember -> "connectedToGroupMember"
is GroupRemoved -> "groupRemoved"
is GroupUpdated -> "groupUpdated"
is RcvFileAcceptedSndCancelled -> "rcvFileAcceptedSndCancelled"
is RcvFileAccepted -> "rcvFileAccepted"
is RcvFileStart -> "rcvFileStart"
is RcvFileComplete -> "rcvFileComplete"
@@ -1761,6 +1841,7 @@ sealed class CR {
is ConnectedToGroupMember -> "groupInfo: $groupInfo\nmember: $member"
is GroupRemoved -> json.encodeToString(groupInfo)
is GroupUpdated -> json.encodeToString(toGroup)
is RcvFileAcceptedSndCancelled -> noDetails()
is RcvFileAccepted -> json.encodeToString(chatItem)
is RcvFileStart -> json.encodeToString(chatItem)
is RcvFileComplete -> json.encodeToString(chatItem)
@@ -43,10 +43,12 @@ fun AddGroupMembersView(groupInfo: GroupInfo, chatModel: ChatModel, close: () ->
selectedRole = selectedRole,
inviteMembers = {
withApi {
selectedContacts.forEach {
val member = chatModel.controller.apiAddMember(groupInfo.groupId, it, selectedRole.value)
for (contactId in selectedContacts) {
val member = chatModel.controller.apiAddMember(groupInfo.groupId, contactId, selectedRole.value)
if (member != null) {
chatModel.upsertGroupMember(groupInfo, member)
} else {
break
}
}
close.invoke()
@@ -43,12 +43,24 @@
<string name="error_setting_network_config">Ошибка при сохранении настроек сети</string>
<!-- API Error Responses - SimpleXAPI.kt -->
<string name="connection_timeout">Превышено время соединения</string>
<string name="connection_error">Ошибка соединения</string>
<string name="network_error_desc">Пожалуйста, проверьте ваше соединение с сетью и попробуйте еще раз.</string>
<string name="error_sending_message">Ошибка при отправке сообщения</string>
<string name="error_adding_members">Ошибка при добавлении членов группы</string>
<string name="error_joining_group">Ошибка при вступлении в группу</string>
<string name="cannot_receive_file">Невозможно получить файл</string>
<string name="sender_cancelled_file_transfer">Отправитель отменил передачу файла.</string>
<string name="error_receiving_file">Ошибка при получении файла</string>
<string name="error_creating_address">Ошибка при создании адреса</string>
<string name="contact_already_exists">Существующий контакт</string>
<string name="you_are_already_connected_to_vName_via_this_link">Вы уже соединены с <xliff:g id="contactName" example="Alice">%1$s!</xliff:g> через эту ссылку.</string>
<string name="invalid_connection_link">Ошибка в ссылке контакта</string>
<string name="please_check_correct_link_and_maybe_ask_for_a_new_one">Пожалуйста, проверьте, что вы использовали правильную ссылку, или попросите ваш контакт отправить вам новую.</string>
<string name="connection_error_auth">Ошибка соединения (AUTH)</string>
<string name="connection_error_auth_desc">Возможно, ваш контакт удалил ссылку, или она уже была использована. Если это не так, то это может быть ошибкой - пожалуйста, сообщите нам об этом.\nЧтобы установить соединение, попросите ваш контакт создать еще одну ссылку и проверьте ваше соединение с сетью.</string>
<string name="error_accepting_contact_request">Ошибка при принятии запроса на соединение</string>
<string name="sender_may_have_deleted_the_connection_request">Отправитель мог удалить запрос на соединение.</string>
<string name="cannot_delete_contact">Невозможно удалить контакт!</string>
<string name="contact_cannot_be_deleted_as_they_are_in_groups">Контакт <xliff:g id="contactName" example="Jane Doe">%1$s!</xliff:g> не может быть удален, так как является членом групп(ы) <xliff:g id="groups" example="[team, chess club]">%2$s</xliff:g>.</string>
<string name="error_deleting_contact">Ошибка удаления контакта</string>
@@ -645,7 +657,6 @@
<string name="alert_message_group_invitation_expired">Приглашение в группу больше не действительно, оно было удалено отправителем.</string>
<string name="alert_title_no_group">Группа не найдена!</string>
<string name="alert_message_no_group">Эта группа больше не существует.</string>
<string name="alert_title_join_group_error">Ошибка приглашения</string>
<string name="alert_title_cant_invite_contacts">Нельзя пригласить контакты!</string>
<string name="alert_title_cant_invite_contacts_descr">Вы используете инкогнито профиль для этой группы - чтобы предотвратить раскрытие вашего основного профиля, приглашать контакты не разрешено</string>
@@ -43,12 +43,24 @@
<string name="error_setting_network_config">Error updating network configuration</string>
<!-- API Error Responses - SimpleXAPI.kt -->
<string name="connection_timeout">Connection timeout</string>
<string name="connection_error">Connection error</string>
<string name="network_error_desc">Please check your network connection and try again.</string>
<string name="error_sending_message">Error sending message</string>
<string name="error_adding_members">Error adding member(s)</string>
<string name="error_joining_group">Error joining group</string>
<string name="cannot_receive_file">Cannot receive file</string>
<string name="sender_cancelled_file_transfer">Sender cancelled file transfer.</string>Error receiving file
<string name="error_receiving_file">Error receiving file</string>
<string name="error_creating_address">Error creating address</string>
<string name="contact_already_exists">Contact already exists</string>
<string name="you_are_already_connected_to_vName_via_this_link">You are already connected to <xliff:g id="contactName" example="Alice">%1$s!</xliff:g> via this link.</string>
<string name="invalid_connection_link">Invalid connection link</string>
<string name="please_check_correct_link_and_maybe_ask_for_a_new_one">Please check that you used the correct link or ask your contact to send you another one.</string>
<string name="connection_error_auth">Connection error (AUTH)</string>
<string name="connection_error_auth_desc">Unless your contact deleted the connection or this link was already used, it might be a bug - please report it.\nTo connect, please ask your contact to create another connection link and check that you have a stable network connection.</string>
<string name="error_accepting_contact_request">Error accepting contact request</string>
<string name="sender_may_have_deleted_the_connection_request">Sender may have deleted the connection request.</string>
<string name="cannot_delete_contact">Can\'t delete contact!</string>
<string name="contact_cannot_be_deleted_as_they_are_in_groups">Contact <xliff:g id="contactName" example="Jane Doe">%1$s!</xliff:g> cannot be deleted, they are a member of the group(s) <xliff:g id="groups" example="[team, chess club]">%2$s</xliff:g>.</string>
<string name="error_deleting_contact">Error deleting contact</string>
@@ -646,7 +658,6 @@
<string name="alert_message_group_invitation_expired">Group invitation is no longer valid, it was removed by sender.</string>
<string name="alert_title_no_group">Group not found!</string>
<string name="alert_message_no_group">This group no longer exists.</string>
<string name="alert_title_join_group_error">Error joining group</string>
<string name="alert_title_cant_invite_contacts">Can\'t invite contacts!</string>
<string name="alert_title_cant_invite_contacts_descr">You\'re using an incognito profile for this group - to prevent sharing your main profile inviting contacts is not allowed</string>
@@ -988,7 +988,7 @@
</trans-unit>
<trans-unit id="Error joining group" xml:space="preserve">
<source>Error joining group</source>
<target>Ошибка приглашения</target>
<target>Ошибка при вступлении в группу</target>
<note>No comment provided by engineer.</note>
</trans-unit>
<trans-unit id="Error receiving file" xml:space="preserve">
+1 -1
View File
@@ -696,7 +696,7 @@
"Error importing chat database" = "Ошибка при импорте архива чата";
/* No comment provided by engineer. */
"Error joining group" = "Ошибка приглашения";
"Error joining group" = "Ошибка при вступлении в группу";
/* No comment provided by engineer. */
"Error receiving file" = "Ошибка при получении файла";