diff --git a/README.md b/README.md index 252fc95708..a515a25df6 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,9 @@ | 30/03/2023 | EN, [FR](/docs/lang/fr/README.md), [CZ](/docs/lang/cs/README.md), [PL](/docs/lang/pl/README.md) | -SimpleX logo +SimpleX logo + +Invest in SimpleX Chat. [Register now](https://simplexchat.typeform.com/crowdfunding). # SimpleX - the first messaging platform that has no user identifiers of any kind - 100% private by design! diff --git a/apps/ios/Shared/Model/AppAPITypes.swift b/apps/ios/Shared/Model/AppAPITypes.swift index a5a56174b1..1a66156a49 100644 --- a/apps/ios/Shared/Model/AppAPITypes.swift +++ b/apps/ios/Shared/Model/AppAPITypes.swift @@ -84,6 +84,7 @@ enum ChatCommand: ChatCmdProtocol { case apiLeaveGroup(groupId: Int64) case apiListMembers(groupId: Int64) case apiUpdateGroupProfile(groupId: Int64, groupProfile: GroupProfile) + case apiSetPublicGroupAccess(groupId: Int64, access: PublicGroupAccess) case apiCreateGroupLink(groupId: Int64, memberRole: GroupMemberRole) case apiGroupLinkMemberRole(groupId: Int64, memberRole: GroupMemberRole) case apiDeleteGroupLink(groupId: Int64) @@ -130,9 +131,9 @@ enum ChatCommand: ChatCmdProtocol { case apiAddContact(userId: Int64, incognito: Bool) case apiSetConnectionIncognito(connId: Int64, incognito: Bool) case apiChangeConnectionUser(connId: Int64, userId: Int64) - case apiConnectPlan(userId: Int64, connLink: String, linkOwnerSig: LinkOwnerSig?) - case apiPrepareContact(userId: Int64, connLink: CreatedConnLink, contactShortLinkData: ContactShortLinkData) - case apiPrepareGroup(userId: Int64, connLink: CreatedConnLink, directLink: Bool, groupShortLinkData: GroupShortLinkData) + case apiConnectPlan(userId: Int64, connLink: String, resolveMode: PlanResolveMode, linkOwnerSig: LinkOwnerSig?) + case apiPrepareContact(userId: Int64, connLink: CreatedConnLink, contactShortLinkData: ContactShortLinkData, verifiedDomain: SimplexDomain?) + case apiPrepareGroup(userId: Int64, connLink: CreatedConnLink, directLink: Bool, groupShortLinkData: GroupShortLinkData, verifiedDomain: SimplexDomain?) case apiChangePreparedContactUser(contactId: Int64, newUserId: Int64) case apiChangePreparedGroupUser(groupId: Int64, newUserId: Int64) case apiConnectPreparedContact(contactId: Int64, incognito: Bool, msg: MsgContent?) @@ -155,6 +156,9 @@ enum ChatCommand: ChatCmdProtocol { case apiAddMyAddressShortLink(userId: Int64) case apiSetProfileAddress(userId: Int64, on: Bool) case apiSetAddressSettings(userId: Int64, addressSettings: AddressSettings) + case apiSetUserDomain(userId: Int64, simplexDomain: String?) + case apiVerifyContactDomain(contactId: Int64) + case apiVerifyGroupDomain(groupId: Int64) case apiAcceptContact(incognito: Bool, contactReqId: Int64) case apiRejectContact(contactReqId: Int64) // WebRTC calls @@ -343,11 +347,12 @@ enum ChatCommand: ChatCmdProtocol { case let .apiAddContact(userId, incognito): return "/_connect \(userId) incognito=\(onOff(incognito))" case let .apiSetConnectionIncognito(connId, incognito): return "/_set incognito :\(connId) \(onOff(incognito))" case let .apiChangeConnectionUser(connId, userId): return "/_set conn user :\(connId) \(userId)" - case let .apiConnectPlan(userId, connLink, linkOwnerSig): + case let .apiConnectPlan(userId, connLink, resolveMode, linkOwnerSig): + let resolveStr = resolveMode == .unknown ? "" : " resolve=\(resolveMode.rawValue)" let sigStr = if let linkOwnerSig { " sig=\(encodeJSON(linkOwnerSig))" } else { "" } - return "/_connect plan \(userId) \(connLink)\(sigStr)" - case let .apiPrepareContact(userId, connLink, contactShortLinkData): return "/_prepare contact \(userId) \(connLink.connFullLink) \(connLink.connShortLink ?? "") \(encodeJSON(contactShortLinkData))" - case let .apiPrepareGroup(userId, connLink, directLink, groupShortLinkData): return "/_prepare group \(userId) \(connLink.connFullLink) \(connLink.connShortLink ?? "") direct=\(onOff(directLink)) \(encodeJSON(groupShortLinkData))" + return "/_connect plan \(userId) \(connLink)\(resolveStr)\(sigStr)" + case let .apiPrepareContact(userId, connLink, contactShortLinkData, verifiedDomain): return "/_prepare contact \(userId) \(connLink.cmdString)\(verifiedDomain.map{ " \($0.cmdString)" } ?? "") \(encodeJSON(contactShortLinkData))" + case let .apiPrepareGroup(userId, connLink, directLink, groupShortLinkData, verifiedDomain): return "/_prepare group \(userId) \(connLink.cmdString) direct=\(onOff(directLink))\(verifiedDomain.map{ " \($0.cmdString)" } ?? "") \(encodeJSON(groupShortLinkData))" case let .apiChangePreparedContactUser(contactId, newUserId): return "/_set contact user @\(contactId) \(newUserId)" case let .apiChangePreparedGroupUser(groupId, newUserId): return "/_set group user #\(groupId) \(newUserId)" case let .apiConnectPreparedContact(contactId, incognito, mc): return "/_connect contact @\(contactId) incognito=\(onOff(incognito))\(maybeContent(mc))" @@ -370,6 +375,10 @@ enum ChatCommand: ChatCmdProtocol { case let .apiAddMyAddressShortLink(userId): return "/_short_link_address \(userId)" case let .apiSetProfileAddress(userId, on): return "/_profile_address \(userId) \(onOff(on))" case let .apiSetAddressSettings(userId, addressSettings): return "/_address_settings \(userId) \(encodeJSON(addressSettings))" + case let .apiSetUserDomain(userId, simplexDomain): return "/_set domain \(userId)" + (simplexDomain.map { " " + $0 } ?? "") + case let .apiSetPublicGroupAccess(groupId, access): return "/_public group access #\(groupId) \(encodeJSON(access))" + case let .apiVerifyContactDomain(contactId): return "/_verify domain @\(contactId)" + case let .apiVerifyGroupDomain(groupId): return "/_verify domain #\(groupId)" case let .apiAcceptContact(incognito, contactReqId): return "/_accept incognito=\(onOff(incognito)) \(contactReqId)" case let .apiRejectContact(contactReqId): return "/_reject \(contactReqId)" case let .apiSendCallInvitation(contact, callType): return "/_call invite @\(contact.apiId) \(encodeJSON(callType))" @@ -481,6 +490,7 @@ enum ChatCommand: ChatCmdProtocol { case .apiLeaveGroup: return "apiLeaveGroup" case .apiListMembers: return "apiListMembers" case .apiUpdateGroupProfile: return "apiUpdateGroupProfile" + case .apiSetPublicGroupAccess: return "apiSetPublicGroupAccess" case .apiCreateGroupLink: return "apiCreateGroupLink" case .apiGroupLinkMemberRole: return "apiGroupLinkMemberRole" case .apiDeleteGroupLink: return "apiDeleteGroupLink" @@ -551,6 +561,9 @@ enum ChatCommand: ChatCmdProtocol { case .apiAddMyAddressShortLink: return "apiAddMyAddressShortLink" case .apiSetProfileAddress: return "apiSetProfileAddress" case .apiSetAddressSettings: return "apiSetAddressSettings" + case .apiSetUserDomain: return "apiSetUserDomain" + case .apiVerifyContactDomain: return "apiVerifyContactDomain" + case .apiVerifyGroupDomain: return "apiVerifyGroupDomain" case .apiAcceptContact: return "apiAcceptContact" case .apiRejectContact: return "apiRejectContact" case .apiSendCallInvitation: return "apiSendCallInvitation" @@ -802,7 +815,7 @@ enum ChatResponse1: Decodable, ChatAPIResult { case invitation(user: UserRef, connLinkInvitation: CreatedConnLink, connection: PendingContactConnection) case connectionIncognitoUpdated(user: UserRef, toConnection: PendingContactConnection) case connectionUserChanged(user: UserRef, fromConnection: PendingContactConnection, toConnection: PendingContactConnection, newUser: UserRef) - case connectionPlan(user: UserRef, connLink: CreatedConnLink, connectionPlan: ConnectionPlan) + case connectionPlan(user: UserRef, connLink: CreatedConnLink, planSimplexName: SimplexNameInfo?, otherSimplexName: SimplexNameInfo?, connectionPlan: ConnectionPlan) case newPreparedChat(user: UserRef, chat: ChatData) case contactUserChanged(user: UserRef, fromContact: Contact, newUser: UserRef, toContact: Contact) case groupUserChanged(user: UserRef, fromGroup: GroupInfo, newUser: UserRef, toGroup: GroupInfo) @@ -926,7 +939,7 @@ enum ChatResponse1: Decodable, ChatAPIResult { case let .invitation(u, connLinkInvitation, connection): return withUser(u, "connLinkInvitation: \(connLinkInvitation)\nconnection: \(connection)") case let .connectionIncognitoUpdated(u, toConnection): return withUser(u, String(describing: toConnection)) case let .connectionUserChanged(u, fromConnection, toConnection, newUser): return withUser(u, "fromConnection: \(String(describing: fromConnection))\ntoConnection: \(String(describing: toConnection))\nnewUserId: \(String(describing: newUser.userId))") - case let .connectionPlan(u, connLink, connectionPlan): return withUser(u, "connLink: \(String(describing: connLink))\nconnectionPlan: \(String(describing: connectionPlan))") + case let .connectionPlan(u, connLink, _, _, connectionPlan): return withUser(u, "connLink: \(String(describing: connLink))\nconnectionPlan: \(String(describing: connectionPlan))") case let .newPreparedChat(u, chat): return withUser(u, String(describing: chat)) case let .contactUserChanged(u, fromContact, newUser, toContact): return withUser(u, "fromContact: \(String(describing: fromContact))\nnewUserId: \(String(describing: newUser.userId))\ntoContact: \(String(describing: toContact))") case let .groupUserChanged(u, fromGroup, newUser, toGroup): return withUser(u, "fromGroup: \(String(describing: fromGroup))\nnewUserId: \(String(describing: newUser.userId))\ntoGroup: \(String(describing: toGroup))") @@ -960,6 +973,8 @@ enum ChatResponse2: Decodable, ChatAPIResult { case membersRoleUser(user: UserRef, groupInfo: GroupInfo, members: [GroupMember], toRole: GroupMemberRole) case membersBlockedForAllUser(user: UserRef, groupInfo: GroupInfo, members: [GroupMember], blocked: Bool) case groupUpdated(user: UserRef, toGroup: GroupInfo) + case contactDomainVerified(user: UserRef, contact: Contact, verificationFailure: String?) + case groupDomainVerified(user: UserRef, groupInfo: GroupInfo, verificationFailure: String?) case groupLinkCreated(user: UserRef, groupInfo: GroupInfo, groupLink: GroupLink) case groupLink(user: UserRef, groupInfo: GroupInfo, groupLink: GroupLink) case groupLinkDeleted(user: UserRef, groupInfo: GroupInfo) @@ -1015,6 +1030,8 @@ enum ChatResponse2: Decodable, ChatAPIResult { case .membersRoleUser: "membersRoleUser" case .membersBlockedForAllUser: "membersBlockedForAllUser" case .groupUpdated: "groupUpdated" + case .contactDomainVerified: "contactDomainVerified" + case .groupDomainVerified: "groupDomainVerified" case .groupLinkCreated: "groupLinkCreated" case .groupLink: "groupLink" case .groupLinkDeleted: "groupLinkDeleted" @@ -1066,6 +1083,8 @@ enum ChatResponse2: Decodable, ChatAPIResult { case let .membersRoleUser(u, groupInfo, members, toRole): return withUser(u, "groupInfo: \(groupInfo)\nmembers: \(members)\ntoRole: \(toRole)") case let .membersBlockedForAllUser(u, groupInfo, members, blocked): return withUser(u, "groupInfo: \(groupInfo)\nmember: \(members)\nblocked: \(blocked)") case let .groupUpdated(u, toGroup): return withUser(u, String(describing: toGroup)) + case let .contactDomainVerified(u, contact, verificationFailure): return withUser(u, "contact: \(contact)\nverificationFailure: \(verificationFailure ?? "ok")") + case let .groupDomainVerified(u, groupInfo, verificationFailure): return withUser(u, "groupInfo: \(groupInfo)\nverificationFailure: \(verificationFailure ?? "ok")") case let .groupLinkCreated(u, groupInfo, groupLink): return withUser(u, "groupInfo: \(groupInfo)\ngroupLink: \(groupLink)") case let .groupLink(u, groupInfo, groupLink): return withUser(u, "groupInfo: \(groupInfo)\ngroupLink: \(groupLink)") case let .groupLinkDeleted(u, groupInfo): return withUser(u, String(describing: groupInfo)) @@ -1368,6 +1387,20 @@ enum OwnerVerification: Decodable, Hashable { case failed(reason: String) } +struct ConnectionPlanResult { + var connLink: CreatedConnLink + var planSimplexName: SimplexNameInfo? + var otherSimplexName: SimplexNameInfo? + var connectionPlan: ConnectionPlan +} + +// APIConnectPlan resolution scope; .never is local-store-only (no network), used for per-keystroke name search +enum PlanResolveMode: String { + case allGroups + case unknown + case never +} + enum ConnectionPlan: Decodable, Hashable { case invitationLink(invitationLinkPlan: InvitationLinkPlan) case contactAddress(contactAddressPlan: ContactAddressPlan) @@ -1766,14 +1799,15 @@ struct ServerOperator: Identifiable, Equatable, Codable { serverDomains: ["simplex.im"], conditionsAcceptance: .accepted(acceptedAt: nil, autoAccepted: false), enabled: true, - smpRoles: ServerRoles(storage: true, proxy: true), - xftpRoles: ServerRoles(storage: true, proxy: true) + smpRoles: ServerRoles(storage: true, proxy: true, names: true), + xftpRoles: ServerRoles(storage: true, proxy: true, names: false) ) } struct ServerRoles: Equatable, Codable { var storage: Bool var proxy: Bool + var names: Bool } struct UserOperatorServers: Identifiable, Equatable, Codable { @@ -1800,8 +1834,8 @@ struct UserOperatorServers: Identifiable, Equatable, Codable { serverDomains: [], conditionsAcceptance: .accepted(acceptedAt: nil, autoAccepted: false), enabled: false, - smpRoles: ServerRoles(storage: true, proxy: true), - xftpRoles: ServerRoles(storage: true, proxy: true) + smpRoles: ServerRoles(storage: true, proxy: true, names: true), + xftpRoles: ServerRoles(storage: true, proxy: true, names: false) ) } set { `operator` = newValue } @@ -1824,6 +1858,7 @@ struct UserOperatorServers: Identifiable, Equatable, Codable { public enum UserServersWarning: Decodable { case noChatRelays(user: UserRef?) + case noNamesServers(user: UserRef?) } enum UserServersError: Decodable { diff --git a/apps/ios/Shared/Model/SimpleXAPI.swift b/apps/ios/Shared/Model/SimpleXAPI.swift index ea2de31569..5e957d68dc 100644 --- a/apps/ios/Shared/Model/SimpleXAPI.swift +++ b/apps/ios/Shared/Model/SimpleXAPI.swift @@ -569,7 +569,7 @@ private func processSendMessageCmd(toChatType: ChatType, cmd: ChatCommand) async return cItems } if let networkErrorAlert = networkErrorAlert(r) { - AlertManager.shared.showAlert(networkErrorAlert) + await MainActor.run { showAlert(networkErrorAlert) } } else { sendMessageErrorAlert(r.unexpected) } @@ -1003,15 +1003,15 @@ func apiVerifyGroupMember(_ groupId: Int64, _ groupMemberId: Int64, connectionCo return nil } -func apiAddContact(incognito: Bool) async -> ((CreatedConnLink, PendingContactConnection)?, Alert?) { +func apiAddContact(incognito: Bool) async -> (CreatedConnLink, PendingContactConnection)? { guard let userId = ChatModel.shared.currentUser?.userId else { logger.error("apiAddContact: no current user") - return (nil, nil) + return nil } let r: APIResult? = await chatApiSendCmdWithRetry(.apiAddContact(userId: userId, incognito: incognito), bgTask: false) - if case let .result(.invitation(_, connLinkInv, connection)) = r { return ((connLinkInv, connection), nil) } - let alert: Alert? = if let r { connectionErrorAlert(r) } else { nil } - return (nil, alert) + if case let .result(.invitation(_, connLinkInv, connection)) = r { return (connLinkInv, connection) } + if let r { await MainActor.run { showAlert(connectionErrorAlert(r)) } } + return nil } func apiSetConnectionIncognito(connId: Int64, incognito: Bool) async throws -> PendingContactConnection? { @@ -1026,94 +1026,128 @@ func apiChangeConnectionUser(connId: Int64, userId: Int64) async throws -> Pendi if let r { throw r.unexpected } else { return nil } } -func apiConnectPlan(connLink: String, linkOwnerSig: LinkOwnerSig? = nil, inProgress: BoxedValue) async -> ((CreatedConnLink, ConnectionPlan)?, Alert?) { +func apiConnectPlan(connLink: String, resolveMode: PlanResolveMode = .unknown, linkOwnerSig: LinkOwnerSig? = nil, inProgress: BoxedValue) async -> ConnectionPlanResult? { guard let userId = ChatModel.shared.currentUser?.userId else { logger.error("apiConnectPlan: no current user") - return (nil, nil) + return nil } - let r: APIResult? = await chatApiSendCmdWithRetry(.apiConnectPlan(userId: userId, connLink: connLink, linkOwnerSig: linkOwnerSig), inProgress: inProgress) - if case let .result(.connectionPlan(_, connLink, connPlan)) = r { return ((connLink, connPlan), nil) } - let alert: Alert? = if let r { apiConnectResponseAlert(r) } else { nil } - return (nil, alert) + let r: APIResult? = await chatApiSendCmdWithRetry(.apiConnectPlan(userId: userId, connLink: connLink, resolveMode: resolveMode, linkOwnerSig: linkOwnerSig), inProgress: inProgress) + if case let .result(.connectionPlan(_, connLink, planSimplexName, otherSimplexName, connPlan)) = r { + return ConnectionPlanResult(connLink: connLink, planSimplexName: planSimplexName, otherSimplexName: otherSimplexName, connectionPlan: connPlan) + } + // a .never (typing) search that matches nothing locally is not an error to surface + if case .error(.error(.notResolvedLocally)) = r { return nil } + if let r { await apiConnectResponseAlert(r) } + return nil } func apiConnect(incognito: Bool, connLink: CreatedConnLink) async -> (ConnReqType, PendingContactConnection)? { - let (r, alert) = await apiConnect_(incognito: incognito, connLink: connLink) - if let alert = alert { - AlertManager.shared.showAlert(alert) - return nil - } else { - return r - } -} - -func apiConnect_(incognito: Bool, connLink: CreatedConnLink) async -> ((ConnReqType, PendingContactConnection)?, Alert?) { guard let userId = ChatModel.shared.currentUser?.userId else { logger.error("apiConnect: no current user") - return (nil, nil) + return nil } let r: APIResult? = await chatApiSendCmdWithRetry(.apiConnect(userId: userId, incognito: incognito, connLink: connLink)) let m = ChatModel.shared switch r { case let .result(.sentConfirmation(_, connection)): - return ((.invitation, connection), nil) + return (.invitation, connection) case let .result(.sentInvitation(_, connection)): - return ((.contact, connection), nil) + return (.contact, connection) case let .result(.contactAlreadyExists(_, contact)): if let c = m.getContactChat(contact.contactId) { ItemsModel.shared.loadOpenChat(c.id) } - let alert = contactAlreadyExistsAlert(contact) - return (nil, alert) + await contactAlreadyExistsAlert(contact) + return nil default: () } - let alert: Alert? = if let r { apiConnectResponseAlert(r) } else { nil } - return (nil, alert) + if let r { await apiConnectResponseAlert(r) } + return nil } -private func apiConnectResponseAlert(_ r: APIResult) -> Alert { - switch r.unexpected { - case .error(.invalidConnReq): - mkAlert( - title: "Invalid connection link", - message: "Please check that you used the correct link or ask your contact to send you another one." - ) - case .error(.unsupportedConnReq): - mkAlert( - title: "Unsupported connection link", - message: "This link requires a newer app version. Please upgrade the app or ask your contact to send a compatible link." - ) - case .errorAgent(.SMP(_, .AUTH)): - mkAlert( - title: "Connection error (AUTH)", - message: "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." - ) - case let .errorAgent(.SMP(_, .BLOCKED(info))): - Alert( - title: Text("Connection blocked"), - message: Text("Connection is blocked by server operator:\n\(info.reason.text)"), - primaryButton: .default(Text("Ok")), - secondaryButton: .default(Text("How it works")) { - DispatchQueue.main.async { - UIApplication.shared.open(contentModerationPostLink) - } - } - ) - case .errorAgent(.SMP(_, .QUOTA)): - mkAlert( - title: "Undelivered messages", - message: "The connection reached the limit of undelivered messages, your contact may be offline." - ) - case let .errorAgent(.INTERNAL(internalErr)): - if internalErr == "SEUniqueID" { - mkAlert( - title: "Already connected?", - message: "It seems like you are already connected via this link. If it is not the case, there was an error (\(internalErr))." +private func apiConnectResponseAlert(_ r: APIResult) async { + await MainActor.run { + switch r.unexpected { + case .error(.invalidConnReq): + showAlert( + NSLocalizedString("Invalid connection link", comment: ""), + message: NSLocalizedString("Please check that you used the correct link or ask your contact to send you another one.", comment: "") ) - } else { - connectionErrorAlert(r) + case .error(.unsupportedConnReq): + showAlert( + NSLocalizedString("Unsupported connection link", comment: ""), + message: NSLocalizedString("This link requires a newer app version. Please upgrade the app or ask your contact to send a compatible link.", comment: "") + ) + case let .error(.simplexDomainNotReady(domain, err)): + switch err { + case .noValidLink: + showAlert( + NSLocalizedString("No valid link", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("The SimpleX name %@ is registered, but it has no valid link.", comment: ""), domain.fullDomainName) + ) + case .unknownDomain: + showAlert( + NSLocalizedString("Unconfirmed name", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("The SimpleX name %@ is registered, but not added to profile. Please add it to your address or channel profile, if you are the owner.", comment: ""), domain.fullDomainName) + ) + } + case .errorAgent(.NO_NAME_SERVERS): + showAlert( + NSLocalizedString("SimpleX name error", comment: ""), + message: NSLocalizedString("None of your servers are set to resolve SimpleX names. Configure servers, or use a connection link.", comment: "") + ) + case .errorAgent(.SMP(_, .AUTH)): + showAlert( + NSLocalizedString("Connection error (AUTH)", comment: ""), + message: NSLocalizedString("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.", comment: "") + ) + case let .errorAgent(.SMP(_, .BLOCKED(info))): + showAlert( + NSLocalizedString("Connection blocked", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("Connection is blocked by server operator:\n%@", comment: ""), info.reason.text), + actions: {[ + okAlertAction, + UIAlertAction(title: NSLocalizedString("How it works", comment: ""), style: .default) { _ in + DispatchQueue.main.async { + UIApplication.shared.open(contentModerationPostLink) + } + } + ]} + ) + case .errorAgent(.SMP(_, .QUOTA)): + showAlert( + NSLocalizedString("Undelivered messages", comment: ""), + message: NSLocalizedString("The connection reached the limit of undelivered messages, your contact may be offline.", comment: "") + ) + case let .errorAgent(.INTERNAL(internalErr)): + if internalErr == "SEUniqueID" { + showAlert( + NSLocalizedString("Already connected?", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("It seems like you are already connected via this link. If it is not the case, there was an error (%@).", comment: ""), internalErr) + ) + } else { + showAlert(connectionErrorAlert(r)) + } + case let .errorAgent(.SMP(serverAddress, .NAME(nameErr))): + switch nameErr { + case .NOT_FOUND: + showAlert( + NSLocalizedString("Name not found", comment: ""), + message: NSLocalizedString("This SimpleX name is not registered. Please check the name.", comment: "") + ) + case .NO_RESOLVER: + showAlert( + NSLocalizedString("SimpleX name error", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("Server %@ does not support name resolution. Configure servers, or use a connection link.", comment: ""), serverAddress) + ) + case let .RESOLVER(resolverErr): + showAlert( + NSLocalizedString("SimpleX name error", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("Resolver error: %@", comment: ""), resolverErr) + ) + } + default: showAlert(connectionErrorAlert(r)) } - default: connectionErrorAlert(r) } } @@ -1126,46 +1160,44 @@ func connErrorText(_ e: ChatError) -> String { case .errorAgent(.SMP(_, .AUTH)): NSLocalizedString("Connection error (AUTH)", comment: "conn error description") case let .errorAgent(.SMP(_, .BLOCKED(info))): - NSLocalizedString("Connection blocked: \(info.reason.text)", comment: "conn error description") + String.localizedStringWithFormat(NSLocalizedString("Connection blocked: %@", comment: "conn error description"), info.reason.text) case .errorAgent(.SMP(_, .QUOTA)): NSLocalizedString("The connection reached the limit of undelivered messages", comment: "conn error description") default: if getNetworkErrorAlert(e) != nil { NSLocalizedString("Network error", comment: "conn error description") } else { - "\(NSLocalizedString("Error", comment: "conn error description")): \(responseError(e))" + String.localizedStringWithFormat(NSLocalizedString("Error: %@", comment: "conn error description"), responseError(e)) } } } -func contactAlreadyExistsAlert(_ contact: Contact) -> Alert { - mkAlert( - title: "Contact already exists", - message: "You are already connected to \(contact.displayName)." - ) -} - -private func connectionErrorAlert(_ r: APIResult) -> Alert { - if let networkErrorAlert = networkErrorAlert(r) { - return networkErrorAlert - } else { - return mkAlert( - title: "Connection error", - message: "Error: \(responseError(r.unexpected))" +func contactAlreadyExistsAlert(_ contact: Contact) async { + await MainActor.run { + showAlert( + NSLocalizedString("Contact already exists", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("You are already connected to %@.", comment: ""), contact.displayName) ) } } -func apiPrepareContact(connLink: CreatedConnLink, contactShortLinkData: ContactShortLinkData) async throws -> ChatData { +private func connectionErrorAlert(_ r: APIResult) -> (title: String, message: String?) { + networkErrorAlert(r) ?? ( + title: NSLocalizedString("Connection error", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("Error: %@", comment: ""), responseError(r.unexpected)) + ) +} + +func apiPrepareContact(connLink: CreatedConnLink, contactShortLinkData: ContactShortLinkData, verifiedDomain: SimplexDomain? = nil) async throws -> ChatData { let userId = try currentUserId("apiPrepareContact") - let r: ChatResponse1 = try await chatSendCmd(.apiPrepareContact(userId: userId, connLink: connLink, contactShortLinkData: contactShortLinkData)) + let r: ChatResponse1 = try await chatSendCmd(.apiPrepareContact(userId: userId, connLink: connLink, contactShortLinkData: contactShortLinkData, verifiedDomain: verifiedDomain)) if case let .newPreparedChat(_, chat) = r { return chat } throw r.unexpected } -func apiPrepareGroup(connLink: CreatedConnLink, directLink: Bool, groupShortLinkData: GroupShortLinkData) async throws -> ChatData { +func apiPrepareGroup(connLink: CreatedConnLink, directLink: Bool, groupShortLinkData: GroupShortLinkData, verifiedDomain: SimplexDomain? = nil) async throws -> ChatData { let userId = try currentUserId("apiPrepareGroup") - let r: ChatResponse1 = try await chatSendCmd(.apiPrepareGroup(userId: userId, connLink: connLink, directLink: directLink, groupShortLinkData: groupShortLinkData)) + let r: ChatResponse1 = try await chatSendCmd(.apiPrepareGroup(userId: userId, connLink: connLink, directLink: directLink, groupShortLinkData: groupShortLinkData, verifiedDomain: verifiedDomain)) if case let .newPreparedChat(_, chat) = r { return chat } throw r.unexpected } @@ -1185,30 +1217,29 @@ func apiChangePreparedGroupUser(groupId: Int64, newUserId: Int64) async throws - func apiConnectPreparedContact(contactId: Int64, incognito: Bool, msg: MsgContent?) async -> Contact? { let r: APIResult? = await chatApiSendCmdWithRetry(.apiConnectPreparedContact(contactId: contactId, incognito: incognito, msg: msg)) if case let .result(.startedConnectionToContact(_, contact)) = r { return contact } - if let r { AlertManager.shared.showAlert(apiConnectResponseAlert(r)) } + if let r { await apiConnectResponseAlert(r) } return nil } func apiConnectPreparedGroup(groupId: Int64, incognito: Bool, msg: MsgContent?) async -> (GroupInfo, [RelayConnectionResult])? { let r: APIResult? = await chatApiSendCmdWithRetry(.apiConnectPreparedGroup(groupId: groupId, incognito: incognito, msg: msg)) if case let .result(.startedConnectionToGroup(_, groupInfo, relayResults)) = r { return (groupInfo, relayResults) } - if let r { AlertManager.shared.showAlert(apiConnectResponseAlert(r)) } + if let r { await apiConnectResponseAlert(r) } return nil } -func apiConnectContactViaAddress(incognito: Bool, contactId: Int64) async -> (Contact?, Alert?) { +func apiConnectContactViaAddress(incognito: Bool, contactId: Int64) async -> Contact? { guard let userId = ChatModel.shared.currentUser?.userId else { logger.error("apiConnectContactViaAddress: no current user") - return (nil, nil) + return nil } let r: APIResult? = await chatApiSendCmdWithRetry(.apiConnectContactViaAddress(userId: userId, incognito: incognito, contactId: contactId)) - if case let .result(.sentInvitationToContact(_, contact, _)) = r { return (contact, nil) } + if case let .result(.sentInvitationToContact(_, contact, _)) = r { return contact } if let r { logger.error("apiConnectContactViaAddress error: \(responseError(r.unexpected))") - return (nil, connectionErrorAlert(r)) - } else { - return (nil, nil) + await MainActor.run { showAlert(connectionErrorAlert(r)) } } + return nil } func apiDeleteChat(type: ChatType, id: Int64, chatDeleteMode: ChatDeleteMode = .full(notify: true)) async throws { @@ -1329,6 +1360,43 @@ func apiSetProfileAddress(on: Bool) async throws -> User? { } } +func showSetSimplexNameError(_ r: APIResult, isChannel: Bool) async { + if case let .error(.simplexDomainNotReady(domain, .noValidLink)) = r.unexpected { + let format = isChannel + ? NSLocalizedString("The SimpleX name #%@ is registered without channel link. Add channel link to the name via the registration page.", comment: "alert message") + : NSLocalizedString("The SimpleX name @%@ is registered without SimpleX address. Add your SimpleX address to the name via the registration page.", comment: "alert message") + await MainActor.run { + showAlert(NSLocalizedString("Error saving name", comment: "alert title"), message: String.localizedStringWithFormat(format, domain.fullDomainName)) + } + } else { + await apiConnectResponseAlert(r) + } +} + +func apiSetUserDomain(_ simplexDomain: String?) async throws -> User { + let userId = try currentUserId("apiSetUserDomain") + let r: APIResult = await chatApiSendCmd(.apiSetUserDomain(userId: userId, simplexDomain: simplexDomain)) + switch r { + case let .result(.userProfileUpdated(user, _, _, _)): return user + case let .result(.userProfileNoChange(user)): return user + default: + await showSetSimplexNameError(r, isChannel: false) + throw r.unexpected + } +} + +func apiVerifyContactDomain(_ contactId: Int64) async throws -> (Contact, String?) { + let r: ChatResponse2 = try await chatSendCmd(.apiVerifyContactDomain(contactId: contactId)) + if case let .contactDomainVerified(_, contact, verificationFailure) = r { return (contact, verificationFailure) } + throw r.unexpected +} + +func apiVerifyGroupDomain(_ groupId: Int64) async throws -> (GroupInfo, String?) { + let r: ChatResponse2 = try await chatSendCmd(.apiVerifyGroupDomain(groupId: groupId)) + if case let .groupDomainVerified(_, groupInfo, verificationFailure) = r { return (groupInfo, verificationFailure) } + throw r.unexpected +} + func apiSetContactPrefs(contactId: Int64, preferences: Preferences) async throws -> Contact? { let r: ChatResponse1 = try await chatSendCmd(.apiSetContactPrefs(contactId: contactId, preferences: preferences)) if case let .contactPrefsUpdated(_, _, toContact) = r { return toContact } @@ -1429,23 +1497,22 @@ func apiSetUserAddressSettings(_ settings: AddressSettings) async throws -> User func apiAcceptContactRequest(incognito: Bool, contactReqId: Int64) async -> Contact? { let r: APIResult? = await chatApiSendCmdWithRetry(.apiAcceptContact(incognito: incognito, contactReqId: contactReqId)) - let am = AlertManager.shared if case let .result(.acceptingContactRequest(_, contact)) = r { return contact } if case .error(.errorAgent(.SMP(_, .AUTH))) = r { - am.showAlertMsg( - title: "Connection error (AUTH)", - message: "Sender may have deleted the connection request." - ) + await MainActor.run { showAlert( + NSLocalizedString("Connection error (AUTH)", comment: ""), + message: NSLocalizedString("Sender may have deleted the connection request.", comment: "") + ) } } else if let r { if let networkErrorAlert = networkErrorAlert(r) { - am.showAlert(networkErrorAlert) + await MainActor.run { showAlert(networkErrorAlert) } } else { logger.error("apiAcceptContactRequest error: \(String(describing: r))") - am.showAlertMsg( - title: "Error accepting contact request", - message: "Error: \(responseError(r.unexpected))" - ) + await MainActor.run { showAlert( + NSLocalizedString("Error accepting contact request", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("Error: %@", comment: ""), responseError(r.unexpected)) + ) } } } return nil @@ -1689,11 +1756,11 @@ func deleteRemoteCtrl(_ rcId: Int64) async throws { try await sendCommandOkResp(.deleteRemoteCtrl(remoteCtrlId: rcId)) } -func networkErrorAlert(_ res: APIResult) -> Alert? { - if case let .error(e) = res, let alert = getNetworkErrorAlert(e) { - return mkAlert(title: alert.title, message: alert.message) +func networkErrorAlert(_ res: APIResult) -> (title: String, message: String?)? { + if case let .error(e) = res { + getNetworkErrorAlert(e) } else { - return nil + nil } } @@ -1995,6 +2062,13 @@ func apiUpdateGroup(_ groupId: Int64, _ groupProfile: GroupProfile) async throws throw r.unexpected } +func apiSetPublicGroupAccess(_ groupId: Int64, access: PublicGroupAccess) async throws -> GroupInfo { + let r: APIResult = await chatApiSendCmd(.apiSetPublicGroupAccess(groupId: groupId, access: access)) + if case let .result(.groupUpdated(_, toGroup)) = r { return toGroup } + await showSetSimplexNameError(r, isChannel: true) + throw r.unexpected +} + func apiCreateGroupLink(_ groupId: Int64, memberRole: GroupMemberRole = .member) async throws -> GroupLink? { let r: APIResult? = await chatApiSendCmdWithRetry(.apiCreateGroupLink(groupId: groupId, memberRole: memberRole)) if case let .result(.groupLinkCreated(_, _, groupLink)) = r { return groupLink } @@ -2049,7 +2123,7 @@ func apiSendMemberContactInvitation(_ contactId: Int64, _ msg: MsgContent) async func apiAcceptMemberContact(contactId: Int64) async -> Contact? { let r: APIResult? = await chatApiSendCmdWithRetry(.apiAcceptMemberContact(contactId: contactId)) if case let .result(.memberContactAccepted(_, contact)) = r { return contact } - if let r { AlertManager.shared.showAlert(apiConnectResponseAlert(r)) } + if let r { await apiConnectResponseAlert(r) } return nil } diff --git a/apps/ios/Shared/Views/Chat/ChatInfoView.swift b/apps/ios/Shared/Views/Chat/ChatInfoView.swift index fdd1dc8a6a..2f76241c00 100644 --- a/apps/ios/Shared/Views/Chat/ChatInfoView.swift +++ b/apps/ios/Shared/Views/Chat/ChatInfoView.swift @@ -283,8 +283,9 @@ struct ChatInfoView: View { } } catch let e { logger.error("apiContactQueueInfo error: \(responseError(e))") - let a = getErrorAlert(e, "Error") - await MainActor.run { alert = .error(title: a.title, error: a.message) } + await MainActor.run { + showErrorAlert(e, NSLocalizedString("Error", comment: "")) + } } } } @@ -334,7 +335,7 @@ struct ChatInfoView: View { case .syncConnectionForceAlert: return syncConnectionForceAlert({ Task { - if let stats = await syncContactConnection(contact, force: true, showAlert: { alert = .someAlert(alert: $0) }) { + if let stats = await syncContactConnection(contact, force: true) { connectionStats = stats dismiss() } @@ -392,6 +393,26 @@ struct ChatInfoView: View { .lineLimit(3) .padding(.bottom, 2) } + if let domain = contact.profile.contactDomain, + contact.profile.contactDomainVerified != nil || domain.proof != nil { + SimplexNameView( + simplexName: "@\(domain.shortName)", + verified: contact.profile.contactDomainVerified, + verify: { + do { + let (ct, reason) = try await apiVerifyContactDomain(contact.contactId) + await MainActor.run { + chatModel.updateContact(ct) + contact = ct + } + return (ct.profile.contactDomainVerified, reason) + } catch { + logger.error("apiVerifyContactDomain: \(responseError(error))") + return nil + } + } + ) + } if let descr = cInfo.shortDescr?.trimmingCharacters(in: .whitespacesAndNewlines), descr != "" { let r = markdownText(descr, textStyle: .subheadline, showSecrets: showSecrets, backgroundColor: theme.colors.background) msgTextResultView(r, Text(AttributedString(r.string)), showSecrets: $showSecrets, centered: true, smallFont: true) @@ -521,7 +542,7 @@ struct ChatInfoView: View { private func synchronizeConnectionButton() -> some View { Button { Task { - if let stats = await syncContactConnection(contact, force: false, showAlert: { alert = .someAlert(alert: $0) }) { + if let stats = await syncContactConnection(contact, force: false) { connectionStats = stats dismiss() } @@ -598,9 +619,8 @@ struct ChatInfoView: View { } } catch let error { logger.error("switchContactAddress apiSwitchContact error: \(responseError(error))") - let a = getErrorAlert(error, "Error changing address") await MainActor.run { - alert = .error(title: a.title, error: a.message) + showErrorAlert(error, NSLocalizedString("Error changing address", comment: "")) } } } @@ -616,9 +636,8 @@ struct ChatInfoView: View { } } catch let error { logger.error("abortSwitchContactAddress apiAbortSwitchContact error: \(responseError(error))") - let a = getErrorAlert(error, "Error aborting address change") await MainActor.run { - alert = .error(title: a.title, error: a.message) + showErrorAlert(error, NSLocalizedString("Error aborting address change", comment: "")) } } } @@ -728,7 +747,7 @@ struct ChatTTLOption: View { } } -func syncContactConnection(_ contact: Contact, force: Bool, showAlert: (SomeAlert) -> Void) async -> ConnectionStats? { +func syncContactConnection(_ contact: Contact, force: Bool) async -> ConnectionStats? { do { let stats = try apiSyncContactRatchet(contact.apiId, force) await MainActor.run { @@ -737,14 +756,8 @@ func syncContactConnection(_ contact: Contact, force: Bool, showAlert: (SomeAler return stats } catch let error { logger.error("syncContactConnection apiSyncContactRatchet error: \(responseError(error))") - let a = getErrorAlert(error, "Error synchronizing connection") await MainActor.run { - showAlert( - SomeAlert( - alert: mkAlert(title: a.title, message: a.message), - id: "syncContactConnection error" - ) - ) + showErrorAlert(error, NSLocalizedString("Error synchronizing connection", comment: "")) } return nil } @@ -824,7 +837,7 @@ private struct CallButton: View { message: Text("Connection requires encryption renegotiation."), primaryButton: .default(Text("Fix")) { Task { - if let stats = await syncContactConnection(contact, force: false, showAlert: showAlert) { + if let stats = await syncContactConnection(contact, force: false) { connectionStats = stats } } @@ -1361,6 +1374,64 @@ private func deleteNotReadyContact( )) } +struct SimplexNameView: View { + @EnvironmentObject var theme: AppTheme + @AppStorage(DEFAULT_PRIVACY_VERIFY_SIMPLEX_NAMES) var autoVerify = false + let simplexName: String + let verified: Bool? + let verify: () async -> (Bool?, String?)? + @State private var inFlight = false + @State private var showSpinner = false + + var body: some View { + HStack(spacing: 6) { + Text(simplexName) + .font(verified == true ? .subheadline : .system(.subheadline, design: .monospaced)) + .foregroundColor(verified == true ? theme.colors.primary : theme.colors.secondary) + indicator() + } + .padding(.bottom, 2) + .onAppear { if autoVerify && verified == nil { runVerify(manual: false) } } + } + + @ViewBuilder private func indicator() -> some View { + if showSpinner { + ProgressView() + } else if verified == true { + Image(systemName: "checkmark") + } else if verified == false { + Image(systemName: "xmark") + .foregroundColor(.red) + .onTapGesture { runVerify(manual: true) } + } else { + Button { runVerify(manual: true) } label: { + Text("Verify name").font(.subheadline).foregroundColor(theme.colors.primary) + } + } + } + + private func runVerify(manual: Bool) { + if inFlight { return } + inFlight = true + // delay the spinner so a fast result on appear doesn't flash it + Task { + try? await Task.sleep(nanoseconds: 300_000000) + await MainActor.run { if inFlight { showSpinner = true } } + } + Task { + let res = await verify() + await MainActor.run { + inFlight = false + showSpinner = false + // show the reason on a manual run, or on an inconclusive auto run (state stayed nil) + if let (newV, reason) = res, let reason, manual || newV == nil { + showAlert(NSLocalizedString("SimpleX name not verified", comment: "alert title"), message: reason) + } + } + } + } +} + struct ChatInfoView_Previews: PreviewProvider { static var previews: some View { ChatInfoView( diff --git a/apps/ios/Shared/Views/Chat/ChatItem/CIRcvDecryptionError.swift b/apps/ios/Shared/Views/Chat/ChatItem/CIRcvDecryptionError.swift index ec23dc15a4..bdd38cb4df 100644 --- a/apps/ios/Shared/Views/Chat/ChatItem/CIRcvDecryptionError.swift +++ b/apps/ios/Shared/Views/Chat/ChatItem/CIRcvDecryptionError.swift @@ -185,9 +185,8 @@ struct CIRcvDecryptionError: View { } } catch let error { logger.error("syncMemberConnection apiSyncGroupMemberRatchet error: \(responseError(error))") - let a = getErrorAlert(error, "Error synchronizing connection") await MainActor.run { - alert = .error(title: a.title, error: a.message) + showErrorAlert(error, NSLocalizedString("Error synchronizing connection", comment: "")) } } } @@ -202,9 +201,8 @@ struct CIRcvDecryptionError: View { } } catch let error { logger.error("syncContactConnection apiSyncContactRatchet error: \(responseError(error))") - let a = getErrorAlert(error, "Error synchronizing connection") await MainActor.run { - alert = .error(title: a.title, error: a.message) + showErrorAlert(error, NSLocalizedString("Error synchronizing connection", comment: "")) } } } diff --git a/apps/ios/Shared/Views/Chat/ChatItem/MsgContentView.swift b/apps/ios/Shared/Views/Chat/ChatItem/MsgContentView.swift index 11c3c4c3f4..5cb93ad279 100644 --- a/apps/ios/Shared/Views/Chat/ChatItem/MsgContentView.swift +++ b/apps/ios/Shared/Views/Chat/ChatItem/MsgContentView.swift @@ -214,8 +214,8 @@ private func handleTextTaps( var simplex: Bool = false s.enumerateAttributes(in: NSRange(location: 0, length: s.length)) { attrs, range, stop in if index >= range.location && index < range.location + range.length { - if let nameInfo = attrs[nameAttrKey] as? SimplexNameInfo { - showUnsupportedNameAlert(nameInfo) + if attrs[nameAttrKey] is SimplexNameInfo { + planAndConnect(s.attributedSubstring(from: range).string, theme: AppTheme.shared, dismiss: false) } else if let url = attrs[linkAttrKey] as? String { linkURL = url browser = attrs[webLinkAttrKey] != nil diff --git a/apps/ios/Shared/Views/Chat/ChatView.swift b/apps/ios/Shared/Views/Chat/ChatView.swift index ded0019692..283157864d 100644 --- a/apps/ios/Shared/Views/Chat/ChatView.swift +++ b/apps/ios/Shared/Views/Chat/ChatView.swift @@ -14,6 +14,29 @@ import Combine private let memberImageSize: CGFloat = 34 +private func shouldShowAvatar(_ current: ChatItem, _ older: ChatItem?) -> Bool { + let oldIsGroupRcv = switch older?.chatDir { + case .groupRcv: true + case .channelRcv: true + default: false + } + let sameMember = switch (older?.chatDir, current.chatDir) { + case (.groupRcv(let oldMember), .groupRcv(let member)): + oldMember.memberId == member.memberId + case (.channelRcv, .channelRcv): + true + default: + false + } + if case .groupRcv = current.chatDir, (older == nil || (!oldIsGroupRcv || !sameMember)) { + return true + } else if case .channelRcv = current.chatDir, (older == nil || (!oldIsGroupRcv || !sameMember)) { + return true + } else { + return false + } +} + // Spec: spec/client/chat-view.md#ChatView struct ChatView: View { @EnvironmentObject var chatModel: ChatModel @@ -896,8 +919,14 @@ struct ChatView: View { } else { let voiceNoFrame = voiceWithoutFrame(ci) let channelReceived = !ci.chatDir.sent && cInfo.isChannel + // consecutive (no-avatar) received messages in channels drop the avatar-sized + // left padding (see .leading padding below), so they get the full row width here + // too — otherwise the reserved avatar inset would leave a gap on the right + let channelReceivedNoAvatar = channelReceived && !shouldShowAvatar(mergedItem.newest().item, mergedItem.oldest().nextItem) let maxWidth = cInfo.chatType == .group - ? voiceNoFrame || channelReceived + ? channelReceivedNoAvatar + ? g.size.width - 26 + : voiceNoFrame || channelReceived ? (g.size.width - 28) - 42 : (g.size.width - 28) * 0.84 - 42 : voiceNoFrame @@ -1733,29 +1762,6 @@ struct ChatView: View { ) } - func shouldShowAvatar(_ current: ChatItem, _ older: ChatItem?) -> Bool { - let oldIsGroupRcv = switch older?.chatDir { - case .groupRcv: true - case .channelRcv: true - default: false - } - let sameMember = switch (older?.chatDir, current.chatDir) { - case (.groupRcv(let oldMember), .groupRcv(let member)): - oldMember.memberId == member.memberId - case (.channelRcv, .channelRcv): - true - default: - false - } - if case .groupRcv = current.chatDir, (older == nil || (!oldIsGroupRcv || !sameMember)) { - return true - } else if case .channelRcv = current.chatDir, (older == nil || (!oldIsGroupRcv || !sameMember)) { - return true - } else { - return false - } - } - var body: some View { let last = isLastItem ? im.reversedChatItems.last : nil let listItem = merged.newest() @@ -1979,7 +1985,7 @@ struct ChatView: View { } chatItemWithMenu(ci, range, maxWidth, itemSeparation) .padding(.trailing) - .padding(.leading, 10 + memberImageSize + 12) + .padding(.leading, chat.chatInfo.isChannel ? nil : 10 + memberImageSize + 12) } .padding(.bottom, bottomPadding) } @@ -2076,7 +2082,7 @@ struct ChatView: View { } chatItemWithMenu(ci, range, maxWidth, itemSeparation) .padding(.trailing) - .padding(.leading, 10 + memberImageSize + 12) + .padding(.leading, chat.chatInfo.isChannel ? nil : 10 + memberImageSize + 12) } .padding(.bottom, bottomPadding) } diff --git a/apps/ios/Shared/Views/Chat/ComposeMessage/ComposeView.swift b/apps/ios/Shared/Views/Chat/ComposeMessage/ComposeView.swift index e308a145b9..9c40b2b395 100644 --- a/apps/ios/Shared/Views/Chat/ComposeMessage/ComposeView.swift +++ b/apps/ios/Shared/Views/Chat/ComposeMessage/ComposeView.swift @@ -392,38 +392,31 @@ struct ComposeView: View { } let ownerState = ownerRelayState + let subscriberState = subscriberRelayState if let gInfo = chat.chatInfo.groupInfo, gInfo.useRelays, ![.memRejected, .memLeft, .memRemoved, .memGroupDeleted].contains(gInfo.membership.memberStatus) { if gInfo.membership.memberRole == .owner { if let s = ownerState, s.relays.isEmpty || s.activeCount < s.relays.count { ownerChannelRelayBar(relays: s.relays, activeCount: s.activeCount, failedCount: s.failedCount, removedCount: s.removedCount) } - } else { - let hostnames = (chatModel.channelRelayHostnames[gInfo.groupId] ?? []).sorted() - let relayMembers = chatModel.groupMembers - .filter { $0.wrapped.memberRole == .relay && ![.memRemoved, .memGroupDeleted].contains($0.wrapped.memberStatus) } - .sorted { hostFromRelayLink($0.wrapped.relayLink ?? "") < hostFromRelayLink($1.wrapped.relayLink ?? "") } + } else if let s = subscriberState { let showProgress = !gInfo.nextConnectPrepared || composeState.inProgress - let removedCount = relayMembers.filter { relayMemberRemoved($0.wrapped.memberStatus) }.count - let connectedCount = relayMembers.filter { !relayMemberRemoved($0.wrapped.memberStatus) && $0.wrapped.activeConn?.connStatus == .ready && $0.wrapped.activeConn?.connFailedErr == nil }.count - let failedCount = relayMembers.filter { !relayMemberRemoved($0.wrapped.memberStatus) && $0.wrapped.activeConn?.connFailedErr != nil }.count - let resolvedCount = connectedCount + removedCount + failedCount - let total = relayMembers.count > 0 ? relayMembers.count : hostnames.count - if total == 0 || removedCount + failedCount > 0 || resolvedCount < total { + let resolvedCount = s.connectedCount + s.removedCount + s.failedCount + if s.total == 0 || s.removedCount + s.failedCount > 0 || resolvedCount < s.total { subscriberChannelRelayBar( - hostnames: hostnames, - relayMembers: relayMembers, - connectedCount: connectedCount, - removedCount: removedCount, - failedCount: failedCount, - total: total, + hostnames: s.hostnames, + relayMembers: s.relayMembers, + connectedCount: s.connectedCount, + removedCount: s.removedCount, + failedCount: s.failedCount, + total: s.total, showProgress: showProgress ) } } } - let userCantSendReason = chat.chatInfo.userCantSendReason(allRelaysBroken: ownerState?.noActiveRelays ?? false) + let userCantSendReason = chat.chatInfo.userCantSendReason(allRelaysBroken: (ownerState?.noActiveRelays ?? subscriberState?.noActiveRelays) ?? false) let composeEnabled = ( userCantSendReason == nil || (chat.chatInfo.groupInfo?.nextConnectPrepared ?? false) || @@ -748,8 +741,25 @@ struct ComposeView: View { return (relays, activeCount, failedCount, removedCount, noActiveRelays) } + private var subscriberRelayState: (hostnames: [String], relayMembers: [GMember], connectedCount: Int, removedCount: Int, failedCount: Int, total: Int, noActiveRelays: Bool)? { + guard let gInfo = chat.chatInfo.groupInfo, gInfo.useRelays, + gInfo.membership.memberRole != .owner, + ![.memRejected, .memLeft, .memRemoved, .memGroupDeleted].contains(gInfo.membership.memberStatus) + else { return nil } + let hostnames = (chatModel.channelRelayHostnames[gInfo.groupId] ?? []).sorted() + let relayMembers = chatModel.groupMembers + .filter { $0.wrapped.memberRole == .relay && ![.memRemoved, .memGroupDeleted].contains($0.wrapped.memberStatus) } + .sorted { hostFromRelayLink($0.wrapped.relayLink ?? "") < hostFromRelayLink($1.wrapped.relayLink ?? "") } + let removedCount = relayMembers.filter { relayMemberRemoved($0.wrapped.memberStatus) }.count + let connectedCount = relayMembers.filter { !relayMemberRemoved($0.wrapped.memberStatus) && $0.wrapped.activeConn?.connStatus == .ready && $0.wrapped.activeConn?.connFailedErr == nil }.count + let failedCount = relayMembers.filter { !relayMemberRemoved($0.wrapped.memberStatus) && $0.wrapped.activeConn?.connFailedErr != nil }.count + let total = relayMembers.count > 0 ? relayMembers.count : hostnames.count + let noActiveRelays = connectedCount == 0 && (removedCount + failedCount) == total + return (hostnames, relayMembers, connectedCount, removedCount, failedCount, total, noActiveRelays) + } + private var disabledText: LocalizedStringKey? { - chat.chatInfo.userCantSendReason(allRelaysBroken: ownerRelayState?.noActiveRelays ?? false)?.composeLabel + chat.chatInfo.userCantSendReason(allRelaysBroken: (ownerRelayState?.noActiveRelays ?? subscriberRelayState?.noActiveRelays) ?? false)?.composeLabel } @ViewBuilder private func ownerChannelRelayBar(relays: [GroupRelay], activeCount: Int, failedCount: Int, removedCount: Int) -> some View { diff --git a/apps/ios/Shared/Views/Chat/Group/AddGroupMembersView.swift b/apps/ios/Shared/Views/Chat/Group/AddGroupMembersView.swift index 336b4adfd1..108f4d4306 100644 --- a/apps/ios/Shared/Views/Chat/Group/AddGroupMembersView.swift +++ b/apps/ios/Shared/Views/Chat/Group/AddGroupMembersView.swift @@ -174,8 +174,9 @@ struct AddGroupMembersViewCommon: View { } addedMembersCb(selectedContacts) } catch { - let a = getErrorAlert(error, "Error adding member(s)") - alert = .error(title: a.title, error: a.message) + await MainActor.run { + showErrorAlert(error, NSLocalizedString("Error adding member(s)", comment: "")) + } } } } diff --git a/apps/ios/Shared/Views/Chat/Group/ChannelWebAccessView.swift b/apps/ios/Shared/Views/Chat/Group/ChannelWebAccessView.swift index dd46b7a117..df0867c470 100644 --- a/apps/ios/Shared/Views/Chat/Group/ChannelWebAccessView.swift +++ b/apps/ios/Shared/Views/Chat/Group/ChannelWebAccessView.swift @@ -148,7 +148,7 @@ struct ChannelWebAccessView: View { let existingAccess = pg.publicGroupAccess pg.publicGroupAccess = PublicGroupAccess( groupWebPage: trimmedPage.isEmpty ? nil : trimmedPage, - groupDomain: existingAccess?.groupDomain, + groupDomainClaim: existingAccess?.groupDomainClaim, domainWebPage: existingAccess?.domainWebPage ?? false, allowEmbedding: allowEmbedding ) diff --git a/apps/ios/Shared/Views/Chat/Group/GroupChatInfoView.swift b/apps/ios/Shared/Views/Chat/Group/GroupChatInfoView.swift index 41e24a6ced..358bf6c7d3 100644 --- a/apps/ios/Shared/Views/Chat/Group/GroupChatInfoView.swift +++ b/apps/ios/Shared/Views/Chat/Group/GroupChatInfoView.swift @@ -112,6 +112,7 @@ struct GroupChatInfoView: View { // TODO [relays] allow other owners to manage channel link (requires protocol changes to share link ownership) if groupInfo.isOwner && groupLink != nil { channelLinkButton() + channelSimplexNameButton() } else if let link = groupInfo.groupProfile.publicGroup?.groupLink { SimpleXLinkQRCode(uri: link) Button { @@ -331,6 +332,27 @@ struct GroupChatInfoView: View { .lineLimit(4) .fixedSize(horizontal: false, vertical: true) } + if let access = groupInfo.groupProfile.publicGroup?.publicGroupAccess, + let domain = access.groupDomainClaim?.shortName, + groupInfo.groupDomainVerified != nil || access.groupDomainClaim?.proof != nil { + SimplexNameView( + simplexName: "#\(domain)", + verified: groupInfo.groupDomainVerified, + verify: { + do { + let (gInfo, reason) = try await apiVerifyGroupDomain(groupInfo.groupId) + await MainActor.run { + chatModel.updateGroup(gInfo) + groupInfo = gInfo + } + return (gInfo.groupDomainVerified, reason) + } catch { + logger.error("apiVerifyGroupDomain: \(responseError(error))") + return nil + } + } + ) + } if let webPage = groupInfo.groupProfile.publicGroup?.publicGroupAccess?.groupWebPage, let url = URL(string: webPage) { Link(destination: url) { @@ -674,6 +696,34 @@ struct GroupChatInfoView: View { } } + private func channelSimplexNameButton() -> some View { + NavigationLink { + let domain = if let d = groupInfo.groupProfile.publicGroup?.publicGroupAccess?.groupDomainClaim?.shortName { "#\(d)" } else { "" } + SetSimplexDomainView( + title: "SimpleX name", + footer: "Let people join via name registered with this channel link.", + prompt: "#channelname.testing", + simplexName: domain, + save: { domain in + do { + var access = groupInfo.groupProfile.publicGroup?.publicGroupAccess ?? PublicGroupAccess() + access.groupDomainClaim = domain.map { SimplexDomainClaim(domain: $0) } + let gInfo = try await apiSetPublicGroupAccess(groupInfo.groupId, access: access) + await MainActor.run { + chatModel.updateGroup(gInfo) + groupInfo = gInfo + } + return true + } catch { + return false + } + } + ) + } label: { + Label("SimpleX name", systemImage: "number") + } + } + private func groupLinkDestinationView() -> some View { GroupLinkView( groupId: groupInfo.groupId, diff --git a/apps/ios/Shared/Views/Chat/Group/GroupLinkView.swift b/apps/ios/Shared/Views/Chat/Group/GroupLinkView.swift index 43d23878f5..8a9bcaf059 100644 --- a/apps/ios/Shared/Views/Chat/Group/GroupLinkView.swift +++ b/apps/ios/Shared/Views/Chat/Group/GroupLinkView.swift @@ -155,8 +155,9 @@ struct GroupLinkView: View { do { groupLink = try await apiGroupLinkMemberRole(groupId, memberRole: groupLinkMemberRole) } catch let error { - let a = getErrorAlert(error, "Error updating group link") - alert = .error(title: a.title, error: a.message) + await MainActor.run { + showErrorAlert(error, NSLocalizedString("Error updating group link", comment: "")) + } } } } @@ -188,8 +189,7 @@ struct GroupLinkView: View { logger.error("GroupLinkView apiCreateGroupLink: \(responseError(error))") await MainActor.run { creatingLink = false - let a = getErrorAlert(error, "Error creating group link") - alert = .error(title: a.title, error: a.message) + showErrorAlert(error, NSLocalizedString("Error creating group link", comment: "")) } } } @@ -230,8 +230,7 @@ struct GroupLinkView: View { logger.error("apiAddGroupShortLink: \(responseError(error))") await MainActor.run { creatingLink = false - let a = getErrorAlert(error, "Error adding short link") - alert = .error(title: a.title, error: a.message) + showErrorAlert(error, NSLocalizedString("Error adding short link", comment: "")) } } } diff --git a/apps/ios/Shared/Views/Chat/Group/GroupMemberInfoView.swift b/apps/ios/Shared/Views/Chat/Group/GroupMemberInfoView.swift index c87f97089c..5e2713f922 100644 --- a/apps/ios/Shared/Views/Chat/Group/GroupMemberInfoView.swift +++ b/apps/ios/Shared/Views/Chat/Group/GroupMemberInfoView.swift @@ -278,8 +278,9 @@ struct GroupMemberInfoView: View { } } catch let e { logger.error("apiContactQueueInfo error: \(responseError(e))") - let a = getErrorAlert(e, "Error") - await MainActor.run { alert = .error(title: a.title, error: a.message) } + await MainActor.run { + showErrorAlert(e, NSLocalizedString("Error", comment: "")) + } } } } @@ -473,10 +474,9 @@ struct GroupMemberInfoView: View { } } catch let error { logger.error("createMemberContactButton apiCreateMemberContact error: \(responseError(error))") - let a = getErrorAlert(error, "Error creating member contact") await MainActor.run { progressIndicator = false - alert = .error(title: a.title, error: a.message) + showErrorAlert(error, NSLocalizedString("Error creating member contact", comment: "")) } } } @@ -752,8 +752,9 @@ struct GroupMemberInfoView: View { } catch let error { newRole = mem.memberRole logger.error("apiMembersRole error: \(responseError(error))") - let a = getErrorAlert(error, "Error changing role") - alert = .error(title: a.title, error: a.message) + await MainActor.run { + showErrorAlert(error, NSLocalizedString("Error changing role", comment: "")) + } } } }, @@ -774,9 +775,8 @@ struct GroupMemberInfoView: View { } } catch let error { logger.error("switchMemberAddress apiSwitchGroupMember error: \(responseError(error))") - let a = getErrorAlert(error, "Error changing address") await MainActor.run { - alert = .error(title: a.title, error: a.message) + showErrorAlert(error, NSLocalizedString("Error changing address", comment: "")) } } } @@ -792,9 +792,8 @@ struct GroupMemberInfoView: View { } } catch let error { logger.error("abortSwitchMemberAddress apiAbortSwitchGroupMember error: \(responseError(error))") - let a = getErrorAlert(error, "Error aborting address change") await MainActor.run { - alert = .error(title: a.title, error: a.message) + showErrorAlert(error, NSLocalizedString("Error aborting address change", comment: "")) } } } @@ -811,9 +810,8 @@ struct GroupMemberInfoView: View { } } catch let error { logger.error("syncMemberConnection apiSyncGroupMemberRatchet error: \(responseError(error))") - let a = getErrorAlert(error, "Error synchronizing connection") await MainActor.run { - alert = .error(title: a.title, error: a.message) + showErrorAlert(error, NSLocalizedString("Error synchronizing connection", comment: "")) } } } diff --git a/apps/ios/Shared/Views/ChatList/ChatListNavLink.swift b/apps/ios/Shared/Views/ChatList/ChatListNavLink.swift index 76734dcb42..0ed78401b0 100644 --- a/apps/ios/Shared/Views/ChatList/ChatListNavLink.swift +++ b/apps/ios/Shared/Views/ChatList/ChatListNavLink.swift @@ -532,9 +532,7 @@ struct ChatListNavLink: View { .frameCompat(height: dynamicRowHeight) .swipeActions(edge: .trailing, allowsFullSwipe: true) { Button { - AlertManager.shared.showAlert(deleteContactConnectionAlert(contactConnection) { a in - AlertManager.shared.showAlertMsg(title: a.title, message: a.message) - }) + AlertManager.shared.showAlert(deleteContactConnectionAlert(contactConnection)) } label: { deleteLabel } @@ -698,7 +696,7 @@ func rejectContactRequestAlert(_ contactRequestId: Int64) -> Alert { ) } -func deleteContactConnectionAlert(_ contactConnection: PendingContactConnection, showError: @escaping (ErrorAlert) -> Void, success: @escaping () -> Void = {}) -> Alert { +func deleteContactConnectionAlert(_ contactConnection: PendingContactConnection, success: @escaping () -> Void = {}) -> Alert { Alert( title: Text("Delete pending connection?"), message: Text(contactConnection.displayName + "\n\n") @@ -715,7 +713,7 @@ func deleteContactConnectionAlert(_ contactConnection: PendingContactConnection, } } catch let error { await MainActor.run { - showError(getErrorAlert(error, "Error deleting connection")) + showErrorAlert(error, NSLocalizedString("Error deleting connection", comment: "")) } } } @@ -725,11 +723,7 @@ func deleteContactConnectionAlert(_ contactConnection: PendingContactConnection, } func connectContactViaAddress(_ contactId: Int64, _ incognito: Bool, showAlert: (Alert) -> Void) async -> Bool { - let (contact, alert) = await apiConnectContactViaAddress(incognito: incognito, contactId: contactId) - if let alert = alert { - showAlert(alert) - return false - } else if let contact = contact { + if let contact = await apiConnectContactViaAddress(incognito: incognito, contactId: contactId) { await MainActor.run { ChatModel.shared.updateContact(contact) } @@ -757,8 +751,9 @@ func joinGroup(_ groupId: Int64, _ onComplete: @escaping () async -> Void) { await onComplete() } catch let error { await onComplete() - let a = getErrorAlert(error, "Error joining group") - AlertManager.shared.showAlertMsg(title: a.title, message: a.message) + await MainActor.run { + showErrorAlert(error, NSLocalizedString("Error joining group", comment: "")) + } } func deleteGroup() async { @@ -773,12 +768,13 @@ func joinGroup(_ groupId: Int64, _ onComplete: @escaping () async -> Void) { } } -func getErrorAlert(_ error: Error, _ title: LocalizedStringKey) -> ErrorAlert { +func showErrorAlert(_ error: Error, _ title: String) { + let err = { String.localizedStringWithFormat(NSLocalizedString("Error: %@", comment: ""), responseError(error)) } if let r = error as? ChatError, let alert = getNetworkErrorAlert(r) { - return alert + showAlert(alert.title, message: alert.message ?? err()) } else { - return ErrorAlert(title: title, message: "Error: \(responseError(error))") + showAlert(title, message: err()) } } diff --git a/apps/ios/Shared/Views/ChatList/ChatListView.swift b/apps/ios/Shared/Views/ChatList/ChatListView.swift index d90149c7dd..bcef5cecf3 100644 --- a/apps/ios/Shared/Views/ChatList/ChatListView.swift +++ b/apps/ios/Shared/Views/ChatList/ChatListView.swift @@ -151,7 +151,7 @@ struct ChatListView: View { @FocusState private var searchFocussed @State private var searchText = "" @State private var searchShowingSimplexLink = false - @State private var searchChatFilteredBySimplexLink: String? = nil + @State private var searchChatFilteredBySimplexLink: Set = [] @State private var scrollToSearchBar = false @State private var userPickerShown: Bool = false @State private var sheet: SomeSheet? = nil @@ -511,8 +511,8 @@ struct ChatListView: View { // Spec: spec/client/chat-list.md#filteredChats private func filteredChats() -> [Chat] { - if let linkChatId = searchChatFilteredBySimplexLink { - return chatModel.chats.filter { $0.id == linkChatId } + if !searchChatFilteredBySimplexLink.isEmpty { + return chatModel.chats.filter { searchChatFilteredBySimplexLink.contains($0.id) } } else { let s = searchString() return s == "" @@ -626,13 +626,21 @@ struct ChatListSearchBar: View { @FocusState.Binding var searchFocussed: Bool @Binding var searchText: String @Binding var searchShowingSimplexLink: Bool - @Binding var searchChatFilteredBySimplexLink: String? + @Binding var searchChatFilteredBySimplexLink: Set @Binding var parentSheet: SomeSheet? @State private var ignoreSearchTextChange = false + // when the search text is a SimpleX name, the string to connect to (with @/# preserved); nil otherwise + @State private var connectNameCandidate: String? = nil + @State private var nameSearchTask: Task? = nil var body: some View { VStack(spacing: 12) { - ScrollView([.horizontal], showsIndicators: false) { TagsView(parentSheet: $parentSheet, searchText: $searchText) } + // a typed name replaces the list tags with a row to connect to it (as on Android mobile) + if let candidate = connectNameCandidate { + connectByNameRow(candidate) + } else { + ScrollView([.horizontal], showsIndicators: false) { TagsView(parentSheet: $parentSheet, searchText: $searchText) } + } HStack(spacing: 12) { HStack(spacing: 4) { Image(systemName: "magnifyingglass") @@ -675,24 +683,50 @@ struct ChatListSearchBar: View { if ignoreSearchTextChange { ignoreSearchTextChange = false } else { - switch strConnectTarget(t.trimmingCharacters(in: .whitespaces)) { + let s = t.trimmingCharacters(in: .whitespaces) + switch strConnectTarget(s) { case let .link(text, _, linkText): + nameSearchTask?.cancel() + nameSearchTask = nil searchFocussed = false ignoreSearchTextChange = true searchText = linkText searchShowingSimplexLink = true - searchChatFilteredBySimplexLink = nil + searchChatFilteredBySimplexLink = [] + connectNameCandidate = nil connect(text) - case let .name(nameInfo): - showUnsupportedNameAlert(nameInfo) - case .none: - if t != "" { + default: + // not a link: a recognized SimpleX name shows the connect-by-name row (in place of the + // list tags) and, debounced, resolves locally per keystroke to narrow the list to the + // matching known chat(s); tapping the row connects online. Clear the filter immediately so + // the list falls back to text search until the search returns. + let candidate = nameSearchCandidate(s) + connectNameCandidate = candidate + searchShowingSimplexLink = false + searchChatFilteredBySimplexLink = [] + nameSearchTask?.cancel() + nameSearchTask = nil + if let candidate = candidate { + nameSearchTask = Task { @MainActor in + try? await Task.sleep(nanoseconds: 300_000_000) + if Task.isCancelled { return } + // a bare name can be a contact or a channel: search both and keep every match + let targets = candidate.hasPrefix("@") || candidate.hasPrefix("#") ? [candidate] : ["@\(candidate)", "#\(candidate)"] + var ids: [String] = [] + for name in targets { + let plan = await apiConnectPlan(connLink: name, resolveMode: .never, inProgress: BoxedValue(false)) + if Task.isCancelled { return } + if let id = knownChatId(plan) { ids.append(id) } + } + searchChatFilteredBySimplexLink = Set(ids) + // drop the row only when every searched type is already known locally + if ids.count == targets.count { connectNameCandidate = nil } + } + } else if t != "" { searchFocussed = true } else { ConnectProgressManager.shared.cancelConnectProgress() } - searchShowingSimplexLink = false - searchChatFilteredBySimplexLink = nil } } } @@ -721,6 +755,33 @@ struct ChatListSearchBar: View { } } + // Row shown in place of the list tags when the search text is a SimpleX name. The @ icon marks a + // contact name, the tag icon a channel/other name; tapping hides the keyboard, connects online, and + // clears the field. + private func connectByNameRow(_ name: String) -> some View { + HStack(spacing: 4) { + Image(systemName: name.hasPrefix("@") ? "at" : "number") + .foregroundColor(theme.colors.primary) + Text(String.localizedStringWithFormat(NSLocalizedString("Connect to %@", comment: "new chat action"), name)) + .foregroundColor(theme.colors.primary) + Spacer() + } + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) + .onTapGesture { + searchFocussed = false + planAndConnect( + name, + theme: theme, + dismiss: false, + cleanup: { + searchText = "" + connectNameCandidate = nil + } + ) + } + } + private func connect(_ link: String) { planAndConnect( link, @@ -730,12 +791,72 @@ struct ChatListSearchBar: View { searchText = "" searchFocussed = false }, - filterKnownContact: { searchChatFilteredBySimplexLink = $0.id }, - filterKnownGroup: { searchChatFilteredBySimplexLink = $0.id } + filterKnownContact: { searchChatFilteredBySimplexLink = [$0.id] }, + filterKnownGroup: { searchChatFilteredBySimplexLink = [$0.id] } ) } } +// Default top-level part used to complete a bare name typed in the search field (search field only; +// the message parser and the wire format are unchanged). +private let DEFAULT_NAME_TLD = "testing" +// Shortest name that offers the button, so it is discoverable but does not flash on a single letter. +private let MIN_NAME_LENGTH = 2 + +private func isNameLabel(_ s: String) -> Bool { + s.count >= 1 && s.count <= 63 && s.range(of: "^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$", options: .regularExpression) != nil +} + +// On-device candidate for connecting by SimpleX name: the string sent to the core to resolve it. +// The chat id a local (.never) search resolved to — a contact, business, or channel — or nil on a miss. +// A name-resolved chat may be prepared in the store but not yet listed, so add it so the filter can surface it. +@MainActor +func knownChatId(_ result: ConnectionPlanResult?) -> String? { + guard let plan = result?.connectionPlan else { return nil } + let m = ChatModel.shared + switch plan { + case let .contactAddress(contactAddressPlan): + if case let .known(contact) = contactAddressPlan { + if m.getContactChat(contact.contactId) == nil { + m.addChat(Chat(chatInfo: .direct(contact: contact), chatItems: [])) + } + return contact.id + } + return nil + case let .groupLink(groupLinkPlan): + switch groupLinkPlan { + case .known(let groupInfo), .ownLink(let groupInfo): + if m.getGroupChat(groupInfo.groupId) == nil { + m.addChat(Chat(chatInfo: .group(groupInfo: groupInfo, groupChatScope: nil), chatItems: [])) + } + return groupInfo.id + default: + return nil + } + default: + return nil + } +} + +// Mirrors the domain grammar (nameLabelP/mkDomain in SimplexName.hs): an optional @/# prefix, then +// dot-separated ASCII labels; a dotless word is completed with the default top-level part. Returns +// the string to send (keeping @/# so the type is preserved), or nil when the text is not a name. +func nameSearchCandidate(_ str: String) -> String? { + let text = str.trimmingCharacters(in: .whitespaces) + let prefix: Character? = text.first.flatMap { $0 == "@" || $0 == "#" ? $0 : nil } + let core = prefix != nil ? String(text.dropFirst()) : text + if core.isEmpty { return nil } + let labels = core.split(separator: ".", omittingEmptySubsequences: false) + if labels.contains(where: { !isNameLabel(String($0)) }) { return nil } + if labels.count > 1 { + return text // already has a top-level part + } else if core.count >= MIN_NAME_LENGTH { + return "\(prefix.map(String.init) ?? "")\(core).\(DEFAULT_NAME_TLD)" + } else { + return nil + } +} + struct TagsView: View { @EnvironmentObject var chatTagsModel: ChatTagsModel @EnvironmentObject var chatModel: ChatModel diff --git a/apps/ios/Shared/Views/ChatList/ContactConnectionInfo.swift b/apps/ios/Shared/Views/ChatList/ContactConnectionInfo.swift index 124c5ee7ba..c777eea80c 100644 --- a/apps/ios/Shared/Views/ChatList/ContactConnectionInfo.swift +++ b/apps/ios/Shared/Views/ChatList/ContactConnectionInfo.swift @@ -103,11 +103,7 @@ struct ContactConnectionInfo: View { .alert(item: $alert) { _alert in switch _alert { case .deleteInvitationAlert: - return deleteContactConnectionAlert(contactConnection) { a in - alert = .error(title: a.title, error: a.message) - } success: { - dismiss() - } + return deleteContactConnectionAlert(contactConnection, success: { dismiss() }) case let .error(title, error): return mkAlert(title: title, message: error) } } diff --git a/apps/ios/Shared/Views/Helpers/ShareSheet.swift b/apps/ios/Shared/Views/Helpers/ShareSheet.swift index 82d17cd2b1..670cc7cae0 100644 --- a/apps/ios/Shared/Views/Helpers/ShareSheet.swift +++ b/apps/ios/Shared/Views/Helpers/ShareSheet.swift @@ -54,6 +54,10 @@ func showAlert( } } +func showAlert(_ a: (title: String, message: String?)) { + showAlert(a.title, message: a.message) +} + func showAlert( _ title: String, message: String? = nil, @@ -140,8 +144,10 @@ class OpenChatAlertViewController: UIViewController { private let information: String? private let cancelTitle: String private let confirmTitle: String? + private let secondTitle: String? private let onCancel: () -> Void private let onConfirm: (() -> Void)? + private let onSecond: (() -> Void)? init( profileName: String, @@ -152,8 +158,10 @@ class OpenChatAlertViewController: UIViewController { information: String? = nil, cancelTitle: String = "Cancel", confirmTitle: String? = "Open", + secondTitle: String? = nil, onCancel: @escaping () -> Void = {}, - onConfirm: (() -> Void)? = nil + onConfirm: (() -> Void)? = nil, + onSecond: (() -> Void)? = nil ) { self.profileName = profileName self.profileFullName = profileFullName @@ -163,8 +171,10 @@ class OpenChatAlertViewController: UIViewController { self.information = information self.cancelTitle = cancelTitle self.confirmTitle = confirmTitle + self.secondTitle = secondTitle self.onCancel = onCancel self.onConfirm = onConfirm + self.onSecond = onSecond super.init(nibName: nil, bundle: nil) modalPresentationStyle = .overFullScreen @@ -273,7 +283,38 @@ class OpenChatAlertViewController: UIViewController { let buttonStack: UIStackView var buttonDividerConstraints: [NSLayoutConstraint] = [] - if let confirmTitle { + if let confirmTitle, let secondTitle { + // Three buttons (a sibling action is present) — always vertical + let confirmButton = UIButton(type: .system) + confirmButton.setTitle(confirmTitle, for: .normal) + confirmButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: .body) + confirmButton.addTarget(self, action: #selector(confirmTapped), for: .touchUpInside) + + let secondButton = UIButton(type: .system) + secondButton.setTitle(secondTitle, for: .normal) + secondButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: .body) + secondButton.addTarget(self, action: #selector(secondTapped), for: .touchUpInside) + + buttonStack = UIStackView(arrangedSubviews: [confirmButton, secondButton, cancelButton]) + buttonStack.axis = .vertical + buttonStack.distribution = .fillEqually + buttonStack.spacing = 0 + buttonStack.translatesAutoresizingMaskIntoConstraints = false + buttonStack.heightAnchor.constraint(greaterThanOrEqualToConstant: alertButtonHeight * 3).isActive = true + + for button in [secondButton, cancelButton] { + let divider = UIView() + divider.backgroundColor = UIColor.separator + divider.translatesAutoresizingMaskIntoConstraints = false + buttonStack.addSubview(divider) + buttonDividerConstraints += [ + divider.leadingAnchor.constraint(equalTo: containerView.leadingAnchor), + divider.trailingAnchor.constraint(equalTo: containerView.trailingAnchor), + divider.bottomAnchor.constraint(equalTo: button.topAnchor), + divider.heightAnchor.constraint(equalToConstant: 1 / UIScreen.main.scale) + ] + } + } else if let confirmTitle { let confirmButton = UIButton(type: .system) confirmButton.setTitle(confirmTitle, for: .normal) confirmButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: .body) @@ -368,6 +409,12 @@ class OpenChatAlertViewController: UIViewController { self.onConfirm?() } } + + @objc private func secondTapped() { + dismiss(animated: true) { + self.onSecond?() + } + } } @@ -381,8 +428,10 @@ func showOpenChatAlert( information: String? = nil, cancelTitle: String = "Cancel", confirmTitle: String? = "Open", + secondTitle: String? = nil, onCancel: @escaping () -> Void = {}, - onConfirm: (() -> Void)? = nil + onConfirm: (() -> Void)? = nil, + onSecond: (() -> Void)? = nil ) { let themedView = profileImage.environmentObject(theme) let hostingController = UIHostingController(rootView: themedView) @@ -399,8 +448,10 @@ func showOpenChatAlert( information: information, cancelTitle: cancelTitle, confirmTitle: confirmTitle, + secondTitle: secondTitle, onCancel: onCancel, - onConfirm: onConfirm + onConfirm: onConfirm, + onSecond: onSecond ) topVC.present(alertVC, animated: true) } diff --git a/apps/ios/Shared/Views/NewChat/NewChatMenuButton.swift b/apps/ios/Shared/Views/NewChat/NewChatMenuButton.swift index f99b03086e..a3e6d2ee2f 100644 --- a/apps/ios/Shared/Views/NewChat/NewChatMenuButton.swift +++ b/apps/ios/Shared/Views/NewChat/NewChatMenuButton.swift @@ -389,8 +389,17 @@ struct ContactsListSearchBar: View { searchShowingSimplexLink = true searchChatFilteredBySimplexLink = nil connect(text) - case let .name(nameInfo): - showUnsupportedNameAlert(nameInfo) + case let .name(text, _): + searchFocussed = false + planAndConnect( + text, + theme: theme, + dismiss: true, + cleanup: { + searchText = "" + searchFocussed = false + } + ) case .none: if t != "" { searchFocussed = true diff --git a/apps/ios/Shared/Views/NewChat/NewChatView.swift b/apps/ios/Shared/Views/NewChat/NewChatView.swift index 67fd353ebc..a87b9b46f4 100644 --- a/apps/ios/Shared/Views/NewChat/NewChatView.swift +++ b/apps/ios/Shared/Views/NewChat/NewChatView.swift @@ -204,8 +204,7 @@ struct NewChatView: View { creatingConnReq = true Task { _ = try? await Task.sleep(nanoseconds: 250_000000) - let (r, apiAlert) = await apiAddContact(incognito: incognitoGroupDefault.get()) - if let (connLink, pcc) = r { + if let (connLink, pcc) = await apiAddContact(incognito: incognitoGroupDefault.get()) { await MainActor.run { m.updateContactConnection(pcc) m.showingInvitation = ShowingInvitation(pcc: pcc, connChatUsed: false) @@ -215,9 +214,6 @@ struct NewChatView: View { } else { await MainActor.run { creatingConnReq = false - if let apiAlert = apiAlert { - alert = .newChatSomeAlert(alert: SomeAlert(alert: apiAlert, id: "createInvitation error")) - } } } } @@ -434,15 +430,9 @@ private struct ActiveProfilePicker: View { profileSwitchStatus = .idle incognitoEnabled = !incognito logger.error("apiSetConnectionIncognito error: \(responseError(error))") - let err = getErrorAlert(error, "Error changing to incognito!") - - alert = SomeAlert( - alert: Alert( - title: Text(err.title), - message: Text(err.message ?? "Error: \(responseError(error))") - ), - id: "setConnectionIncognitoError" - ) + await MainActor.run { + showErrorAlert(error, NSLocalizedString("Error changing to incognito!", comment: "")) + } } } } @@ -494,14 +484,7 @@ private struct ActiveProfilePicker: View { if let currentUser = chatModel.currentUser { selectedProfile = currentUser } - let err = getErrorAlert(error, "Error changing connection profile") - alert = SomeAlert( - alert: Alert( - title: Text(err.title), - message: Text(err.message ?? "Error: \(responseError(error))") - ), - id: "changeConnectionUserError" - ) + showErrorAlert(error, NSLocalizedString("Error changing connection profile", comment: "")) } } } @@ -669,8 +652,9 @@ private struct ConnectView: View { case let .link(text, _, _): pastedLink = text connect(pastedLink) - case let .name(nameInfo): - showUnsupportedNameAlert(nameInfo) + case let .name(text, _): + pastedLink = text + connect(pastedLink) case .none: alert = .newChatSomeAlert(alert: SomeAlert( alert: mkAlert(title: "Invalid link", message: "The text you pasted is not a SimpleX link."), @@ -869,7 +853,7 @@ func strIsSimplexLink(_ str: String) -> Bool { enum ConnectTarget { case link(text: String, linkType: SimplexLinkType, linkText: String) - case name(SimplexNameInfo) + case name(text: String, nameInfo: SimplexNameInfo) } func strConnectTarget(_ str: String) -> ConnectTarget? { @@ -878,28 +862,14 @@ func strConnectTarget(_ str: String) -> ConnectTarget? { return if links.count == 1, case let .simplexLink(_, linkType, _, smpHosts) = links[0].format { .link(text: links[0].text, linkType: linkType, linkText: simplexLinkText(linkType, smpHosts)) } else if links.isEmpty, - case let .simplexName(nameInfo) = parsedMd?.first(where: { if case .simplexName = $0.format { true } else { false } })?.format { - .name(nameInfo) + let nameFt = parsedMd?.first(where: { if case .simplexName = $0.format { true } else { false } }), + case let .simplexName(nameInfo) = nameFt.format { + .name(text: nameFt.text, nameInfo: nameInfo) } else { nil } } -func showUnsupportedNameAlert(_ nameInfo: SimplexNameInfo) { - let upgrade = " " + NSLocalizedString("Please upgrade the app.", comment: "alert message") - if nameInfo.nameType == .contact { - showAlert( - NSLocalizedString("Unsupported contact name", comment: "alert title"), - message: NSLocalizedString("Connecting via contact name requires a newer app version.", comment: "alert message") + upgrade - ) - } else { - showAlert( - NSLocalizedString("Unsupported channel name", comment: "alert title"), - message: NSLocalizedString("Connecting via channel name requires a newer app version.", comment: "alert message") + upgrade - ) - } -} - struct IncognitoToggle: View { @EnvironmentObject var theme: AppTheme @Binding var incognitoEnabled: Bool @@ -1145,6 +1115,9 @@ private func showPrepareContactAlert( connectionLink: CreatedConnLink, contactShortLinkData: ContactShortLinkData, ownerVerification: OwnerVerification? = nil, + verifiedDomain: SimplexDomain? = nil, + connectOtherButton: String? = nil, + connectOtherLink: String? = nil, theme: AppTheme, dismiss: Bool, cleanup: (() -> Void)? @@ -1167,11 +1140,12 @@ private func showPrepareContactAlert( information: ownerVerificationMessage(ownerVerification), cancelTitle: NSLocalizedString("Cancel", comment: "new chat action"), confirmTitle: NSLocalizedString("Open new chat", comment: "new chat action"), + secondTitle: connectOtherButton, onCancel: { cleanup?() }, onConfirm: { Task { do { - let chat = try await apiPrepareContact(connLink: connectionLink, contactShortLinkData: contactShortLinkData) + let chat = try await apiPrepareContact(connLink: connectionLink, contactShortLinkData: contactShortLinkData, verifiedDomain: verifiedDomain) await MainActor.run { ChatModel.shared.addChat(Chat(chat)) openKnownChat(chat.id, dismiss: dismiss, cleanup: cleanup) @@ -1184,6 +1158,9 @@ private func showPrepareContactAlert( } } } + }, + onSecond: connectOtherLink.map { link in + { planAndConnect(link, theme: theme, dismiss: dismiss, cleanup: cleanup) } } ) } @@ -1193,6 +1170,9 @@ private func showPrepareGroupAlert( groupShortLinkInfo: GroupShortLinkInfo?, groupShortLinkData: GroupShortLinkData, ownerVerification: OwnerVerification? = nil, + verifiedDomain: SimplexDomain? = nil, + connectOtherButton: String? = nil, + connectOtherLink: String? = nil, theme: AppTheme, dismiss: Bool, cleanup: (() -> Void)? @@ -1217,11 +1197,12 @@ private func showPrepareGroupAlert( confirmTitle: isChannel ? NSLocalizedString("Open new channel", comment: "new chat action") : NSLocalizedString("Open new group", comment: "new chat action"), + secondTitle: connectOtherButton, onCancel: { cleanup?() }, onConfirm: { Task { do { - let chat = try await apiPrepareGroup(connLink: connectionLink, directLink: groupShortLinkInfo?.direct ?? true, groupShortLinkData: groupShortLinkData) + let chat = try await apiPrepareGroup(connLink: connectionLink, directLink: groupShortLinkInfo?.direct ?? true, groupShortLinkData: groupShortLinkData, verifiedDomain: verifiedDomain) await MainActor.run { if let relays = groupShortLinkInfo?.groupRelays, !relays.isEmpty, case let .group(gInfo, _) = chat.chatInfo { @@ -1238,6 +1219,9 @@ private func showPrepareGroupAlert( } } } + }, + onSecond: connectOtherLink.map { link in + { planAndConnect(link, theme: theme, dismiss: dismiss, cleanup: cleanup) } } ) } @@ -1245,7 +1229,9 @@ private func showPrepareGroupAlert( private func showOpenKnownContactAlert( _ contact: Contact, theme: AppTheme, - dismiss: Bool + dismiss: Bool, + connectOtherButton: String? = nil, + connectOtherLink: String? = nil ) { showOpenChatAlert( profileName: contact.profile.displayName, @@ -1263,8 +1249,12 @@ private func showOpenKnownContactAlert( contact.nextConnectPrepared ? NSLocalizedString("Open new chat", comment: "new chat action") : NSLocalizedString("Open chat", comment: "new chat action"), + secondTitle: connectOtherButton, onConfirm: { openKnownContact(contact, dismiss: dismiss, cleanup: nil) + }, + onSecond: connectOtherLink.map { link in + { planAndConnect(link, theme: theme, dismiss: dismiss) } } ) } @@ -1272,7 +1262,9 @@ private func showOpenKnownContactAlert( private func showOpenKnownGroupAlert( _ groupInfo: GroupInfo, theme: AppTheme, - dismiss: Bool + dismiss: Bool, + connectOtherButton: String? = nil, + connectOtherLink: String? = nil ) { let subscriberCount = groupInfo.groupSummary.publicMemberCount.map { "\($0) subscribers" } showOpenChatAlert( @@ -1302,8 +1294,12 @@ private func showOpenKnownGroupAlert( ? NSLocalizedString("Open new chat", comment: "new chat action") : NSLocalizedString("Open chat", comment: "new chat action") ), + secondTitle: connectOtherButton, onConfirm: { openKnownGroup(groupInfo, dismiss: dismiss, cleanup: nil) + }, + onSecond: connectOtherLink.map { link in + { planAndConnect(link, theme: theme, dismiss: dismiss) } } ) } @@ -1319,10 +1315,6 @@ func planAndConnect( filterKnownGroup: ((GroupInfo) -> Void)? = nil ) { switch strConnectTarget(shortOrFullLink) { - case let .name(nameInfo): - showUnsupportedNameAlert(nameInfo) - cleanup?() - return case let .link(_, linkType, _): if linkType == .relay { showAlert( @@ -1332,7 +1324,9 @@ func planAndConnect( cleanup?() return } - case .none: break + // A SimplexName falls through to apiConnectPlan, which resolves it on the + // core (the /_connect plan command accepts a name target, not only a link). + case .name, .none: break } ConnectProgressManager.shared.cancelConnectProgress() let inProgress = BoxedValue(true) @@ -1344,12 +1338,25 @@ func planAndConnect( func connectTask(_ inProgress: BoxedValue) { Task { - let (result, alert) = await apiConnectPlan(connLink: shortOrFullLink, linkOwnerSig: linkOwnerSig, inProgress: inProgress) + let result = await apiConnectPlan(connLink: shortOrFullLink, linkOwnerSig: linkOwnerSig, inProgress: inProgress) await MainActor.run { ConnectProgressManager.shared.stopConnectProgress() } if !inProgress.boxedValue { return } - if let (connectionLink, connectionPlan) = result { + if let result { + let connectionLink = result.connLink + let connectionPlan = result.connectionPlan + let planSimplexName = result.planSimplexName + // the name can also resolve to the other kind; its type picks the verb, its short form the label and target + let connectOtherLink = result.otherSimplexName?.shortStr + let connectOtherButton: String? = result.otherSimplexName.map { info in + String.localizedStringWithFormat( + info.nameType == .publicGroup + ? NSLocalizedString("Join channel %@", comment: "new chat action") + : NSLocalizedString("Connect to %@", comment: "new chat action"), + info.shortStr + ) + } switch connectionPlan { case let .invitationLink(ilp): switch ilp { @@ -1424,6 +1431,9 @@ func planAndConnect( connectionLink: connectionLink, contactShortLinkData: contactSLinkData, ownerVerification: ownerVerification, + verifiedDomain: planSimplexName?.nameDomain, + connectOtherButton: connectOtherButton, + connectOtherLink: connectOtherLink, theme: theme, dismiss: dismiss, cleanup: cleanup @@ -1472,16 +1482,19 @@ func planAndConnect( if let f = filterKnownContact { f(contact) } else { - showOpenKnownContactAlert(contact, theme: theme, dismiss: dismiss) + showOpenKnownContactAlert(contact, theme: theme, dismiss: dismiss, connectOtherButton: connectOtherButton, connectOtherLink: connectOtherLink) } } case let .known(contact): logger.debug("planAndConnect, .contactAddress, .known") await MainActor.run { + if ChatModel.shared.getContactChat(contact.contactId) == nil { + ChatModel.shared.addChat(Chat(chatInfo: .direct(contact: contact))) + } if let f = filterKnownContact { f(contact) } else { - showOpenKnownContactAlert(contact, theme: theme, dismiss: dismiss) + showOpenKnownContactAlert(contact, theme: theme, dismiss: dismiss, connectOtherButton: connectOtherButton, connectOtherLink: connectOtherLink) } } case let .contactViaAddress(contact): @@ -1505,6 +1518,9 @@ func planAndConnect( groupShortLinkInfo: groupShortLinkInfo_, groupShortLinkData: groupSLinkData, ownerVerification: ownerVerification, + verifiedDomain: planSimplexName?.nameDomain, + connectOtherButton: connectOtherButton, + connectOtherLink: connectOtherLink, theme: theme, dismiss: dismiss, cleanup: cleanup @@ -1557,10 +1573,13 @@ func planAndConnect( case let .known(groupInfo): logger.debug("planAndConnect, .groupLink, .known") await MainActor.run { + if ChatModel.shared.getGroupChat(groupInfo.groupId) == nil { + ChatModel.shared.addChat(Chat(chatInfo: .group(groupInfo: groupInfo, groupChatScope: nil))) + } if let f = filterKnownGroup { f(groupInfo) } else { - showOpenKnownGroupAlert(groupInfo, theme: theme, dismiss: dismiss) + showOpenKnownGroupAlert(groupInfo, theme: theme, dismiss: dismiss, connectOtherButton: connectOtherButton, connectOtherLink: connectOtherLink) } } case let .noRelays(groupSLinkData_): @@ -1628,17 +1647,8 @@ func planAndConnect( cleanup: cleanup ) } - } else { - await MainActor.run { - if let alert { - dismissAllSheets(animated: true) { - AlertManager.shared.showAlert(alert) - cleanup?() - } - } else { - cleanup?() - } - } + } else if let cleanup { + await MainActor.run { cleanup() } } } } diff --git a/apps/ios/Shared/Views/Onboarding/CreateSimpleXAddress.swift b/apps/ios/Shared/Views/Onboarding/CreateSimpleXAddress.swift index ab84bed7df..b348057b8a 100644 --- a/apps/ios/Shared/Views/Onboarding/CreateSimpleXAddress.swift +++ b/apps/ios/Shared/Views/Onboarding/CreateSimpleXAddress.swift @@ -86,12 +86,10 @@ struct CreateSimpleXAddress: View { await MainActor.run { progressIndicator = false } } catch let error { logger.error("CreateSimpleXAddress create address: \(responseError(error))") - await MainActor.run { progressIndicator = false } - let a = getErrorAlert(error, "Error creating address") - AlertManager.shared.showAlertMsg( - title: a.title, - message: a.message - ) + await MainActor.run { + progressIndicator = false + showErrorAlert(error, NSLocalizedString("Error creating address", comment: "")) + } } } } label: { @@ -156,11 +154,7 @@ struct CreateSimpleXAddress: View { } case let .failure(error): logger.error("CreateSimpleXAddress share via email: \(responseError(error))") - let a = getErrorAlert(error, "Error sending email") - AlertManager.shared.showAlertMsg( - title: a.title, - message: a.message - ) + showErrorAlert(error, NSLocalizedString("Error sending email", comment: "")) } mailViewResult = nil } diff --git a/apps/ios/Shared/Views/Onboarding/YourNetwork.swift b/apps/ios/Shared/Views/Onboarding/YourNetwork.swift index d3727e196e..015a2be491 100644 --- a/apps/ios/Shared/Views/Onboarding/YourNetwork.swift +++ b/apps/ios/Shared/Views/Onboarding/YourNetwork.swift @@ -180,11 +180,9 @@ struct YourNetworkView: View { m.notificationMode = notificationMode } } catch let error { - let a = getErrorAlert(error, "Error enabling notifications") - AlertManager.shared.showAlertMsg( - title: a.title, - message: a.message - ) + await MainActor.run { + showErrorAlert(error, NSLocalizedString("Error enabling notifications", comment: "")) + } } } } diff --git a/apps/ios/Shared/Views/RemoteAccess/ConnectDesktopView.swift b/apps/ios/Shared/Views/RemoteAccess/ConnectDesktopView.swift index 01b25baed8..24ae5cffca 100644 --- a/apps/ios/Shared/Views/RemoteAccess/ConnectDesktopView.swift +++ b/apps/ios/Shared/Views/RemoteAccess/ConnectDesktopView.swift @@ -535,8 +535,7 @@ struct ConnectDesktopView: View { } private func errorAlert(_ error: Error) { - let a = getErrorAlert(error, "Error") - alert = .error(title: a.title, error: a.message) + showErrorAlert(error, NSLocalizedString("Error", comment: "")) } } diff --git a/apps/ios/Shared/Views/UserSettings/NetworkAndServers/NetworkAndServers.swift b/apps/ios/Shared/Views/UserSettings/NetworkAndServers/NetworkAndServers.swift index 24cf088918..8095c0297e 100644 --- a/apps/ios/Shared/Views/UserSettings/NetworkAndServers/NetworkAndServers.swift +++ b/apps/ios/Shared/Views/UserSettings/NetworkAndServers/NetworkAndServers.swift @@ -111,13 +111,16 @@ struct NetworkAndServers: View { Button("Save servers", action: { saveServers($ss.servers.currUserServers, $ss.servers.userServers) }) .disabled(!serversCanBeSaved(ss.servers.currUserServers, ss.servers.userServers, ss.servers.serverErrors)) } footer: { - if let errStr = globalServersError(ss.servers.serverErrors) { - ServersErrorView(errStr: errStr) + let errs = globalServersErrors(ss.servers.serverErrors) + if !errs.isEmpty { + ForEach(errs, id: \.self) { err in + ServersErrorView(errStr: err) + } } else if !ss.servers.serverErrors.isEmpty { ServersErrorView(errStr: NSLocalizedString("Errors in servers configuration.", comment: "servers error")) } - if let warnStr = globalServersWarning(ss.servers.serverWarnings) { - ServersWarningView(warnStr: warnStr) + ForEach(globalServersWarnings(ss.servers.serverWarnings), id: \.self) { warn in + ServersWarningView(warnStr: warn) } } @@ -397,17 +400,12 @@ struct ServersWarningView: View { } } -func globalServersError(_ serverErrors: [UserServersError]) -> String? { - for err in serverErrors { - if let errStr = err.globalError { - return errStr - } - } - return nil +func globalServersErrors(_ serverErrors: [UserServersError]) -> [String] { + serverErrors.compactMap { $0.globalError } } -func globalServersWarning(_ serverWarnings: [UserServersWarning]) -> String? { - for warn in serverWarnings { +func globalServersWarnings(_ serverWarnings: [UserServersWarning]) -> [String] { + serverWarnings.map { warn in switch warn { case let .noChatRelays(user): let text = NSLocalizedString("No chat relays enabled.", comment: "servers warning") @@ -417,9 +415,16 @@ func globalServersWarning(_ serverWarnings: [UserServersWarning]) -> String? { user.localDisplayName ) + " " + text } else { return text } + case let .noNamesServers(user): + let text = NSLocalizedString("No servers to resolve names.", comment: "servers warning") + if let user = user { + return String.localizedStringWithFormat( + NSLocalizedString("For chat profile %@:", comment: "servers warning"), + user.localDisplayName + ) + " " + text + } else { return text } } } - return nil } func bindingForChatRelays(_ userServers: Binding<[UserOperatorServers]>, _ opIndex: Int) -> Binding<[UserChatRelay]> { diff --git a/apps/ios/Shared/Views/UserSettings/NetworkAndServers/OperatorView.swift b/apps/ios/Shared/Views/UserSettings/NetworkAndServers/OperatorView.swift index 26f24f2f0f..4e2f1992d6 100644 --- a/apps/ios/Shared/Views/UserSettings/NetworkAndServers/OperatorView.swift +++ b/apps/ios/Shared/Views/UserSettings/NetworkAndServers/OperatorView.swift @@ -52,10 +52,16 @@ struct OperatorView: View { Text("Operator") .foregroundColor(theme.colors.secondary) } footer: { - if let errStr = globalServersError(serverErrors) { - ServersErrorView(errStr: errStr) - } else if let warnStr = globalServersWarning(serverWarnings) { - ServersWarningView(warnStr: warnStr) + let errs = globalServersErrors(serverErrors) + let warns = globalServersWarnings(serverWarnings) + if !errs.isEmpty { + ForEach(errs, id: \.self) { err in + ServersErrorView(errStr: err) + } + } else if !warns.isEmpty { + ForEach(warns, id: \.self) { warn in + ServersWarningView(warnStr: warn) + } } else { switch (userServers[operatorIndex].operator_.conditionsAcceptance) { case let .accepted(acceptedAt, _): @@ -105,6 +111,10 @@ struct OperatorView: View { .onChange(of: userServers[operatorIndex].operator_.smpRoles.proxy) { _ in validateServers_($userServers, $serverErrors, $serverWarnings) } + Toggle("To resolve names", isOn: $userServers[operatorIndex].operator_.smpRoles.names) + .onChange(of: userServers[operatorIndex].operator_.smpRoles.names) { _ in + validateServers_($userServers, $serverErrors, $serverWarnings) + } } header: { Text("Use for messages") .foregroundColor(theme.colors.secondary) diff --git a/apps/ios/Shared/Views/UserSettings/NetworkAndServers/ProtocolServersView.swift b/apps/ios/Shared/Views/UserSettings/NetworkAndServers/ProtocolServersView.swift index b059be7cb0..a92491edef 100644 --- a/apps/ios/Shared/Views/UserSettings/NetworkAndServers/ProtocolServersView.swift +++ b/apps/ios/Shared/Views/UserSettings/NetworkAndServers/ProtocolServersView.swift @@ -169,10 +169,16 @@ struct YourServersView: View { .hidden() } } footer: { - if let errStr = globalServersError(serverErrors) { - ServersErrorView(errStr: errStr) - } else if let warnStr = globalServersWarning(serverWarnings) { - ServersWarningView(warnStr: warnStr) + let errs = globalServersErrors(serverErrors) + let warns = globalServersWarnings(serverWarnings) + if !errs.isEmpty { + ForEach(errs, id: \.self) { err in + ServersErrorView(errStr: err) + } + } else if !warns.isEmpty { + ForEach(warns, id: \.self) { warn in + ServersWarningView(warnStr: warn) + } } } diff --git a/apps/ios/Shared/Views/UserSettings/PrivacySettings.swift b/apps/ios/Shared/Views/UserSettings/PrivacySettings.swift index ad6b2d4454..f1bacee425 100644 --- a/apps/ios/Shared/Views/UserSettings/PrivacySettings.swift +++ b/apps/ios/Shared/Views/UserSettings/PrivacySettings.swift @@ -16,6 +16,7 @@ struct PrivacySettings: View { @AppStorage(GROUP_DEFAULT_PRIVACY_LINK_PREVIEWS, store: groupDefaults) private var useLinkPreviews = true @AppStorage(GROUP_DEFAULT_PRIVACY_SANITIZE_LINKS, store: groupDefaults) private var privacySanitizeLinks = false @AppStorage(DEFAULT_PRIVACY_SHOW_CHAT_PREVIEWS) private var showChatPreviews = true + @AppStorage(DEFAULT_PRIVACY_VERIFY_SIMPLEX_NAMES) private var verifySimplexNames = false @AppStorage(DEFAULT_PRIVACY_SAVE_LAST_DRAFT) private var saveLastDraft = true @AppStorage(GROUP_DEFAULT_PRIVACY_ENCRYPT_LOCAL_FILES, store: groupDefaults) private var encryptLocalFiles = true @AppStorage(GROUP_DEFAULT_PRIVACY_ASK_TO_APPROVE_RELAYS, store: groupDefaults) private var askToApproveRelays = true @@ -193,6 +194,9 @@ struct PrivacySettings: View { m.draftChatId = nil } } + settingsRow("number", color: theme.colors.secondary) { + Toggle("Verify SimpleX names", isOn: $verifySimplexNames) + } } header: { Text("Chats") .foregroundColor(theme.colors.secondary) diff --git a/apps/ios/Shared/Views/UserSettings/SettingsView.swift b/apps/ios/Shared/Views/UserSettings/SettingsView.swift index 135a90c65e..057ce5a227 100644 --- a/apps/ios/Shared/Views/UserSettings/SettingsView.swift +++ b/apps/ios/Shared/Views/UserSettings/SettingsView.swift @@ -32,6 +32,7 @@ let DEFAULT_PRIVACY_ACCEPT_IMAGES = "privacyAcceptImages" // unused. Use GROUP_D let DEFAULT_PRIVACY_LINK_PREVIEWS = "privacyLinkPreviews" // deprecated, moved to app group let DEFAULT_PRIVACY_SIMPLEX_LINK_MODE = "privacySimplexLinkMode" let DEFAULT_PRIVACY_SHOW_CHAT_PREVIEWS = "privacyShowChatPreviews" +let DEFAULT_PRIVACY_VERIFY_SIMPLEX_NAMES = "privacyVerifySimplexNames" let DEFAULT_PRIVACY_SAVE_LAST_DRAFT = "privacySaveLastDraft" let DEFAULT_PRIVACY_PROTECT_SCREEN = "privacyProtectScreen" let DEFAULT_PRIVACY_DELIVERY_RECEIPTS_SET = "privacyDeliveryReceiptsSet" @@ -99,6 +100,7 @@ let appDefaults: [String: Any] = [ DEFAULT_PRIVACY_LINK_PREVIEWS: true, DEFAULT_PRIVACY_SIMPLEX_LINK_MODE: SimpleXLinkMode.description.rawValue, DEFAULT_PRIVACY_SHOW_CHAT_PREVIEWS: true, + DEFAULT_PRIVACY_VERIFY_SIMPLEX_NAMES: false, DEFAULT_PRIVACY_SAVE_LAST_DRAFT: true, DEFAULT_PRIVACY_PROTECT_SCREEN: false, DEFAULT_PRIVACY_DELIVERY_RECEIPTS_SET: false, diff --git a/apps/ios/Shared/Views/UserSettings/UserAddressView.swift b/apps/ios/Shared/Views/UserSettings/UserAddressView.swift index e22042fa24..13caf135e9 100644 --- a/apps/ios/Shared/Views/UserSettings/UserAddressView.swift +++ b/apps/ios/Shared/Views/UserSettings/UserAddressView.swift @@ -191,6 +191,29 @@ struct UserAddressView: View { } } + Section { + NavigationLink { + let simplexName = if let d = chatModel.currentUser?.profile.contactDomain?.shortName { "@\(d)" } else { "" } + SetSimplexDomainView( + title: "Your SimpleX name", + footer: "Let people connect to you via name registered with your SimpleX address.", + prompt: "@yourname.testing", + simplexName: simplexName, + save: { simplexDomain in + do { + let u = try await apiSetUserDomain(simplexDomain) + await MainActor.run { chatModel.updateUser(u) } + return true + } catch { + return false + } + } + ) + } label: { + Label("Your SimpleX name", systemImage: "at") + } + } + Section { createOneTimeLinkButton() } header: { @@ -293,9 +316,10 @@ struct UserAddressView: View { } } catch let error { logger.error("UserAddressView apiCreateUserAddress: \(responseError(error))") - let a = getErrorAlert(error, "Error creating address") - alert = .error(title: a.title, error: a.message) - await MainActor.run { progressIndicator = false } + await MainActor.run { + progressIndicator = false + showErrorAlert(error, NSLocalizedString("Error creating address", comment: "")) + } } } } @@ -367,8 +391,7 @@ struct UserAddressView: View { case .success: () case let .failure(error): logger.error("UserAddressView share via email: \(responseError(error))") - let a = getErrorAlert(error, "Error sending email") - alert = .error(title: a.title, error: a.message) + showErrorAlert(error, NSLocalizedString("Error sending email", comment: "")) } mailViewResult = nil } @@ -688,6 +711,59 @@ private func saveAddressSettings(_ settings: AddressSettingsState, _ savedSettin } } +struct SetSimplexDomainView: View { + let title: LocalizedStringKey + let footer: LocalizedStringKey + let prompt: String + @State var simplexName: String + let save: (String?) async -> Bool + @Environment(\.dismiss) var dismiss + @EnvironmentObject var theme: AppTheme + @State private var saving = false + + var body: some View { + List { + Section { + TextField(prompt, text: $simplexName) + .autocorrectionDisabled(true) + .textInputAutocapitalization(.never) + } header: { + Text(verbatim: "") + } footer: { + Text(footer).foregroundColor(theme.colors.secondary) + } + Section { + Button { + saving = true + Task { + let ok = await save(normalized()) + await MainActor.run { + saving = false + if ok { dismiss() } + } + } + } label: { + Text("Save") + } + .disabled(saving) + } + } + .navigationTitle(title) + .navigationBarTitleDisplayMode(.large) + } + + private func normalized() -> String? { + let s = simplexName.trimmingCharacters(in: .whitespacesAndNewlines) + return s.isEmpty + ? nil + : addSimplexTLD(s.hasPrefix("@") || s.hasPrefix("#") ? String(s.dropFirst()) : s) + } + + private func addSimplexTLD(_ d: String) -> String { + if d.contains(".") { d } else { "\(d).simplex" } + } +} + struct UserAddressView_Previews: PreviewProvider { static var previews: some View { let chatModel = ChatModel() diff --git a/apps/ios/Shared/Views/UserSettings/UserProfilesView.swift b/apps/ios/Shared/Views/UserSettings/UserProfilesView.swift index ad3b5cdf95..3f3adbcb2d 100644 --- a/apps/ios/Shared/Views/UserSettings/UserProfilesView.swift +++ b/apps/ios/Shared/Views/UserSettings/UserProfilesView.swift @@ -319,8 +319,9 @@ struct UserProfilesView: View { } } catch let error { logger.error("Error deleting user profile: \(error)") - let a = getErrorAlert(error, "Error deleting user profile") - alert = .error(title: a.title, error: a.message) + await MainActor.run { + showErrorAlert(error, NSLocalizedString("Error deleting user profile", comment: "")) + } } func deleteUser() async throws { @@ -436,8 +437,9 @@ struct UserProfilesView: View { } } } catch let error { - let a = getErrorAlert(error, "Error updating user privacy") - alert = .error(title: a.title, error: a.message) + await MainActor.run { + showErrorAlert(error, NSLocalizedString("Error updating user privacy", comment: "")) + } } } } diff --git a/apps/ios/SimpleX Localizations/bg.xcloc/Localized Contents/bg.xliff b/apps/ios/SimpleX Localizations/bg.xcloc/Localized Contents/bg.xliff index 3c83ee7bf3..cac4ef3d06 100644 --- a/apps/ios/SimpleX Localizations/bg.xcloc/Localized Contents/bg.xliff +++ b/apps/ios/SimpleX Localizations/bg.xcloc/Localized Contents/bg.xliff @@ -197,6 +197,18 @@ %d месеца time interval + + %d owner + channel owners count + + + %d owners + channel owners count + + + %d owners & contributors + channel members count + %d relays failed channel relay bar @@ -1684,11 +1696,6 @@ new chat action Промяна на режима на заключване authentication reason - - Change member role? - Промяна на ролята на члена? - No comment provided by engineer. - Change passcode Промени kодa за достъп @@ -1709,6 +1716,10 @@ new chat action Промени ролята No comment provided by engineer. + + Change role? + No comment provided by engineer. + Change self-destruct mode Промени режима на самоунищожение @@ -2274,14 +2285,6 @@ This is your own one-time link! Свързване с настолно устройство No comment provided by engineer. - - Connecting via channel name requires a newer app version. - alert message - - - Connecting via contact name requires a newer app version. - alert message - Connection Връзка @@ -2297,6 +2300,10 @@ This is your own one-time link! Връзката е блокирана No comment provided by engineer. + + Connection blocked: %@ + conn error description + Connection error Грешка при свързване @@ -3037,7 +3044,7 @@ alert button No comment provided by engineer. - Destination server address of %@ is incompatible with forwarding server %@ settings. + Destination server address of %1$@ is incompatible with forwarding server %2$@ settings. No comment provided by engineer. @@ -3045,7 +3052,7 @@ alert button snd error text - Destination server version of %@ is incompatible with forwarding server %@. + Destination server version of %1$@ is incompatible with forwarding server %2$@. No comment provided by engineer. @@ -3567,7 +3574,7 @@ chat item action Error Грешка при свързване със сървъра - conn error description + No comment provided by engineer. Error aborting address change @@ -3841,6 +3848,10 @@ chat item action Грешка при запазване на профила на групата No comment provided by engineer. + + Error saving name + alert title + Error saving passcode Грешка при запазване на кода за достъп @@ -3969,6 +3980,7 @@ chat item action Error: %@ Грешка: %@ alert message +conn error description file error text snd error text @@ -5110,6 +5122,14 @@ This is your link for group %@! Less traffic on mobile networks. No comment provided by engineer. + + Let people connect to you via name registered with your SimpleX address. + No comment provided by engineer. + + + Let people join via name registered with this channel link. + No comment provided by engineer. + Let someone connect to you No comment provided by engineer. @@ -5275,20 +5295,6 @@ This is your link for group %@! Member reports chat feature - - Member role will be changed to "%@". All chat members will be notified. - No comment provided by engineer. - - - Member role will be changed to "%@". All group members will be notified. - Ролята на члена ще бъде променена на "%@". Всички членове на групата ще бъдат уведомени. - No comment provided by engineer. - - - Member role will be changed to "%@". The member will receive a new invitation. - Ролята на члена ще бъде променена на "%@". Членът ще получи нова покана. - No comment provided by engineer. - Member will be removed from chat - this cannot be undone! alert message @@ -5620,6 +5626,10 @@ This is your link for group %@! Име swipe action + + Name not found + No comment provided by engineer. + Network & servers Мрежа и сървъри @@ -5914,6 +5924,10 @@ The most secure encryption. No servers to receive messages. servers error + + No servers to resolve names. + servers warning + No servers to send files. servers error @@ -5926,6 +5940,10 @@ The most secure encryption. No unread chats No comment provided by engineer. + + No valid link + No comment provided by engineer. + Nobody tracked your conversations. No one drew a map of where you'd been. Privacy was never a feature - it was the way of life. No comment provided by engineer. @@ -5934,6 +5952,10 @@ The most secure encryption. Non-profit governance No comment provided by engineer. + + None of your servers are set to resolve SimpleX names. Configure servers, or use a connection link. + No comment provided by engineer. + Not a better lock on someone else's door. Not a nicer landlord that respects your privacy, but still keeps the record of all visitors. You are not a guest. You are home. No king can enter it - you are sovereign. No comment provided by engineer. @@ -6307,8 +6329,8 @@ alert button Owner No comment provided by engineer. - - Owners + + Owners & contributors No comment provided by engineer. @@ -6491,10 +6513,6 @@ Error: %@ Please try to disable and re-enable notfications. token info - - Please upgrade the app. - alert message - Please wait for group moderators to review your request to join the group. snd group event chat item @@ -7141,6 +7159,10 @@ swipe action Reset to user theme No comment provided by engineer. + + Resolver error: %@ + No comment provided by engineer. + Restart the app to create a new chat profile Рестартирайте приложението, за да създадете нов чат профил @@ -7217,6 +7239,22 @@ swipe action Роля No comment provided by engineer. + + Role will be changed to "%@". All chat members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All group members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All subscribers will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". The member will receive a new invitation. + No comment provided by engineer. + Run chat Стартиране на чат @@ -7715,6 +7753,10 @@ chat item action Server No comment provided by engineer. + + Server %@ does not support name resolution. Configure servers, or use a connection link. + No comment provided by engineer. + Server added to operator %@. alert message @@ -8105,6 +8147,18 @@ chat item action SimpleX линковете не са разрешени No comment provided by engineer. + + SimpleX name + No comment provided by engineer. + + + SimpleX name error + No comment provided by engineer. + + + SimpleX name not verified + alert title + SimpleX one-time invitation Еднократна покана за SimpleX @@ -8533,6 +8587,22 @@ It can happen because of some bug or when the connection is compromised. No comment provided by engineer. + + The SimpleX name #%@ is registered without channel link. Add channel link to the name via the registration page. + alert message + + + The SimpleX name %@ is registered, but it has no valid link. + No comment provided by engineer. + + + The SimpleX name %@ is registered, but not added to profile. Please add it to your address or channel profile, if you are the owner. + No comment provided by engineer. + + + The SimpleX name @%@ is registered without SimpleX address. Add your SimpleX address to the name via the registration page. + alert message + The address will be short, and your profile will be shared via the address. alert message @@ -8699,6 +8769,10 @@ your contacts and groups. Те могат да бъдат променени в настройките за всеки контакт и група. No comment provided by engineer. + + This SimpleX name is not registered. Please check the name. + No comment provided by engineer. + This action cannot be undone - all received and sent files and media will be deleted. Low resolution pictures will remain. Това действие не може да бъде отменено - всички получени и изпратени файлове и медия ще бъдат изтрити. Снимките с ниска разделителна способност ще бъдат запазени. @@ -8864,6 +8938,10 @@ You will be prompted to complete authentication before this feature is enabled.< За да запишете гласово съобщение, моля, дайте разрешение за използване на микрофон. No comment provided by engineer. + + To resolve names + No comment provided by engineer. + To reveal your hidden profile, enter a full password into a search field in **Your chat profiles** page. За да разкриете своя скрит профил, въведете пълна парола в полето за търсене на страницата **Вашите чат профили**. @@ -8978,6 +9056,10 @@ You will be prompted to complete authentication before this feature is enabled.< Unblock subscriber for all? No comment provided by engineer. + + Unconfirmed name + No comment provided by engineer. + Undelivered messages No comment provided by engineer. @@ -9073,18 +9155,10 @@ To connect, please ask your contact to create another connection link and check Непрочетено swipe action - - Unsupported channel name - alert title - Unsupported connection link conn error description - - Unsupported contact name - alert title - Unverified badge badge alert title @@ -9313,6 +9387,10 @@ To connect, please ask your contact to create another connection link and check Verify relay test step + + Verify SimpleX names + No comment provided by engineer. + Verify code with desktop Потвърди кода с настолното устройство @@ -9338,6 +9416,10 @@ To connect, please ask your contact to create another connection link and check Проверете паролата на базата данни No comment provided by engineer. + + Verify name + No comment provided by engineer. + Verify passphrase Провери паролата @@ -9947,6 +10029,10 @@ Repeat connection request? Вашият адрес в SimpleX No comment provided by engineer. + + Your SimpleX name + No comment provided by engineer. + Your business contact No comment provided by engineer. @@ -10400,6 +10486,10 @@ marked deleted chat item preview text contact should accept… No comment provided by engineer. + + contributor + member role + creator създател @@ -11014,6 +11104,10 @@ last received msg: %2$@ зачеркнат No comment provided by engineer. + + subscriber + member role + this contact този контакт diff --git a/apps/ios/SimpleX Localizations/cs.xcloc/Localized Contents/cs.xliff b/apps/ios/SimpleX Localizations/cs.xcloc/Localized Contents/cs.xliff index 46a4171039..0eb4b0640c 100644 --- a/apps/ios/SimpleX Localizations/cs.xcloc/Localized Contents/cs.xliff +++ b/apps/ios/SimpleX Localizations/cs.xcloc/Localized Contents/cs.xliff @@ -197,6 +197,18 @@ %d měsíce time interval + + %d owner + channel owners count + + + %d owners + channel owners count + + + %d owners & contributors + channel members count + %d relays failed channel relay bar @@ -1648,11 +1660,6 @@ new chat action Změnit zamykání authentication reason - - Change member role? - Změnit roli člena? - No comment provided by engineer. - Change passcode Změnit heslo @@ -1673,6 +1680,10 @@ new chat action Změnit roli No comment provided by engineer. + + Change role? + No comment provided by engineer. + Change self-destruct mode Změnit režim sebedestrukce @@ -2186,14 +2197,6 @@ Toto je váš vlastní jednorázový odkaz! Connecting to desktop No comment provided by engineer. - - Connecting via channel name requires a newer app version. - alert message - - - Connecting via contact name requires a newer app version. - alert message - Connection Připojení @@ -2207,6 +2210,10 @@ Toto je váš vlastní jednorázový odkaz! Connection blocked No comment provided by engineer. + + Connection blocked: %@ + conn error description + Connection error Chyba připojení @@ -2927,7 +2934,7 @@ alert button No comment provided by engineer. - Destination server address of %@ is incompatible with forwarding server %@ settings. + Destination server address of %1$@ is incompatible with forwarding server %2$@ settings. No comment provided by engineer. @@ -2935,7 +2942,7 @@ alert button snd error text - Destination server version of %@ is incompatible with forwarding server %@. + Destination server version of %1$@ is incompatible with forwarding server %2$@. No comment provided by engineer. @@ -3440,7 +3447,7 @@ chat item action Error Chyba - conn error description + No comment provided by engineer. Error aborting address change @@ -3711,6 +3718,10 @@ chat item action Chyba při ukládání profilu skupiny No comment provided by engineer. + + Error saving name + alert title + Error saving passcode Chyba uložení hesla @@ -3835,6 +3846,7 @@ chat item action Error: %@ Chyba: %@ alert message +conn error description file error text snd error text @@ -4941,6 +4953,14 @@ This is your link for group %@! Less traffic on mobile networks. No comment provided by engineer. + + Let people connect to you via name registered with your SimpleX address. + No comment provided by engineer. + + + Let people join via name registered with this channel link. + No comment provided by engineer. + Let someone connect to you No comment provided by engineer. @@ -5103,20 +5123,6 @@ This is your link for group %@! Member reports chat feature - - Member role will be changed to "%@". All chat members will be notified. - No comment provided by engineer. - - - Member role will be changed to "%@". All group members will be notified. - Role člena se změní na "%@". Všichni členové skupiny budou upozorněni. - No comment provided by engineer. - - - Member role will be changed to "%@". The member will receive a new invitation. - Role člena se změní na "%@". Člen obdrží novou pozvánku. - No comment provided by engineer. - Member will be removed from chat - this cannot be undone! alert message @@ -5435,6 +5441,10 @@ This is your link for group %@! Jméno swipe action + + Name not found + No comment provided by engineer. + Network & servers Síť a servery @@ -5725,6 +5735,10 @@ The most secure encryption. No servers to receive messages. servers error + + No servers to resolve names. + servers warning + No servers to send files. servers error @@ -5737,6 +5751,10 @@ The most secure encryption. No unread chats No comment provided by engineer. + + No valid link + No comment provided by engineer. + Nobody tracked your conversations. No one drew a map of where you'd been. Privacy was never a feature - it was the way of life. Nikdo nesledoval vaše konverzace. Nikdo nevytvořil mapu, kde jste byli. Soukromí nikdy nebylo funkcí - byl to způsob života. @@ -5746,6 +5764,10 @@ The most secure encryption. Non-profit governance No comment provided by engineer. + + None of your servers are set to resolve SimpleX names. Configure servers, or use a connection link. + No comment provided by engineer. + Not a better lock on someone else's door. Not a nicer landlord that respects your privacy, but still keeps the record of all visitors. You are not a guest. You are home. No king can enter it - you are sovereign. Nejde o to mít lepší zámek na dveřích někoho jiného. Ani o to mít nájemce, který respektuje vaše soukromí, ale vede evidenci všech vašich návštěvníků. Nejste host. Jste doma. Ani král k vám nemůže vstoupit - jste suverén. @@ -6110,8 +6132,8 @@ alert button Owner No comment provided by engineer. - - Owners + + Owners & contributors No comment provided by engineer. @@ -6287,10 +6309,6 @@ Error: %@ Please try to disable and re-enable notfications. token info - - Please upgrade the app. - alert message - Please wait for group moderators to review your request to join the group. snd group event chat item @@ -6927,6 +6945,10 @@ swipe action Reset to user theme No comment provided by engineer. + + Resolver error: %@ + No comment provided by engineer. + Restart the app to create a new chat profile Restartujte aplikaci pro vytvoření nového profilu chatu @@ -7002,6 +7024,22 @@ swipe action Role No comment provided by engineer. + + Role will be changed to "%@". All chat members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All group members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All subscribers will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". The member will receive a new invitation. + No comment provided by engineer. + Run chat Spustit chat @@ -7492,6 +7530,10 @@ chat item action Server No comment provided by engineer. + + Server %@ does not support name resolution. Configure servers, or use a connection link. + No comment provided by engineer. + Server added to operator %@. alert message @@ -7874,6 +7916,18 @@ chat item action SimpleX links not allowed No comment provided by engineer. + + SimpleX name + No comment provided by engineer. + + + SimpleX name error + No comment provided by engineer. + + + SimpleX name not verified + alert title + SimpleX one-time invitation Jednorázová pozvánka SimpleX @@ -8295,6 +8349,22 @@ It can happen because of some bug or when the connection is compromised. No comment provided by engineer. + + The SimpleX name #%@ is registered without channel link. Add channel link to the name via the registration page. + alert message + + + The SimpleX name %@ is registered, but it has no valid link. + No comment provided by engineer. + + + The SimpleX name %@ is registered, but not added to profile. Please add it to your address or channel profile, if you are the owner. + No comment provided by engineer. + + + The SimpleX name @%@ is registered without SimpleX address. Add your SimpleX address to the name via the registration page. + alert message + The address will be short, and your profile will be shared via the address. alert message @@ -8462,6 +8532,10 @@ your contacts and groups. Mohou být přepsány v nastavení kontaktů. No comment provided by engineer. + + This SimpleX name is not registered. Please check the name. + No comment provided by engineer. + This action cannot be undone - all received and sent files and media will be deleted. Low resolution pictures will remain. Tuto akci nelze vrátit zpět - všechny přijaté a odeslané soubory a média budou smazány. Obrázky s nízkým rozlišením zůstanou zachovány. @@ -8622,6 +8696,10 @@ Před zapnutím této funkce budete vyzváni k dokončení ověření. Chcete-li nahrávat hlasové zprávy, udělte povolení k použití mikrofonu. No comment provided by engineer. + + To resolve names + No comment provided by engineer. + To reveal your hidden profile, enter a full password into a search field in **Your chat profiles** page. Chcete-li odhalit svůj skrytý profil, zadejte celé heslo do vyhledávacího pole na stránce **Profily chatu**. @@ -8730,6 +8808,10 @@ Před zapnutím této funkce budete vyzváni k dokončení ověření. Unblock subscriber for all? No comment provided by engineer. + + Unconfirmed name + No comment provided by engineer. + Undelivered messages No comment provided by engineer. @@ -8823,18 +8905,10 @@ Chcete-li se připojit, požádejte svůj kontakt o vytvoření dalšího odkazu Nepřečtený swipe action - - Unsupported channel name - alert title - Unsupported connection link conn error description - - Unsupported contact name - alert title - Unverified badge badge alert title @@ -9057,6 +9131,10 @@ Chcete-li se připojit, požádejte svůj kontakt o vytvoření dalšího odkazu Verify relay test step + + Verify SimpleX names + No comment provided by engineer. + Verify code with desktop No comment provided by engineer. @@ -9078,6 +9156,10 @@ Chcete-li se připojit, požádejte svůj kontakt o vytvoření dalšího odkazu Verify database passphrase No comment provided by engineer. + + Verify name + No comment provided by engineer. + Verify passphrase No comment provided by engineer. @@ -9661,6 +9743,10 @@ Repeat connection request? Vaše SimpleX adresa No comment provided by engineer. + + Your SimpleX name + No comment provided by engineer. + Your business contact No comment provided by engineer. @@ -10106,6 +10192,10 @@ marked deleted chat item preview text contact should accept… No comment provided by engineer. + + contributor + member role + creator tvůrce @@ -10708,6 +10798,10 @@ last received msg: %2$@ stávka No comment provided by engineer. + + subscriber + member role + this contact tento kontakt diff --git a/apps/ios/SimpleX Localizations/de.xcloc/Localized Contents/de.xliff b/apps/ios/SimpleX Localizations/de.xcloc/Localized Contents/de.xliff index be4a0ce46f..3674a5bb94 100644 --- a/apps/ios/SimpleX Localizations/de.xcloc/Localized Contents/de.xliff +++ b/apps/ios/SimpleX Localizations/de.xcloc/Localized Contents/de.xliff @@ -197,6 +197,18 @@ %d Monate time interval + + %d owner + channel owners count + + + %d owners + channel owners count + + + %d owners & contributors + channel members count + %d relays failed %d Relais fehlgeschlagen @@ -1720,11 +1732,6 @@ new chat action Sperr-Modus ändern authentication reason - - Change member role? - Die Mitgliederrolle ändern? - No comment provided by engineer. - Change passcode Zugangscode ändern @@ -1745,6 +1752,10 @@ new chat action Rolle ändern No comment provided by engineer. + + Change role? + No comment provided by engineer. + Change self-destruct mode Selbstzerstörungs-Modus ändern @@ -2335,14 +2346,6 @@ Das ist Ihr eigener Einmal-Link! Mit dem Desktop verbinden No comment provided by engineer. - - Connecting via channel name requires a newer app version. - alert message - - - Connecting via contact name requires a newer app version. - alert message - Connection Verbindung @@ -2358,6 +2361,10 @@ Das ist Ihr eigener Einmal-Link! Verbindung blockiert No comment provided by engineer. + + Connection blocked: %@ + conn error description + Connection error Verbindungsfehler @@ -3147,7 +3154,7 @@ alert button No comment provided by engineer. - Destination server address of %@ is incompatible with forwarding server %@ settings. + Destination server address of %1$@ is incompatible with forwarding server %2$@ settings. Adresse des Zielservers von %@ ist nicht kompatibel mit den Einstellungen des Weiterleitungsservers %@. No comment provided by engineer. @@ -3157,7 +3164,7 @@ alert button snd error text - Destination server version of %@ is incompatible with forwarding server %@. + Destination server version of %1$@ is incompatible with forwarding server %2$@. Die Version des Zielservers %@ ist nicht kompatibel mit dem Weiterleitungsserver %@. No comment provided by engineer. @@ -3714,7 +3721,7 @@ chat item action Error Fehler - conn error description + No comment provided by engineer. Error aborting address change @@ -4014,6 +4021,10 @@ chat item action Fehler beim Speichern des Gruppenprofils No comment provided by engineer. + + Error saving name + alert title + Error saving passcode Fehler beim Speichern des Zugangscodes @@ -4148,6 +4159,7 @@ chat item action Error: %@ Fehler: %@ alert message +conn error description file error text snd error text @@ -5371,6 +5383,14 @@ Das ist Ihr Link für die Gruppe %@! Weniger Datenverkehr in mobilen Netzen. No comment provided by engineer. + + Let people connect to you via name registered with your SimpleX address. + No comment provided by engineer. + + + Let people join via name registered with this channel link. + No comment provided by engineer. + Let someone connect to you Jemand mit Ihnen verbinden lassen @@ -5551,21 +5571,6 @@ Das ist Ihr Link für die Gruppe %@! Mitglieder-Meldungen chat feature - - Member role will be changed to "%@". All chat members will be notified. - Die Rolle des Mitglieds wird auf "%@" geändert. Alle Chat-Mitglieder werden darüber informiert. - No comment provided by engineer. - - - Member role will be changed to "%@". All group members will be notified. - Die Mitgliederrolle wird auf "%@" geändert. Alle Mitglieder der Gruppe werden benachrichtigt. - No comment provided by engineer. - - - Member role will be changed to "%@". The member will receive a new invitation. - Die Mitgliederrolle wird auf "%@" geändert. Das Mitglied wird eine neue Einladung erhalten. - No comment provided by engineer. - Member will be removed from chat - this cannot be undone! Das Mitglied wird aus dem Chat entfernt. Dies kann nicht rückgängig gemacht werden! @@ -5925,6 +5930,10 @@ Das ist Ihr Link für die Gruppe %@! Name swipe action + + Name not found + No comment provided by engineer. + Network & servers Netzwerk & Server @@ -6257,6 +6266,10 @@ Die sicherste Verschlüsselung. Keine Server für den Empfang von Nachrichten. servers error + + No servers to resolve names. + servers warning + No servers to send files. Keine Server für das Versenden von Dateien. @@ -6272,6 +6285,10 @@ Die sicherste Verschlüsselung. Keine ungelesenen Chats No comment provided by engineer. + + No valid link + No comment provided by engineer. + Nobody tracked your conversations. No one drew a map of where you'd been. Privacy was never a feature - it was the way of life. Niemand verfolgte Ihre Gespräche. Niemand erstellte eine Karte, wo Sie sich aufgehalten haben. Privatsphäre war nie ein Feature - sie war selbstverständlich. @@ -6282,6 +6299,10 @@ Die sicherste Verschlüsselung. Non‑Profit‑Governance No comment provided by engineer. + + None of your servers are set to resolve SimpleX names. Configure servers, or use a connection link. + No comment provided by engineer. + Not a better lock on someone else's door. Not a nicer landlord that respects your privacy, but still keeps the record of all visitors. You are not a guest. You are home. No king can enter it - you are sovereign. Nicht ein besseres Schloss an der Tür eines Anderen. Kein freundlicher Vermieter, der Ihre Privatsphäre respektiert, aber dennoch jeden Besucher registriert. Sie sind kein Gast. Sie sind zu Hause. Kein Vermieter, kein Fremder kann es betreten - Sie sind souverän. @@ -6700,9 +6721,8 @@ alert button Eigentümer No comment provided by engineer. - - Owners - Eigentümer + + Owners & contributors No comment provided by engineer. @@ -6894,10 +6914,6 @@ Fehler: %@ Bitte versuchen Sie, die Benachrichtigungen zu deaktivieren und wieder zu aktivieren. token info - - Please upgrade the app. - alert message - Please wait for group moderators to review your request to join the group. Bitte warten Sie auf die Überprüfung Ihrer Anfrage durch die Gruppen-Moderatoren, um der Gruppe beitreten zu können. @@ -7618,6 +7634,10 @@ swipe action Auf das Benutzer-spezifische Design zurücksetzen No comment provided by engineer. + + Resolver error: %@ + No comment provided by engineer. + Restart the app to create a new chat profile Um ein neues Chat-Profil zu erstellen, starten Sie die App neu @@ -7698,6 +7718,22 @@ swipe action Rolle No comment provided by engineer. + + Role will be changed to "%@". All chat members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All group members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All subscribers will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". The member will receive a new invitation. + No comment provided by engineer. + Run chat Chat starten @@ -8242,6 +8278,10 @@ chat item action Server No comment provided by engineer. + + Server %@ does not support name resolution. Configure servers, or use a connection link. + No comment provided by engineer. + Server added to operator %@. Der Server wurde dem Betreiber %@ hinzugefügt. @@ -8678,6 +8718,18 @@ chat item action SimpleX-Links sind nicht erlaubt No comment provided by engineer. + + SimpleX name + No comment provided by engineer. + + + SimpleX name error + No comment provided by engineer. + + + SimpleX name not verified + alert title + SimpleX one-time invitation SimpleX-Einmal-Einladung @@ -9154,6 +9206,22 @@ It can happen because of some bug or when the connection is compromised. No comment provided by engineer. + + The SimpleX name #%@ is registered without channel link. Add channel link to the name via the registration page. + alert message + + + The SimpleX name %@ is registered, but it has no valid link. + No comment provided by engineer. + + + The SimpleX name %@ is registered, but not added to profile. Please add it to your address or channel profile, if you are the owner. + No comment provided by engineer. + + + The SimpleX name @%@ is registered without SimpleX address. Add your SimpleX address to the name via the registration page. + alert message + The address will be short, and your profile will be shared via the address. Die Adresse wird gekürzt sein, und Ihr Profil wird über die Adresse geteilt. @@ -9340,6 +9408,10 @@ in dem Sie Ihre Kontakte und Gruppen besitzen. Sie können in den Kontakteinstellungen überschrieben werden. No comment provided by engineer. + + This SimpleX name is not registered. Please check the name. + No comment provided by engineer. + This action cannot be undone - all received and sent files and media will be deleted. Low resolution pictures will remain. Dieser Vorgang kann nicht rückgängig gemacht werden - alle empfangenen und gesendeten Dateien sowie Medien werden gelöscht. Bilder mit niedriger Auflösung bleiben erhalten. @@ -9520,6 +9592,10 @@ Sie werden aufgefordert, die Authentifizierung abzuschließen, bevor diese Funkt Bitte erlauben Sie die Nutzung des Mikrofons, um Sprachnachrichten aufnehmen zu können. No comment provided by engineer. + + To resolve names + No comment provided by engineer. + To reveal your hidden profile, enter a full password into a search field in **Your chat profiles** page. Geben Sie ein vollständiges Passwort in das Suchfeld auf der Seite **Ihre Chat-Profile** ein, um Ihr verborgenes Profil zu sehen. @@ -9645,6 +9721,10 @@ Sie werden aufgefordert, die Authentifizierung abzuschließen, bevor diese Funkt Abonnent für alle freigeben? No comment provided by engineer. + + Unconfirmed name + No comment provided by engineer. + Undelivered messages Nicht ausgelieferte Nachrichten @@ -9742,19 +9822,11 @@ Bitten Sie Ihren Kontakt darum einen weiteren Verbindungs-Link zu erzeugen, um s Ungelesen swipe action - - Unsupported channel name - alert title - Unsupported connection link Verbindungs-Link wird nicht unterstützt conn error description - - Unsupported contact name - alert title - Unverified badge badge alert title @@ -10013,6 +10085,10 @@ Bitten Sie Ihren Kontakt darum einen weiteren Verbindungs-Link zu erzeugen, um s Überprüfen relay test step + + Verify SimpleX names + No comment provided by engineer. + Verify code with desktop Code mit dem Desktop überprüfen @@ -10038,6 +10114,10 @@ Bitten Sie Ihren Kontakt darum einen weiteren Verbindungs-Link zu erzeugen, um s Überprüfen Sie das Datenbank-Passwort No comment provided by engineer. + + Verify name + No comment provided by engineer. + Verify passphrase Überprüfen Sie das Passwort @@ -10687,6 +10767,10 @@ Verbindungsanfrage wiederholen? Ihre SimpleX-Adresse No comment provided by engineer. + + Your SimpleX name + No comment provided by engineer. + Your business contact Ihr geschäftlicher Kontakt @@ -11174,6 +11258,10 @@ marked deleted chat item preview text Kontakt sollte annehmen… No comment provided by engineer. + + contributor + member role + creator Ersteller @@ -11826,6 +11914,10 @@ Zuletzt empfangene Nachricht: %2$@ durchstreichen No comment provided by engineer. + + subscriber + member role + this contact Dieser Kontakt diff --git a/apps/ios/SimpleX Localizations/en.xcloc/Localized Contents/en.xliff b/apps/ios/SimpleX Localizations/en.xcloc/Localized Contents/en.xliff index d375d20396..fe8baaaa41 100644 --- a/apps/ios/SimpleX Localizations/en.xcloc/Localized Contents/en.xliff +++ b/apps/ios/SimpleX Localizations/en.xcloc/Localized Contents/en.xliff @@ -200,6 +200,21 @@ %d months time interval + + %d owner + %d owner + channel owners count + + + %d owners + %d owners + channel owners count + + + %d owners & contributors + %d owners & contributors + channel members count + %d relays failed %d relays failed @@ -1735,11 +1750,6 @@ new chat action Change lock mode authentication reason - - Change member role? - Change member role? - No comment provided by engineer. - Change passcode Change passcode @@ -1760,6 +1770,11 @@ new chat action Change role No comment provided by engineer. + + Change role? + Change role? + No comment provided by engineer. + Change self-destruct mode Change self-destruct mode @@ -2353,16 +2368,6 @@ This is your own one-time link! Connecting to desktop No comment provided by engineer. - - Connecting via channel name requires a newer app version. - Connecting via channel name requires a newer app version. - alert message - - - Connecting via contact name requires a newer app version. - Connecting via contact name requires a newer app version. - alert message - Connection Connection @@ -2378,6 +2383,11 @@ This is your own one-time link! Connection blocked No comment provided by engineer. + + Connection blocked: %@ + Connection blocked: %@ + conn error description + Connection error Connection error @@ -3171,8 +3181,8 @@ alert button No comment provided by engineer. - Destination server address of %@ is incompatible with forwarding server %@ settings. - Destination server address of %@ is incompatible with forwarding server %@ settings. + Destination server address of %1$@ is incompatible with forwarding server %2$@ settings. + Destination server address of %1$@ is incompatible with forwarding server %2$@ settings. No comment provided by engineer. @@ -3181,8 +3191,8 @@ alert button snd error text - Destination server version of %@ is incompatible with forwarding server %@. - Destination server version of %@ is incompatible with forwarding server %@. + Destination server version of %1$@ is incompatible with forwarding server %2$@. + Destination server version of %1$@ is incompatible with forwarding server %2$@. No comment provided by engineer. @@ -3739,7 +3749,7 @@ chat item action Error Error - conn error description + No comment provided by engineer. Error aborting address change @@ -4041,6 +4051,11 @@ chat item action Error saving group profile No comment provided by engineer. + + Error saving name + Error saving name + alert title + Error saving passcode Error saving passcode @@ -4175,6 +4190,7 @@ chat item action Error: %@ Error: %@ alert message +conn error description file error text snd error text @@ -5401,6 +5417,16 @@ This is your link for group %@! Less traffic on mobile networks. No comment provided by engineer. + + Let people connect to you via name registered with your SimpleX address. + Let people connect to you via name registered with your SimpleX address. + No comment provided by engineer. + + + Let people join via name registered with this channel link. + Let people join via name registered with this channel link. + No comment provided by engineer. + Let someone connect to you Let someone connect to you @@ -5581,21 +5607,6 @@ This is your link for group %@! Member reports chat feature - - Member role will be changed to "%@". All chat members will be notified. - Member role will be changed to "%@". All chat members will be notified. - No comment provided by engineer. - - - Member role will be changed to "%@". All group members will be notified. - Member role will be changed to "%@". All group members will be notified. - No comment provided by engineer. - - - Member role will be changed to "%@". The member will receive a new invitation. - Member role will be changed to "%@". The member will receive a new invitation. - No comment provided by engineer. - Member will be removed from chat - this cannot be undone! Member will be removed from chat - this cannot be undone! @@ -5956,6 +5967,11 @@ This is your link for group %@! Name swipe action + + Name not found + Name not found + No comment provided by engineer. + Network & servers Network & servers @@ -6290,6 +6306,11 @@ The most secure encryption. No servers to receive messages. servers error + + No servers to resolve names. + No servers to resolve names. + servers warning + No servers to send files. No servers to send files. @@ -6305,6 +6326,11 @@ The most secure encryption. No unread chats No comment provided by engineer. + + No valid link + No valid link + No comment provided by engineer. + Nobody tracked your conversations. No one drew a map of where you'd been. Privacy was never a feature - it was the way of life. Nobody tracked your conversations. No one drew a map of where you'd been. Privacy was never a feature - it was the way of life. @@ -6315,6 +6341,11 @@ The most secure encryption. Non-profit governance No comment provided by engineer. + + None of your servers are set to resolve SimpleX names. Configure servers, or use a connection link. + None of your servers are set to resolve SimpleX names. Configure servers, or use a connection link. + No comment provided by engineer. + Not a better lock on someone else's door. Not a nicer landlord that respects your privacy, but still keeps the record of all visitors. You are not a guest. You are home. No king can enter it - you are sovereign. Not a better lock on someone else's door. Not a nicer landlord that respects your privacy, but still keeps the record of all visitors. You are not a guest. You are home. No king can enter it - you are sovereign. @@ -6734,9 +6765,9 @@ alert button Owner No comment provided by engineer. - - Owners - Owners + + Owners & contributors + Owners & contributors No comment provided by engineer. @@ -6928,11 +6959,6 @@ Error: %@ Please try to disable and re-enable notfications. token info - - Please upgrade the app. - Please upgrade the app. - alert message - Please wait for group moderators to review your request to join the group. Please wait for group moderators to review your request to join the group. @@ -7657,6 +7683,11 @@ swipe action Reset to user theme No comment provided by engineer. + + Resolver error: %@ + Resolver error: %@ + No comment provided by engineer. + Restart the app to create a new chat profile Restart the app to create a new chat profile @@ -7737,6 +7768,26 @@ swipe action Role No comment provided by engineer. + + Role will be changed to "%@". All chat members will be notified. + Role will be changed to "%@". All chat members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All group members will be notified. + Role will be changed to "%@". All group members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All subscribers will be notified. + Role will be changed to "%@". All subscribers will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". The member will receive a new invitation. + Role will be changed to "%@". The member will receive a new invitation. + No comment provided by engineer. + Run chat Run chat @@ -8283,6 +8334,11 @@ chat item action Server No comment provided by engineer. + + Server %@ does not support name resolution. Configure servers, or use a connection link. + Server %@ does not support name resolution. Configure servers, or use a connection link. + No comment provided by engineer. + Server added to operator %@. Server added to operator %@. @@ -8719,6 +8775,21 @@ chat item action SimpleX links not allowed No comment provided by engineer. + + SimpleX name + SimpleX name + No comment provided by engineer. + + + SimpleX name error + SimpleX name error + No comment provided by engineer. + + + SimpleX name not verified + SimpleX name not verified + alert title + SimpleX one-time invitation SimpleX one-time invitation @@ -9197,6 +9268,26 @@ It can happen because of some bug or when the connection is compromised. No comment provided by engineer. + + The SimpleX name #%@ is registered without channel link. Add channel link to the name via the registration page. + The SimpleX name #%@ is registered without channel link. Add channel link to the name via the registration page. + alert message + + + The SimpleX name %@ is registered, but it has no valid link. + The SimpleX name %@ is registered, but it has no valid link. + No comment provided by engineer. + + + The SimpleX name %@ is registered, but not added to profile. Please add it to your address or channel profile, if you are the owner. + The SimpleX name %@ is registered, but not added to profile. Please add it to your address or channel profile, if you are the owner. + No comment provided by engineer. + + + The SimpleX name @%@ is registered without SimpleX address. Add your SimpleX address to the name via the registration page. + The SimpleX name @%@ is registered without SimpleX address. Add your SimpleX address to the name via the registration page. + alert message + The address will be short, and your profile will be shared via the address. The address will be short, and your profile will be shared via the address. @@ -9384,6 +9475,11 @@ your contacts and groups. They can be overridden in contact and group settings. No comment provided by engineer. + + This SimpleX name is not registered. Please check the name. + This SimpleX name is not registered. Please check the name. + No comment provided by engineer. + This action cannot be undone - all received and sent files and media will be deleted. Low resolution pictures will remain. This action cannot be undone - all received and sent files and media will be deleted. Low resolution pictures will remain. @@ -9567,6 +9663,11 @@ You will be prompted to complete authentication before this feature is enabled.< To record voice message please grant permission to use Microphone. No comment provided by engineer. + + To resolve names + To resolve names + No comment provided by engineer. + To reveal your hidden profile, enter a full password into a search field in **Your chat profiles** page. To reveal your hidden profile, enter a full password into a search field in **Your chat profiles** page. @@ -9692,6 +9793,11 @@ You will be prompted to complete authentication before this feature is enabled.< Unblock subscriber for all? No comment provided by engineer. + + Unconfirmed name + Unconfirmed name + No comment provided by engineer. + Undelivered messages Undelivered messages @@ -9789,21 +9895,11 @@ To connect, please ask your contact to create another connection link and check Unread swipe action - - Unsupported channel name - Unsupported channel name - alert title - Unsupported connection link Unsupported connection link conn error description - - Unsupported contact name - Unsupported contact name - alert title - Unverified badge Unverified badge @@ -10064,6 +10160,11 @@ To connect, please ask your contact to create another connection link and check Verify relay test step + + Verify SimpleX names + Verify SimpleX names + No comment provided by engineer. + Verify code with desktop Verify code with desktop @@ -10089,6 +10190,11 @@ To connect, please ask your contact to create another connection link and check Verify database passphrase No comment provided by engineer. + + Verify name + Verify name + No comment provided by engineer. + Verify passphrase Verify passphrase @@ -10742,6 +10848,11 @@ Repeat connection request? Your SimpleX address No comment provided by engineer. + + Your SimpleX name + Your SimpleX name + No comment provided by engineer. + Your business contact Your business contact @@ -11232,6 +11343,11 @@ marked deleted chat item preview text contact should accept… No comment provided by engineer. + + contributor + contributor + member role + creator creator @@ -11885,6 +12001,11 @@ last received msg: %2$@ strike No comment provided by engineer. + + subscriber + subscriber + member role + this contact this contact diff --git a/apps/ios/SimpleX Localizations/es.xcloc/Localized Contents/es.xliff b/apps/ios/SimpleX Localizations/es.xcloc/Localized Contents/es.xliff index 8ed8087d1b..88294ced4e 100644 --- a/apps/ios/SimpleX Localizations/es.xcloc/Localized Contents/es.xliff +++ b/apps/ios/SimpleX Localizations/es.xcloc/Localized Contents/es.xliff @@ -197,6 +197,18 @@ %d mes(es) time interval + + %d owner + channel owners count + + + %d owners + channel owners count + + + %d owners & contributors + channel members count + %d relays failed %d servidores han fallado @@ -1720,11 +1732,6 @@ new chat action Cambiar el modo de bloqueo authentication reason - - Change member role? - ¿Cambiar rol? - No comment provided by engineer. - Change passcode Cambiar código de acceso @@ -1745,6 +1752,10 @@ new chat action Cambiar rol No comment provided by engineer. + + Change role? + No comment provided by engineer. + Change self-destruct mode Cambiar el modo de autodestrucción @@ -2335,14 +2346,6 @@ This is your own one-time link! Conectando con ordenador No comment provided by engineer. - - Connecting via channel name requires a newer app version. - alert message - - - Connecting via contact name requires a newer app version. - alert message - Connection Conexión @@ -2358,6 +2361,10 @@ This is your own one-time link! Conexión bloqueada No comment provided by engineer. + + Connection blocked: %@ + conn error description + Connection error Error conexión @@ -3147,7 +3154,7 @@ alert button No comment provided by engineer. - Destination server address of %@ is incompatible with forwarding server %@ settings. + Destination server address of %1$@ is incompatible with forwarding server %2$@ settings. La dirección del servidor de destino de %@ es incompatible con la configuración del servidor de reenvío %@. No comment provided by engineer. @@ -3157,7 +3164,7 @@ alert button snd error text - Destination server version of %@ is incompatible with forwarding server %@. + Destination server version of %1$@ is incompatible with forwarding server %2$@. La versión del servidor de destino de %@ es incompatible con el servidor de reenvío %@. No comment provided by engineer. @@ -3714,7 +3721,7 @@ chat item action Error Error - conn error description + No comment provided by engineer. Error aborting address change @@ -4014,6 +4021,10 @@ chat item action Error al guardar perfil de grupo No comment provided by engineer. + + Error saving name + alert title + Error saving passcode Error al guardar código de acceso @@ -4148,6 +4159,7 @@ chat item action Error: %@ Error: %@ alert message +conn error description file error text snd error text @@ -5371,6 +5383,14 @@ This is your link for group %@! Menos tráfico en redes móviles. No comment provided by engineer. + + Let people connect to you via name registered with your SimpleX address. + No comment provided by engineer. + + + Let people join via name registered with this channel link. + No comment provided by engineer. + Let someone connect to you Conecta con alguien @@ -5551,21 +5571,6 @@ This is your link for group %@! Informes de miembros chat feature - - Member role will be changed to "%@". All chat members will be notified. - El rol del miembro cambiará a "%@". Se notificará en el chat. - No comment provided by engineer. - - - Member role will be changed to "%@". All group members will be notified. - El rol del miembro cambiará a "%@" y se notificará al grupo. - No comment provided by engineer. - - - Member role will be changed to "%@". The member will receive a new invitation. - El rol del miembro cambiará a "%@" y recibirá una invitación nueva. - No comment provided by engineer. - Member will be removed from chat - this cannot be undone! El miembro será eliminado del chat. ¡No puede deshacerse! @@ -5925,6 +5930,10 @@ This is your link for group %@! Nombre swipe action + + Name not found + No comment provided by engineer. + Network & servers Servidores y Redes @@ -6257,6 +6266,10 @@ El cifrado más seguro. Sin servidores para recibir mensajes. servers error + + No servers to resolve names. + servers warning + No servers to send files. Sin servidores para enviar archivos. @@ -6272,6 +6285,10 @@ El cifrado más seguro. Ningún chat sin leer No comment provided by engineer. + + No valid link + No comment provided by engineer. + Nobody tracked your conversations. No one drew a map of where you'd been. Privacy was never a feature - it was the way of life. Nadie monitorizaba tus conversaciones. Nadie registraba tus ubicaciones. La privacidad nunca fue un lujo, era la manera de vivir. @@ -6282,6 +6299,10 @@ El cifrado más seguro. Gobernanza no lucrativa No comment provided by engineer. + + None of your servers are set to resolve SimpleX names. Configure servers, or use a connection link. + No comment provided by engineer. + Not a better lock on someone else's door. Not a nicer landlord that respects your privacy, but still keeps the record of all visitors. You are not a guest. You are home. No king can enter it - you are sovereign. No un candado mejorado en la puerta de otro. No un terrateniente que respeta tu privacidad pero sigue guardando un registro de tus visitantes. Tu no eres el invitado. Estás en tu casa y ningún rey podrá entrar. Tu eres el soberano. @@ -6700,9 +6721,8 @@ alert button Propietario No comment provided by engineer. - - Owners - Propietarios + + Owners & contributors No comment provided by engineer. @@ -6894,10 +6914,6 @@ Error: %@ Por favor, intenta desactivar y reactivar las notificaciones. token info - - Please upgrade the app. - alert message - Please wait for group moderators to review your request to join the group. Por favor, espera a que tu solicitud sea revisada por los moderadores del grupo. @@ -7618,6 +7634,10 @@ swipe action Restablecer al tema del usuario No comment provided by engineer. + + Resolver error: %@ + No comment provided by engineer. + Restart the app to create a new chat profile Reinicia la aplicación para crear un perfil nuevo @@ -7698,6 +7718,22 @@ swipe action Rol No comment provided by engineer. + + Role will be changed to "%@". All chat members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All group members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All subscribers will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". The member will receive a new invitation. + No comment provided by engineer. + Run chat Ejecutar SimpleX @@ -8242,6 +8278,10 @@ chat item action Servidor No comment provided by engineer. + + Server %@ does not support name resolution. Configure servers, or use a connection link. + No comment provided by engineer. + Server added to operator %@. Servidor añadido al operador %@. @@ -8678,6 +8718,18 @@ chat item action Enlaces SimpleX no permitidos No comment provided by engineer. + + SimpleX name + No comment provided by engineer. + + + SimpleX name error + No comment provided by engineer. + + + SimpleX name not verified + alert title + SimpleX one-time invitation Invitación SimpleX de un uso @@ -9154,6 +9206,22 @@ It can happen because of some bug or when the connection is compromised. No comment provided by engineer. + + The SimpleX name #%@ is registered without channel link. Add channel link to the name via the registration page. + alert message + + + The SimpleX name %@ is registered, but it has no valid link. + No comment provided by engineer. + + + The SimpleX name %@ is registered, but not added to profile. Please add it to your address or channel profile, if you are the owner. + No comment provided by engineer. + + + The SimpleX name @%@ is registered without SimpleX address. Add your SimpleX address to the name via the registration page. + alert message + The address will be short, and your profile will be shared via the address. La dirección pasará a ser corta y tu perfil será compartido mediante la dirección. @@ -9340,6 +9408,10 @@ y los contactos son tuyos. Se puede modificar desde la configuración particular de cada grupo y contacto. No comment provided by engineer. + + This SimpleX name is not registered. Please check the name. + No comment provided by engineer. + This action cannot be undone - all received and sent files and media will be deleted. Low resolution pictures will remain. Esta acción es irreversible. Se eliminarán todos los archivos y multimedia recibidos y enviados. Las imágenes de baja resolución permanecerán. @@ -9520,6 +9592,10 @@ Se te pedirá que completes la autenticación antes de activar esta función.Para grabar el mensaje de voz concede permiso para usar el micrófono. No comment provided by engineer. + + To resolve names + No comment provided by engineer. + To reveal your hidden profile, enter a full password into a search field in **Your chat profiles** page. Para hacer visible tu perfil oculto, introduce la contraseña en el campo de búsqueda del menú **Mis perfiles**. @@ -9645,6 +9721,10 @@ Se te pedirá que completes la autenticación antes de activar esta función.¿Desbloquear al suscriptor para todos? No comment provided by engineer. + + Unconfirmed name + No comment provided by engineer. + Undelivered messages Mensajes no entregados @@ -9742,19 +9822,11 @@ Para conectarte pide a tu contacto que cree otro enlace y comprueba la conexión No leído swipe action - - Unsupported channel name - alert title - Unsupported connection link Enlace de conexión no compatible conn error description - - Unsupported contact name - alert title - Unverified badge badge alert title @@ -10013,6 +10085,10 @@ Para conectarte pide a tu contacto que cree otro enlace y comprueba la conexión Verificar relay test step + + Verify SimpleX names + No comment provided by engineer. + Verify code with desktop Verificar código con ordenador @@ -10038,6 +10114,10 @@ Para conectarte pide a tu contacto que cree otro enlace y comprueba la conexión Verificar la contraseña de la base de datos No comment provided by engineer. + + Verify name + No comment provided by engineer. + Verify passphrase Verificar frase de contraseña @@ -10687,6 +10767,10 @@ Repeat connection request? Mi dirección SimpleX No comment provided by engineer. + + Your SimpleX name + No comment provided by engineer. + Your business contact Mi contacto empresarial @@ -11174,6 +11258,10 @@ marked deleted chat item preview text el contacto debe aceptarte… No comment provided by engineer. + + contributor + member role + creator creador @@ -11826,6 +11914,10 @@ last received msg: %2$@ tachado No comment provided by engineer. + + subscriber + member role + this contact este contacto diff --git a/apps/ios/SimpleX Localizations/fi.xcloc/Localized Contents/fi.xliff b/apps/ios/SimpleX Localizations/fi.xcloc/Localized Contents/fi.xliff index d1300df5ed..cf32c10c6d 100644 --- a/apps/ios/SimpleX Localizations/fi.xcloc/Localized Contents/fi.xliff +++ b/apps/ios/SimpleX Localizations/fi.xcloc/Localized Contents/fi.xliff @@ -184,6 +184,18 @@ %d kuukautta time interval + + %d owner + channel owners count + + + %d owners + channel owners count + + + %d owners & contributors + channel members count + %d relays failed channel relay bar @@ -1542,11 +1554,6 @@ new chat action Vaihda lukitustilaa authentication reason - - Change member role? - Vaihda jäsenroolia? - No comment provided by engineer. - Change passcode Vaihda pääsykoodi @@ -1567,6 +1574,10 @@ new chat action Vaihda rooli No comment provided by engineer. + + Change role? + No comment provided by engineer. + Change self-destruct mode Vaihda itsetuhotilaa @@ -2073,14 +2084,6 @@ This is your own one-time link! Connecting to desktop No comment provided by engineer. - - Connecting via channel name requires a newer app version. - alert message - - - Connecting via contact name requires a newer app version. - alert message - Connection Yhteys @@ -2094,6 +2097,10 @@ This is your own one-time link! Connection blocked No comment provided by engineer. + + Connection blocked: %@ + conn error description + Connection error Yhteysvirhe @@ -2814,7 +2821,7 @@ alert button No comment provided by engineer. - Destination server address of %@ is incompatible with forwarding server %@ settings. + Destination server address of %1$@ is incompatible with forwarding server %2$@ settings. No comment provided by engineer. @@ -2822,7 +2829,7 @@ alert button snd error text - Destination server version of %@ is incompatible with forwarding server %@. + Destination server version of %1$@ is incompatible with forwarding server %2$@. No comment provided by engineer. @@ -3326,7 +3333,7 @@ chat item action Error Virhe - conn error description + No comment provided by engineer. Error aborting address change @@ -3596,6 +3603,10 @@ chat item action Virhe ryhmäprofiilin tallentamisessa No comment provided by engineer. + + Error saving name + alert title + Error saving passcode Virhe pääsykoodin tallentamisessa @@ -3719,6 +3730,7 @@ chat item action Error: %@ Virhe: %@ alert message +conn error description file error text snd error text @@ -4825,6 +4837,14 @@ This is your link for group %@! Less traffic on mobile networks. No comment provided by engineer. + + Let people connect to you via name registered with your SimpleX address. + No comment provided by engineer. + + + Let people join via name registered with this channel link. + No comment provided by engineer. + Let someone connect to you No comment provided by engineer. @@ -4987,20 +5007,6 @@ This is your link for group %@! Member reports chat feature - - Member role will be changed to "%@". All chat members will be notified. - No comment provided by engineer. - - - Member role will be changed to "%@". All group members will be notified. - Jäsenen rooli muuttuu muotoon "%@". Kaikille ryhmän jäsenille ilmoitetaan asiasta. - No comment provided by engineer. - - - Member role will be changed to "%@". The member will receive a new invitation. - Jäsenen rooli muutetaan muotoon "%@". Jäsen saa uuden kutsun. - No comment provided by engineer. - Member will be removed from chat - this cannot be undone! alert message @@ -5319,6 +5325,10 @@ This is your link for group %@! Nimi swipe action + + Name not found + No comment provided by engineer. + Network & servers Verkko ja palvelimet @@ -5608,6 +5618,10 @@ The most secure encryption. No servers to receive messages. servers error + + No servers to resolve names. + servers warning + No servers to send files. servers error @@ -5620,6 +5634,10 @@ The most secure encryption. No unread chats No comment provided by engineer. + + No valid link + No comment provided by engineer. + Nobody tracked your conversations. No one drew a map of where you'd been. Privacy was never a feature - it was the way of life. No comment provided by engineer. @@ -5628,6 +5646,10 @@ The most secure encryption. Non-profit governance No comment provided by engineer. + + None of your servers are set to resolve SimpleX names. Configure servers, or use a connection link. + No comment provided by engineer. + Not a better lock on someone else's door. Not a nicer landlord that respects your privacy, but still keeps the record of all visitors. You are not a guest. You are home. No king can enter it - you are sovereign. No comment provided by engineer. @@ -5990,8 +6012,8 @@ alert button Owner No comment provided by engineer. - - Owners + + Owners & contributors No comment provided by engineer. @@ -6167,10 +6189,6 @@ Error: %@ Please try to disable and re-enable notfications. token info - - Please upgrade the app. - alert message - Please wait for group moderators to review your request to join the group. snd group event chat item @@ -6807,6 +6825,10 @@ swipe action Reset to user theme No comment provided by engineer. + + Resolver error: %@ + No comment provided by engineer. + Restart the app to create a new chat profile Käynnistä sovellus uudelleen uuden keskusteluprofiilin luomiseksi @@ -6882,6 +6904,22 @@ swipe action Rooli No comment provided by engineer. + + Role will be changed to "%@". All chat members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All group members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All subscribers will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". The member will receive a new invitation. + No comment provided by engineer. + Run chat Käynnistä chat @@ -7371,6 +7409,10 @@ chat item action Server No comment provided by engineer. + + Server %@ does not support name resolution. Configure servers, or use a connection link. + No comment provided by engineer. + Server added to operator %@. alert message @@ -7753,6 +7795,18 @@ chat item action SimpleX links not allowed No comment provided by engineer. + + SimpleX name + No comment provided by engineer. + + + SimpleX name error + No comment provided by engineer. + + + SimpleX name not verified + alert title + SimpleX one-time invitation SimpleX-kertakutsu @@ -8173,6 +8227,22 @@ It can happen because of some bug or when the connection is compromised. No comment provided by engineer. + + The SimpleX name #%@ is registered without channel link. Add channel link to the name via the registration page. + alert message + + + The SimpleX name %@ is registered, but it has no valid link. + No comment provided by engineer. + + + The SimpleX name %@ is registered, but not added to profile. Please add it to your address or channel profile, if you are the owner. + No comment provided by engineer. + + + The SimpleX name @%@ is registered without SimpleX address. Add your SimpleX address to the name via the registration page. + alert message + The address will be short, and your profile will be shared via the address. alert message @@ -8337,6 +8407,10 @@ your contacts and groups. Ne voidaan ohittaa kontakti- ja ryhmäasetuksissa. No comment provided by engineer. + + This SimpleX name is not registered. Please check the name. + No comment provided by engineer. + This action cannot be undone - all received and sent files and media will be deleted. Low resolution pictures will remain. Tätä toimintoa ei voi kumota - kaikki vastaanotetut ja lähetetyt tiedostot ja media poistetaan. Matalan resoluution kuvat säilyvät. @@ -8497,6 +8571,10 @@ Sinua kehotetaan suorittamaan todennus loppuun, ennen kuin tämä ominaisuus ote Jos haluat nauhoittaa ääniviestin, anna lupa käyttää mikrofonia. No comment provided by engineer. + + To resolve names + No comment provided by engineer. + To reveal your hidden profile, enter a full password into a search field in **Your chat profiles** page. Voit paljastaa piilotetun profiilisi syöttämällä koko salasanan hakukenttään **Keskusteluprofiilisi** -sivulla. @@ -8604,6 +8682,10 @@ Sinua kehotetaan suorittamaan todennus loppuun, ennen kuin tämä ominaisuus ote Unblock subscriber for all? No comment provided by engineer. + + Unconfirmed name + No comment provided by engineer. + Undelivered messages No comment provided by engineer. @@ -8697,18 +8779,10 @@ Jos haluat muodostaa yhteyden, pyydä kontaktiasi luomaan toinen yhteyslinkki ja Lukematon swipe action - - Unsupported channel name - alert title - Unsupported connection link conn error description - - Unsupported contact name - alert title - Unverified badge badge alert title @@ -8931,6 +9005,10 @@ Jos haluat muodostaa yhteyden, pyydä kontaktiasi luomaan toinen yhteyslinkki ja Verify relay test step + + Verify SimpleX names + No comment provided by engineer. + Verify code with desktop No comment provided by engineer. @@ -8952,6 +9030,10 @@ Jos haluat muodostaa yhteyden, pyydä kontaktiasi luomaan toinen yhteyslinkki ja Verify database passphrase No comment provided by engineer. + + Verify name + No comment provided by engineer. + Verify passphrase No comment provided by engineer. @@ -9534,6 +9616,10 @@ Repeat connection request? SimpleX-osoitteesi No comment provided by engineer. + + Your SimpleX name + No comment provided by engineer. + Your business contact No comment provided by engineer. @@ -9978,6 +10064,10 @@ marked deleted chat item preview text contact should accept… No comment provided by engineer. + + contributor + member role + creator luoja @@ -10580,6 +10670,10 @@ last received msg: %2$@ soita No comment provided by engineer. + + subscriber + member role + this contact tämä kontakti diff --git a/apps/ios/SimpleX Localizations/fr.xcloc/Localized Contents/fr.xliff b/apps/ios/SimpleX Localizations/fr.xcloc/Localized Contents/fr.xliff index 2d180fd51e..b743c5da98 100644 --- a/apps/ios/SimpleX Localizations/fr.xcloc/Localized Contents/fr.xliff +++ b/apps/ios/SimpleX Localizations/fr.xcloc/Localized Contents/fr.xliff @@ -197,6 +197,18 @@ %d mois time interval + + %d owner + channel owners count + + + %d owners + channel owners count + + + %d owners & contributors + channel members count + %d relays failed channel relay bar @@ -1677,11 +1689,6 @@ new chat action Modifier le mode de verrouillage authentication reason - - Change member role? - Changer le rôle du membre ? - No comment provided by engineer. - Change passcode Modifier le code d'accès @@ -1702,6 +1709,10 @@ new chat action Changer le rôle No comment provided by engineer. + + Change role? + No comment provided by engineer. + Change self-destruct mode Modifier le mode d'autodestruction @@ -2262,14 +2273,6 @@ Il s'agit de votre propre lien unique ! Connexion au bureau No comment provided by engineer. - - Connecting via channel name requires a newer app version. - alert message - - - Connecting via contact name requires a newer app version. - alert message - Connection Connexion @@ -2285,6 +2288,10 @@ Il s'agit de votre propre lien unique ! Connexion bloquée No comment provided by engineer. + + Connection blocked: %@ + conn error description + Connection error Erreur de connexion @@ -3056,7 +3063,7 @@ alert button No comment provided by engineer. - Destination server address of %@ is incompatible with forwarding server %@ settings. + Destination server address of %1$@ is incompatible with forwarding server %2$@ settings. L'adresse du serveur de destination %@ est incompatible avec les paramètres du serveur de redirection %@. No comment provided by engineer. @@ -3066,7 +3073,7 @@ alert button snd error text - Destination server version of %@ is incompatible with forwarding server %@. + Destination server version of %1$@ is incompatible with forwarding server %2$@. La version du serveur de destination %@ est incompatible avec le serveur de redirection %@. No comment provided by engineer. @@ -3610,7 +3617,7 @@ chat item action Error Erreur - conn error description + No comment provided by engineer. Error aborting address change @@ -3901,6 +3908,10 @@ chat item action Erreur lors de la sauvegarde du profil de groupe No comment provided by engineer. + + Error saving name + alert title + Error saving passcode Erreur lors de la sauvegarde du code d'accès @@ -4033,6 +4044,7 @@ chat item action Error: %@ Erreur : %@ alert message +conn error description file error text snd error text @@ -5221,6 +5233,14 @@ Voici votre lien pour le groupe %@ ! Less traffic on mobile networks. No comment provided by engineer. + + Let people connect to you via name registered with your SimpleX address. + No comment provided by engineer. + + + Let people join via name registered with this channel link. + No comment provided by engineer. + Let someone connect to you No comment provided by engineer. @@ -5389,21 +5409,6 @@ Voici votre lien pour le groupe %@ ! Member reports chat feature - - Member role will be changed to "%@". All chat members will be notified. - Le rôle du membre sera modifié pour « %@ ». Tous les membres du chat seront notifiés. - No comment provided by engineer. - - - Member role will be changed to "%@". All group members will be notified. - Le rôle du membre sera changé pour "%@". Tous les membres du groupe en seront informés. - No comment provided by engineer. - - - Member role will be changed to "%@". The member will receive a new invitation. - Le rôle du membre sera changé pour "%@". Ce membre recevra une nouvelle invitation. - No comment provided by engineer. - Member will be removed from chat - this cannot be undone! Le membre sera retiré de la discussion - cela ne peut pas être annulé ! @@ -5750,6 +5755,10 @@ Voici votre lien pour le groupe %@ ! Nom swipe action + + Name not found + No comment provided by engineer. + Network & servers Réseau et serveurs @@ -6062,6 +6071,10 @@ The most secure encryption. Pas de serveurs pour recevoir des messages. servers error + + No servers to resolve names. + servers warning + No servers to send files. Pas de serveurs pour envoyer des fichiers. @@ -6075,6 +6088,10 @@ The most secure encryption. No unread chats No comment provided by engineer. + + No valid link + No comment provided by engineer. + Nobody tracked your conversations. No one drew a map of where you'd been. Privacy was never a feature - it was the way of life. No comment provided by engineer. @@ -6083,6 +6100,10 @@ The most secure encryption. Non-profit governance No comment provided by engineer. + + None of your servers are set to resolve SimpleX names. Configure servers, or use a connection link. + No comment provided by engineer. + Not a better lock on someone else's door. Not a nicer landlord that respects your privacy, but still keeps the record of all visitors. You are not a guest. You are home. No king can enter it - you are sovereign. No comment provided by engineer. @@ -6469,8 +6490,8 @@ alert button Owner No comment provided by engineer. - - Owners + + Owners & contributors No comment provided by engineer. @@ -6659,10 +6680,6 @@ Erreur : %@ Please try to disable and re-enable notfications. token info - - Please upgrade the app. - alert message - Please wait for group moderators to review your request to join the group. snd group event chat item @@ -7341,6 +7358,10 @@ swipe action Réinitialisation au thème de l'utilisateur No comment provided by engineer. + + Resolver error: %@ + No comment provided by engineer. + Restart the app to create a new chat profile Redémarrez l'application pour créer un nouveau profil de chat @@ -7418,6 +7439,22 @@ swipe action Rôle No comment provided by engineer. + + Role will be changed to "%@". All chat members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All group members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All subscribers will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". The member will receive a new invitation. + No comment provided by engineer. + Run chat Exécuter le chat @@ -7939,6 +7976,10 @@ chat item action Serveur No comment provided by engineer. + + Server %@ does not support name resolution. Configure servers, or use a connection link. + No comment provided by engineer. + Server added to operator %@. Serveur ajouté à l'opérateur %@. @@ -8356,6 +8397,18 @@ chat item action Les liens SimpleX ne sont pas autorisés No comment provided by engineer. + + SimpleX name + No comment provided by engineer. + + + SimpleX name error + No comment provided by engineer. + + + SimpleX name not verified + alert title + SimpleX one-time invitation Invitation unique SimpleX @@ -8803,6 +8856,22 @@ It can happen because of some bug or when the connection is compromised. No comment provided by engineer. + + The SimpleX name #%@ is registered without channel link. Add channel link to the name via the registration page. + alert message + + + The SimpleX name %@ is registered, but it has no valid link. + No comment provided by engineer. + + + The SimpleX name %@ is registered, but not added to profile. Please add it to your address or channel profile, if you are the owner. + No comment provided by engineer. + + + The SimpleX name @%@ is registered without SimpleX address. Add your SimpleX address to the name via the registration page. + alert message + The address will be short, and your profile will be shared via the address. alert message @@ -8980,6 +9049,10 @@ your contacts and groups. Ils peuvent être modifiés dans les paramètres des contacts et des groupes. No comment provided by engineer. + + This SimpleX name is not registered. Please check the name. + No comment provided by engineer. + This action cannot be undone - all received and sent files and media will be deleted. Low resolution pictures will remain. Cette action ne peut être annulée - tous les fichiers et médias reçus et envoyés seront supprimés. Les photos à faible résolution seront conservées. @@ -9152,6 +9225,10 @@ Vous serez invité à confirmer l'authentification avant que cette fonction ne s Pour enregistrer un message vocal, veuillez accorder la permission d'utiliser le microphone. No comment provided by engineer. + + To resolve names + No comment provided by engineer. + To reveal your hidden profile, enter a full password into a search field in **Your chat profiles** page. Pour révéler votre profil caché, entrez le mot de passe dans le champ de recherche de la page **Vos profils de chat**. @@ -9271,6 +9348,10 @@ Vous serez invité à confirmer l'authentification avant que cette fonction ne s Unblock subscriber for all? No comment provided by engineer. + + Unconfirmed name + No comment provided by engineer. + Undelivered messages Messages non distribués @@ -9368,18 +9449,10 @@ Pour vous connecter, veuillez demander à votre contact de créer un autre lien Non lu swipe action - - Unsupported channel name - alert title - Unsupported connection link conn error description - - Unsupported contact name - alert title - Unverified badge badge alert title @@ -9622,6 +9695,10 @@ Pour vous connecter, veuillez demander à votre contact de créer un autre lien Verify relay test step + + Verify SimpleX names + No comment provided by engineer. + Verify code with desktop Vérifier le code avec le bureau @@ -9647,6 +9724,10 @@ Pour vous connecter, veuillez demander à votre contact de créer un autre lien Vérifier la phrase secrète de la base de données No comment provided by engineer. + + Verify name + No comment provided by engineer. + Verify passphrase Vérifier la phrase secrète @@ -10277,6 +10358,10 @@ Répéter la demande de connexion ? Votre adresse SimpleX No comment provided by engineer. + + Your SimpleX name + No comment provided by engineer. + Your business contact No comment provided by engineer. @@ -10738,6 +10823,10 @@ marked deleted chat item preview text contact should accept… No comment provided by engineer. + + contributor + member role + creator créateur @@ -11365,6 +11454,10 @@ dernier message reçu : %2$@ barré No comment provided by engineer. + + subscriber + member role + this contact ce contact diff --git a/apps/ios/SimpleX Localizations/hu.xcloc/Localized Contents/hu.xliff b/apps/ios/SimpleX Localizations/hu.xcloc/Localized Contents/hu.xliff index c0ddfedc0b..cbbda85b5d 100644 --- a/apps/ios/SimpleX Localizations/hu.xcloc/Localized Contents/hu.xliff +++ b/apps/ios/SimpleX Localizations/hu.xcloc/Localized Contents/hu.xliff @@ -197,6 +197,18 @@ %d hónap time interval + + %d owner + channel owners count + + + %d owners + channel owners count + + + %d owners & contributors + channel members count + %d relays failed %d átjátszóhoz nem sikerült kapcsolódni @@ -1720,11 +1732,6 @@ new chat action Zárolási mód módosítása authentication reason - - Change member role? - Módosítja a tag szerepkörét? - No comment provided by engineer. - Change passcode Jelkód módosítása @@ -1745,6 +1752,10 @@ new chat action Szerepkör módosítása No comment provided by engineer. + + Change role? + No comment provided by engineer. + Change self-destruct mode Önmegsemmisítő-mód módosítása @@ -2335,14 +2346,6 @@ Ez a saját egyszer használható meghívója! Társítás számítógéppel No comment provided by engineer. - - Connecting via channel name requires a newer app version. - alert message - - - Connecting via contact name requires a newer app version. - alert message - Connection Kapcsolat @@ -2358,6 +2361,10 @@ Ez a saját egyszer használható meghívója! A kapcsolat le van tiltva No comment provided by engineer. + + Connection blocked: %@ + conn error description + Connection error Kapcsolódási hiba @@ -3147,7 +3154,7 @@ alert button No comment provided by engineer. - Destination server address of %@ is incompatible with forwarding server %@ settings. + Destination server address of %1$@ is incompatible with forwarding server %2$@ settings. A(z) %@ célkiszolgáló címe nem kompatibilis a(z) %@ továbbító kiszolgáló beállításaival. No comment provided by engineer. @@ -3157,7 +3164,7 @@ alert button snd error text - Destination server version of %@ is incompatible with forwarding server %@. + Destination server version of %1$@ is incompatible with forwarding server %2$@. A(z) %@ célkiszolgáló verziója nem kompatibilis a(z) %@ továbbító kiszolgálóval. No comment provided by engineer. @@ -3714,7 +3721,7 @@ chat item action Error Hiba - conn error description + No comment provided by engineer. Error aborting address change @@ -4014,6 +4021,10 @@ chat item action Hiba történt a csoportprofil mentésekor No comment provided by engineer. + + Error saving name + alert title + Error saving passcode Hiba történt a jelkód mentésekor @@ -4148,6 +4159,7 @@ chat item action Error: %@ Hiba: %@ alert message +conn error description file error text snd error text @@ -5371,6 +5383,14 @@ Ez a saját hivatkozása a(z) %@ nevű csoporthoz! Kevesebb adatforgalom a mobilhálózatokon. No comment provided by engineer. + + Let people connect to you via name registered with your SimpleX address. + No comment provided by engineer. + + + Let people join via name registered with this channel link. + No comment provided by engineer. + Let someone connect to you Legyen elérhető mások számára @@ -5551,21 +5571,6 @@ Ez a saját hivatkozása a(z) %@ nevű csoporthoz! Tagok jelentései chat feature - - Member role will be changed to "%@". All chat members will be notified. - A tag szerepköre a következőre fog módosulni: „%@”. A csevegés összes tagja értesítést fog kapni. - No comment provided by engineer. - - - Member role will be changed to "%@". All group members will be notified. - A tag szerepköre a következőre fog módosulni: „%@”. A csoport az összes tagja értesítést fog kapni. - No comment provided by engineer. - - - Member role will be changed to "%@". The member will receive a new invitation. - A tag szerepköre a következőre fog módosulni: „%@”. A tag új meghívást fog kapni. - No comment provided by engineer. - Member will be removed from chat - this cannot be undone! A tag el lesz távolítva a csevegésből – ez a művelet nem vonható vissza! @@ -5925,6 +5930,10 @@ Ez a saját hivatkozása a(z) %@ nevű csoporthoz! Név swipe action + + Name not found + No comment provided by engineer. + Network & servers Hálózat és kiszolgálók @@ -6257,6 +6266,10 @@ A legbiztonságosabb titkosítás. Nincsenek üzenetfogadási kiszolgálók. servers error + + No servers to resolve names. + servers warning + No servers to send files. Nincsenek fájlküldési kiszolgálók. @@ -6272,6 +6285,10 @@ A legbiztonságosabb titkosítás. Nincsenek olvasatlan csevegések No comment provided by engineer. + + No valid link + No comment provided by engineer. + Nobody tracked your conversations. No one drew a map of where you'd been. Privacy was never a feature - it was the way of life. Senki sem követte nyomon a beszélgetéseinket. Senki sem készített térképet arról, hogy merre jártunk. A magánéletünk nem csak egy funkció volt, hanem az életmódunk. @@ -6282,6 +6299,10 @@ A legbiztonságosabb titkosítás. Nonprofit irányítás No comment provided by engineer. + + None of your servers are set to resolve SimpleX names. Configure servers, or use a connection link. + No comment provided by engineer. + Not a better lock on someone else's door. Not a nicer landlord that respects your privacy, but still keeps the record of all visitors. You are not a guest. You are home. No king can enter it - you are sovereign. Nem egy jobb zár mások ajtaján. Nem egy kedvesebb házmester, aki tiszteletben tartja az Ön magánéletét, de mégis nyilvántartást vezet minden látogatójáról. Ön itt nem csak egy vendég. Ön itt otthon van. Nincs az a hatalom, amely beléphetne ide - Ön itt szuverén. @@ -6700,9 +6721,8 @@ alert button Tulajdonos No comment provided by engineer. - - Owners - Tulajdonosok + + Owners & contributors No comment provided by engineer. @@ -6894,10 +6914,6 @@ Hiba: %@ Próbálja meg letiltani és újra engedélyezni az értesítéseket. token info - - Please upgrade the app. - alert message - Please wait for group moderators to review your request to join the group. Várja meg, amíg a csoport moderátorai áttekintik a csoporthoz való csatlakozási kérését. @@ -7618,6 +7634,10 @@ swipe action Felhasználó által létrehozott téma visszaállítása No comment provided by engineer. + + Resolver error: %@ + No comment provided by engineer. + Restart the app to create a new chat profile Új csevegési profil létrehozásához indítsa újra az alkalmazást @@ -7698,6 +7718,22 @@ swipe action Szerepkör No comment provided by engineer. + + Role will be changed to "%@". All chat members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All group members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All subscribers will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". The member will receive a new invitation. + No comment provided by engineer. + Run chat Csevegési szolgáltatás indítása @@ -8242,6 +8278,10 @@ chat item action Kiszolgáló No comment provided by engineer. + + Server %@ does not support name resolution. Configure servers, or use a connection link. + No comment provided by engineer. + Server added to operator %@. Kiszolgáló hozzáadva a következő üzemeltetőhöz: %@. @@ -8678,6 +8718,18 @@ chat item action A SimpleX-hivatkozások küldése le van tiltva No comment provided by engineer. + + SimpleX name + No comment provided by engineer. + + + SimpleX name error + No comment provided by engineer. + + + SimpleX name not verified + alert title + SimpleX one-time invitation Egyszer használható SimpleX meghívó @@ -9154,6 +9206,22 @@ It can happen because of some bug or when the connection is compromised. No comment provided by engineer. + + The SimpleX name #%@ is registered without channel link. Add channel link to the name via the registration page. + alert message + + + The SimpleX name %@ is registered, but it has no valid link. + No comment provided by engineer. + + + The SimpleX name %@ is registered, but not added to profile. Please add it to your address or channel profile, if you are the owner. + No comment provided by engineer. + + + The SimpleX name @%@ is registered without SimpleX address. Add your SimpleX address to the name via the registration page. + alert message + The address will be short, and your profile will be shared via the address. A cím rövid lesz és a profil meg lesz osztva a címen keresztül. @@ -9340,6 +9408,10 @@ a saját kapcsolatait és csoportjait. Ezek felülbírálhatók a partner- és csoportbeállításokban. No comment provided by engineer. + + This SimpleX name is not registered. Please check the name. + No comment provided by engineer. + This action cannot be undone - all received and sent files and media will be deleted. Low resolution pictures will remain. Ez a művelet nem vonható vissza – az összes fogadott és küldött fájl a médiatartalmakkal együtt törölve lesznek. Az alacsony felbontású képek viszont megmaradnak. @@ -9520,6 +9592,10 @@ A funkció bekapcsolása előtt a rendszer felszólítja a képernyőzár beáll Hangüzenet rögzítéséhez adjon engedélyt a mikrofon használathoz. No comment provided by engineer. + + To resolve names + No comment provided by engineer. + To reveal your hidden profile, enter a full password into a search field in **Your chat profiles** page. Rejtett profilja felfedéséhez adja meg a teljes jelszót a keresőmezőben, a **Csevegési profilok** menüben. @@ -9645,6 +9721,10 @@ A funkció bekapcsolása előtt a rendszer felszólítja a képernyőzár beáll Az összes feliratkozó számára feloldja a feliratkozó letiltását? No comment provided by engineer. + + Unconfirmed name + No comment provided by engineer. + Undelivered messages Kézbesítetlen üzenetek @@ -9742,19 +9822,11 @@ A kapcsolódáshoz kérje meg a partnerét, hogy hozzon létre egy másik kapcso Olvasatlan swipe action - - Unsupported channel name - alert title - Unsupported connection link Nem támogatott kapcsolattartási hivatkozás conn error description - - Unsupported contact name - alert title - Unverified badge badge alert title @@ -10013,6 +10085,10 @@ A kapcsolódáshoz kérje meg a partnerét, hogy hozzon létre egy másik kapcso Ellenőrzés relay test step + + Verify SimpleX names + No comment provided by engineer. + Verify code with desktop Kód ellenőrzése a számítógépen @@ -10038,6 +10114,10 @@ A kapcsolódáshoz kérje meg a partnerét, hogy hozzon létre egy másik kapcso Adatbázis jelmondatának ellenőrzése No comment provided by engineer. + + Verify name + No comment provided by engineer. + Verify passphrase Jelmondat ellenőrzése @@ -10687,6 +10767,10 @@ Megismétli a kapcsolódási kérést? Profil SimpleX-címe No comment provided by engineer. + + Your SimpleX name + No comment provided by engineer. + Your business contact Üzleti partner @@ -11174,6 +11258,10 @@ marked deleted chat item preview text a partnernek el kell fogadnia… No comment provided by engineer. + + contributor + member role + creator készítő @@ -11826,6 +11914,10 @@ utoljára fogadott üzenet: %2$@ áthúzott No comment provided by engineer. + + subscriber + member role + this contact ez a partner diff --git a/apps/ios/SimpleX Localizations/it.xcloc/Localized Contents/it.xliff b/apps/ios/SimpleX Localizations/it.xcloc/Localized Contents/it.xliff index ae720efdeb..2626efcd5d 100644 --- a/apps/ios/SimpleX Localizations/it.xcloc/Localized Contents/it.xliff +++ b/apps/ios/SimpleX Localizations/it.xcloc/Localized Contents/it.xliff @@ -197,6 +197,18 @@ %d mesi time interval + + %d owner + channel owners count + + + %d owners + channel owners count + + + %d owners & contributors + channel members count + %d relays failed %d relay falliti @@ -1720,11 +1732,6 @@ new chat action Cambia modalità di blocco authentication reason - - Change member role? - Cambiare ruolo del membro? - No comment provided by engineer. - Change passcode Cambia codice di accesso @@ -1745,6 +1752,10 @@ new chat action Cambia ruolo No comment provided by engineer. + + Change role? + No comment provided by engineer. + Change self-destruct mode Cambia modalità di autodistruzione @@ -2335,14 +2346,6 @@ Questo è il tuo link una tantum! Connessione al desktop No comment provided by engineer. - - Connecting via channel name requires a newer app version. - alert message - - - Connecting via contact name requires a newer app version. - alert message - Connection Connessione @@ -2358,6 +2361,10 @@ Questo è il tuo link una tantum! Connessione bloccata No comment provided by engineer. + + Connection blocked: %@ + conn error description + Connection error Errore di connessione @@ -3147,7 +3154,7 @@ alert button No comment provided by engineer. - Destination server address of %@ is incompatible with forwarding server %@ settings. + Destination server address of %1$@ is incompatible with forwarding server %2$@ settings. L'indirizzo del server di destinazione di %@ è incompatibile con le impostazioni del server di inoltro %@. No comment provided by engineer. @@ -3157,7 +3164,7 @@ alert button snd error text - Destination server version of %@ is incompatible with forwarding server %@. + Destination server version of %1$@ is incompatible with forwarding server %2$@. La versione del server di destinazione di %@ è incompatibile con il server di inoltro %@. No comment provided by engineer. @@ -3714,7 +3721,7 @@ chat item action Error Errore - conn error description + No comment provided by engineer. Error aborting address change @@ -4014,6 +4021,10 @@ chat item action Errore nel salvataggio del profilo del gruppo No comment provided by engineer. + + Error saving name + alert title + Error saving passcode Errore nel salvataggio del codice di accesso @@ -4148,6 +4159,7 @@ chat item action Error: %@ Errore: %@ alert message +conn error description file error text snd error text @@ -5371,6 +5383,14 @@ Questo è il tuo link per il gruppo %@! Meno traffico sulle reti mobili. No comment provided by engineer. + + Let people connect to you via name registered with your SimpleX address. + No comment provided by engineer. + + + Let people join via name registered with this channel link. + No comment provided by engineer. + Let someone connect to you Lascia che qualcuno si connetta a te @@ -5551,21 +5571,6 @@ Questo è il tuo link per il gruppo %@! Segnalazioni dei membri chat feature - - Member role will be changed to "%@". All chat members will be notified. - Il ruolo del membro verrà cambiato in "%@". Verranno notificati tutti i membri della chat. - No comment provided by engineer. - - - Member role will be changed to "%@". All group members will be notified. - Il ruolo del membro verrà cambiato in "%@". Tutti i membri del gruppo verranno avvisati. - No comment provided by engineer. - - - Member role will be changed to "%@". The member will receive a new invitation. - Il ruolo del membro verrà cambiato in "%@". Il membro riceverà un invito nuovo. - No comment provided by engineer. - Member will be removed from chat - this cannot be undone! Il membro verrà rimosso dalla chat, non è reversibile! @@ -5925,6 +5930,10 @@ Questo è il tuo link per il gruppo %@! Nome swipe action + + Name not found + No comment provided by engineer. + Network & servers Rete e server @@ -6257,6 +6266,10 @@ La crittografia più sicura. Nessun server per ricevere messaggi. servers error + + No servers to resolve names. + servers warning + No servers to send files. Nessun server per inviare file. @@ -6272,6 +6285,10 @@ La crittografia più sicura. Nessuna chat non letta No comment provided by engineer. + + No valid link + No comment provided by engineer. + Nobody tracked your conversations. No one drew a map of where you'd been. Privacy was never a feature - it was the way of life. Nessuno monitorava le tue conversazioni. Nessuno disegnava una mappa delle tue posizioni. La privacy non era mai stata una caratteristica, era uno stile di vita. @@ -6282,6 +6299,10 @@ La crittografia più sicura. Organizzazione non a scopo di lucro No comment provided by engineer. + + None of your servers are set to resolve SimpleX names. Configure servers, or use a connection link. + No comment provided by engineer. + Not a better lock on someone else's door. Not a nicer landlord that respects your privacy, but still keeps the record of all visitors. You are not a guest. You are home. No king can enter it - you are sovereign. Non una serratura migliore sulla porta di qualcun altro. Non un padrone di casa più gentile che rispetta la tua privacy, ma che continua a tenere traccia di tutti i visitatori. Non sei un ospite. Sei a casa tua. Nessun re può entrarvi: sei tu il sovrano. @@ -6700,9 +6721,8 @@ alert button Proprietario No comment provided by engineer. - - Owners - Proprietari + + Owners & contributors No comment provided by engineer. @@ -6894,10 +6914,6 @@ Errore: %@ Prova a disattivare e riattivare le notifiche. token info - - Please upgrade the app. - alert message - Please wait for group moderators to review your request to join the group. Attendi che i moderatori del gruppo revisionino la tua richiesta di entrare nel gruppo. @@ -7618,6 +7634,10 @@ swipe action Ripristina al tema dell'utente No comment provided by engineer. + + Resolver error: %@ + No comment provided by engineer. + Restart the app to create a new chat profile Riavvia l'app per creare un nuovo profilo di chat @@ -7698,6 +7718,22 @@ swipe action Ruolo No comment provided by engineer. + + Role will be changed to "%@". All chat members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All group members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All subscribers will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". The member will receive a new invitation. + No comment provided by engineer. + Run chat Avvia chat @@ -8242,6 +8278,10 @@ chat item action Server No comment provided by engineer. + + Server %@ does not support name resolution. Configure servers, or use a connection link. + No comment provided by engineer. + Server added to operator %@. Server aggiunto all'operatore %@. @@ -8678,6 +8718,18 @@ chat item action Link di SimpleX non consentiti No comment provided by engineer. + + SimpleX name + No comment provided by engineer. + + + SimpleX name error + No comment provided by engineer. + + + SimpleX name not verified + alert title + SimpleX one-time invitation Invito SimpleX una tantum @@ -9154,6 +9206,22 @@ It can happen because of some bug or when the connection is compromised. No comment provided by engineer. + + The SimpleX name #%@ is registered without channel link. Add channel link to the name via the registration page. + alert message + + + The SimpleX name %@ is registered, but it has no valid link. + No comment provided by engineer. + + + The SimpleX name %@ is registered, but not added to profile. Please add it to your address or channel profile, if you are the owner. + No comment provided by engineer. + + + The SimpleX name @%@ is registered without SimpleX address. Add your SimpleX address to the name via the registration page. + alert message + The address will be short, and your profile will be shared via the address. L'indirizzo sarà breve e il tuo profilo verrà condiviso attraverso l'indirizzo. @@ -9340,6 +9408,10 @@ i tuoi contatti e i tuoi gruppi. Possono essere sovrascritte nelle impostazioni dei contatti e dei gruppi. No comment provided by engineer. + + This SimpleX name is not registered. Please check the name. + No comment provided by engineer. + This action cannot be undone - all received and sent files and media will be deleted. Low resolution pictures will remain. Questa azione non può essere annullata: tutti i file e i media ricevuti e inviati verranno eliminati. Rimarranno le immagini a bassa risoluzione. @@ -9520,6 +9592,10 @@ Ti verrà chiesto di completare l'autenticazione prima di attivare questa funzio Per registrare un messaggio vocale, concedi l'autorizzazione all'uso del microfono. No comment provided by engineer. + + To resolve names + No comment provided by engineer. + To reveal your hidden profile, enter a full password into a search field in **Your chat profiles** page. Per rivelare il tuo profilo nascosto, inserisci una password completa in un campo di ricerca nella pagina **I tuoi profili di chat**. @@ -9645,6 +9721,10 @@ Ti verrà chiesto di completare l'autenticazione prima di attivare questa funzio Sbloccare l'iscritto per tutti? No comment provided by engineer. + + Unconfirmed name + No comment provided by engineer. + Undelivered messages Messaggi non consegnati @@ -9742,19 +9822,11 @@ Per connetterti, chiedi al tuo contatto di creare un altro link di connessione e Non letto swipe action - - Unsupported channel name - alert title - Unsupported connection link Link di connessione non supportato conn error description - - Unsupported contact name - alert title - Unverified badge badge alert title @@ -10013,6 +10085,10 @@ Per connetterti, chiedi al tuo contatto di creare un altro link di connessione e Verifica relay test step + + Verify SimpleX names + No comment provided by engineer. + Verify code with desktop Verifica il codice con il desktop @@ -10038,6 +10114,10 @@ Per connetterti, chiedi al tuo contatto di creare un altro link di connessione e Verifica password del database No comment provided by engineer. + + Verify name + No comment provided by engineer. + Verify passphrase Verifica password @@ -10687,6 +10767,10 @@ Ripetere la richiesta di connessione? Il tuo indirizzo SimpleX No comment provided by engineer. + + Your SimpleX name + No comment provided by engineer. + Your business contact Il tuo contatto lavorativo @@ -11174,6 +11258,10 @@ marked deleted chat item preview text il contatto dovrebbe accettare… No comment provided by engineer. + + contributor + member role + creator creatore @@ -11826,6 +11914,10 @@ ultimo msg ricevuto: %2$@ barrato No comment provided by engineer. + + subscriber + member role + this contact questo contatto diff --git a/apps/ios/SimpleX Localizations/ja.xcloc/Localized Contents/ja.xliff b/apps/ios/SimpleX Localizations/ja.xcloc/Localized Contents/ja.xliff index 4c5970f087..b8e1497bba 100644 --- a/apps/ios/SimpleX Localizations/ja.xcloc/Localized Contents/ja.xliff +++ b/apps/ios/SimpleX Localizations/ja.xcloc/Localized Contents/ja.xliff @@ -197,6 +197,18 @@ %d 月 time interval + + %d owner + channel owners count + + + %d owners + channel owners count + + + %d owners & contributors + channel members count + %d relays failed channel relay bar @@ -1617,11 +1629,6 @@ new chat action ロックモードを変更 authentication reason - - Change member role? - メンバーの役割を変更しますか? - No comment provided by engineer. - Change passcode パスコードを変更 @@ -1642,6 +1649,10 @@ new chat action 役割変更 No comment provided by engineer. + + Change role? + No comment provided by engineer. + Change self-destruct mode 自己破壊モードの変更 @@ -2166,14 +2177,6 @@ This is your own one-time link! デスクトップに接続中 No comment provided by engineer. - - Connecting via channel name requires a newer app version. - alert message - - - Connecting via contact name requires a newer app version. - alert message - Connection 接続 @@ -2188,6 +2191,10 @@ This is your own one-time link! Connection blocked No comment provided by engineer. + + Connection blocked: %@ + conn error description + Connection error 接続エラー @@ -2913,7 +2920,7 @@ alert button No comment provided by engineer. - Destination server address of %@ is incompatible with forwarding server %@ settings. + Destination server address of %1$@ is incompatible with forwarding server %2$@ settings. No comment provided by engineer. @@ -2921,7 +2928,7 @@ alert button snd error text - Destination server version of %@ is incompatible with forwarding server %@. + Destination server version of %1$@ is incompatible with forwarding server %2$@. No comment provided by engineer. @@ -3433,7 +3440,7 @@ chat item action Error エラー - conn error description + No comment provided by engineer. Error aborting address change @@ -3703,6 +3710,10 @@ chat item action グループのプロフィール保存にエラー発生 No comment provided by engineer. + + Error saving name + alert title + Error saving passcode パスコードの保存にエラー発生 @@ -3826,6 +3837,7 @@ chat item action Error: %@ エラー : %@ alert message +conn error description file error text snd error text @@ -4932,6 +4944,14 @@ This is your link for group %@! Less traffic on mobile networks. No comment provided by engineer. + + Let people connect to you via name registered with your SimpleX address. + No comment provided by engineer. + + + Let people join via name registered with this channel link. + No comment provided by engineer. + Let someone connect to you No comment provided by engineer. @@ -5094,20 +5114,6 @@ This is your link for group %@! Member reports chat feature - - Member role will be changed to "%@". All chat members will be notified. - No comment provided by engineer. - - - Member role will be changed to "%@". All group members will be notified. - メンバーの役割が "%@" に変更されます。 グループメンバー全員に通知されます。 - No comment provided by engineer. - - - Member role will be changed to "%@". The member will receive a new invitation. - メンバーの役割が "%@" に変更されます。 メンバーは新たな招待を受け取ります。 - No comment provided by engineer. - Member will be removed from chat - this cannot be undone! alert message @@ -5427,6 +5433,10 @@ This is your link for group %@! 名前 swipe action + + Name not found + No comment provided by engineer. + Network & servers ネットワークとサーバ @@ -5717,6 +5727,10 @@ The most secure encryption. No servers to receive messages. servers error + + No servers to resolve names. + servers warning + No servers to send files. servers error @@ -5729,6 +5743,10 @@ The most secure encryption. No unread chats No comment provided by engineer. + + No valid link + No comment provided by engineer. + Nobody tracked your conversations. No one drew a map of where you'd been. Privacy was never a feature - it was the way of life. No comment provided by engineer. @@ -5737,6 +5755,10 @@ The most secure encryption. Non-profit governance No comment provided by engineer. + + None of your servers are set to resolve SimpleX names. Configure servers, or use a connection link. + No comment provided by engineer. + Not a better lock on someone else's door. Not a nicer landlord that respects your privacy, but still keeps the record of all visitors. You are not a guest. You are home. No king can enter it - you are sovereign. No comment provided by engineer. @@ -6100,8 +6122,8 @@ alert button Owner No comment provided by engineer. - - Owners + + Owners & contributors No comment provided by engineer. @@ -6277,10 +6299,6 @@ Error: %@ Please try to disable and re-enable notfications. token info - - Please upgrade the app. - alert message - Please wait for group moderators to review your request to join the group. snd group event chat item @@ -6917,6 +6935,10 @@ swipe action Reset to user theme No comment provided by engineer. + + Resolver error: %@ + No comment provided by engineer. + Restart the app to create a new chat profile 新しいチャットプロファイルを作成するためにアプリを再起動する @@ -6992,6 +7014,22 @@ swipe action 役割 No comment provided by engineer. + + Role will be changed to "%@". All chat members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All group members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All subscribers will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". The member will receive a new invitation. + No comment provided by engineer. + Run chat チャット起動 @@ -7474,6 +7512,10 @@ chat item action Server No comment provided by engineer. + + Server %@ does not support name resolution. Configure servers, or use a connection link. + No comment provided by engineer. + Server added to operator %@. alert message @@ -7856,6 +7898,18 @@ chat item action SimpleX links not allowed No comment provided by engineer. + + SimpleX name + No comment provided by engineer. + + + SimpleX name error + No comment provided by engineer. + + + SimpleX name not verified + alert title + SimpleX one-time invitation SimpleX使い捨て招待リンク @@ -8277,6 +8331,22 @@ It can happen because of some bug or when the connection is compromised. No comment provided by engineer. + + The SimpleX name #%@ is registered without channel link. Add channel link to the name via the registration page. + alert message + + + The SimpleX name %@ is registered, but it has no valid link. + No comment provided by engineer. + + + The SimpleX name %@ is registered, but not added to profile. Please add it to your address or channel profile, if you are the owner. + No comment provided by engineer. + + + The SimpleX name @%@ is registered without SimpleX address. Add your SimpleX address to the name via the registration page. + alert message + The address will be short, and your profile will be shared via the address. alert message @@ -8441,6 +8511,10 @@ your contacts and groups. これらは連絡先の設定が優先します。 No comment provided by engineer. + + This SimpleX name is not registered. Please check the name. + No comment provided by engineer. + This action cannot be undone - all received and sent files and media will be deleted. Low resolution pictures will remain. ファイルとメディアが全て削除されます (※元に戻せません※)。低解像度の画像が残ります。 @@ -8600,6 +8674,10 @@ You will be prompted to complete authentication before this feature is enabled.< 音声メッセージを録音する場合は、マイクの使用を許可してください。 No comment provided by engineer. + + To resolve names + No comment provided by engineer. + To reveal your hidden profile, enter a full password into a search field in **Your chat profiles** page. 非表示のプロフィールを表示するには、**チャット プロフィール** ページの検索フィールドに完全なパスワードを入力します。 @@ -8707,6 +8785,10 @@ You will be prompted to complete authentication before this feature is enabled.< Unblock subscriber for all? No comment provided by engineer. + + Unconfirmed name + No comment provided by engineer. + Undelivered messages No comment provided by engineer. @@ -8800,18 +8882,10 @@ To connect, please ask your contact to create another connection link and check 未読 swipe action - - Unsupported channel name - alert title - Unsupported connection link conn error description - - Unsupported contact name - alert title - Unverified badge badge alert title @@ -9034,6 +9108,10 @@ To connect, please ask your contact to create another connection link and check Verify relay test step + + Verify SimpleX names + No comment provided by engineer. + Verify code with desktop No comment provided by engineer. @@ -9055,6 +9133,10 @@ To connect, please ask your contact to create another connection link and check Verify database passphrase No comment provided by engineer. + + Verify name + No comment provided by engineer. + Verify passphrase No comment provided by engineer. @@ -9638,6 +9720,10 @@ Repeat connection request? あなたのSimpleXアドレス No comment provided by engineer. + + Your SimpleX name + No comment provided by engineer. + Your business contact No comment provided by engineer. @@ -10082,6 +10168,10 @@ marked deleted chat item preview text contact should accept… No comment provided by engineer. + + contributor + member role + creator 作成者 @@ -10685,6 +10775,10 @@ last received msg: %2$@ 取り消し線 No comment provided by engineer. + + subscriber + member role + this contact この連絡先 diff --git a/apps/ios/SimpleX Localizations/nl.xcloc/Localized Contents/nl.xliff b/apps/ios/SimpleX Localizations/nl.xcloc/Localized Contents/nl.xliff index 26dec5caf6..78a4b80039 100644 --- a/apps/ios/SimpleX Localizations/nl.xcloc/Localized Contents/nl.xliff +++ b/apps/ios/SimpleX Localizations/nl.xcloc/Localized Contents/nl.xliff @@ -197,6 +197,18 @@ %d maanden time interval + + %d owner + channel owners count + + + %d owners + channel owners count + + + %d owners & contributors + channel members count + %d relays failed channel relay bar @@ -1674,11 +1686,6 @@ new chat action Wijzig de vergrendelings modus authentication reason - - Change member role? - Rol van lid wijzigen? - No comment provided by engineer. - Change passcode Toegangscode wijzigen @@ -1699,6 +1706,10 @@ new chat action Rol wijzigen No comment provided by engineer. + + Change role? + No comment provided by engineer. + Change self-destruct mode Zelfvernietigings modus wijzigen @@ -2262,14 +2273,6 @@ Dit is uw eigen eenmalige link! Verbinding maken met desktop No comment provided by engineer. - - Connecting via channel name requires a newer app version. - alert message - - - Connecting via contact name requires a newer app version. - alert message - Connection Verbinding @@ -2285,6 +2288,10 @@ Dit is uw eigen eenmalige link! Verbinding geblokkeerd No comment provided by engineer. + + Connection blocked: %@ + conn error description + Connection error Verbindingsfout @@ -3057,7 +3064,7 @@ alert button No comment provided by engineer. - Destination server address of %@ is incompatible with forwarding server %@ settings. + Destination server address of %1$@ is incompatible with forwarding server %2$@ settings. Het bestemmingsserveradres van %@ is niet compatibel met de doorstuurserverinstellingen %@. No comment provided by engineer. @@ -3067,7 +3074,7 @@ alert button snd error text - Destination server version of %@ is incompatible with forwarding server %@. + Destination server version of %1$@ is incompatible with forwarding server %2$@. De versie van de bestemmingsserver %@ is niet compatibel met de doorstuurserver %@. No comment provided by engineer. @@ -3611,7 +3618,7 @@ chat item action Error Fout - conn error description + No comment provided by engineer. Error aborting address change @@ -3904,6 +3911,10 @@ chat item action Fout bij opslaan van groep profiel No comment provided by engineer. + + Error saving name + alert title + Error saving passcode Fout bij opslaan van toegangscode @@ -4036,6 +4047,7 @@ chat item action Error: %@ Fout: %@ alert message +conn error description file error text snd error text @@ -5237,6 +5249,14 @@ Dit is jouw link voor groep %@! Less traffic on mobile networks. No comment provided by engineer. + + Let people connect to you via name registered with your SimpleX address. + No comment provided by engineer. + + + Let people join via name registered with this channel link. + No comment provided by engineer. + Let someone connect to you No comment provided by engineer. @@ -5410,21 +5430,6 @@ Dit is jouw link voor groep %@! Ledenrapporten chat feature - - Member role will be changed to "%@". All chat members will be notified. - De rol van het lid wordt gewijzigd naar "%@". Alle chatleden worden op de hoogte gebracht. - No comment provided by engineer. - - - Member role will be changed to "%@". All group members will be notified. - De rol van lid wordt gewijzigd in "%@". Alle groepsleden worden op de hoogte gebracht. - No comment provided by engineer. - - - Member role will be changed to "%@". The member will receive a new invitation. - De rol van lid wordt gewijzigd in "%@". Het lid ontvangt een nieuwe uitnodiging. - No comment provided by engineer. - Member will be removed from chat - this cannot be undone! Lid wordt verwijderd uit de chat - dit kan niet ongedaan worden gemaakt! @@ -5777,6 +5782,10 @@ Dit is jouw link voor groep %@! Naam swipe action + + Name not found + No comment provided by engineer. + Network & servers Netwerk & servers @@ -6096,6 +6105,10 @@ The most secure encryption. Geen servers om berichten te ontvangen. servers error + + No servers to resolve names. + servers warning + No servers to send files. Geen servers om bestanden te verzenden. @@ -6111,6 +6124,10 @@ The most secure encryption. Geen ongelezen chats No comment provided by engineer. + + No valid link + No comment provided by engineer. + Nobody tracked your conversations. No one drew a map of where you'd been. Privacy was never a feature - it was the way of life. No comment provided by engineer. @@ -6119,6 +6136,10 @@ The most secure encryption. Non-profit governance No comment provided by engineer. + + None of your servers are set to resolve SimpleX names. Configure servers, or use a connection link. + No comment provided by engineer. + Not a better lock on someone else's door. Not a nicer landlord that respects your privacy, but still keeps the record of all visitors. You are not a guest. You are home. No king can enter it - you are sovereign. No comment provided by engineer. @@ -6512,8 +6533,8 @@ alert button Owner No comment provided by engineer. - - Owners + + Owners & contributors No comment provided by engineer. @@ -6703,10 +6724,6 @@ Fout: %@ Probeer meldingen uit en weer in te schakelen. token info - - Please upgrade the app. - alert message - Please wait for group moderators to review your request to join the group. Wacht totdat de moderators van de groep uw verzoek tot lidmaatschap van de groep hebben beoordeeld. @@ -7406,6 +7423,10 @@ swipe action Terugzetten naar gebruikersthema No comment provided by engineer. + + Resolver error: %@ + No comment provided by engineer. + Restart the app to create a new chat profile Start de app opnieuw om een nieuw chatprofiel aan te maken @@ -7485,6 +7506,22 @@ swipe action Rol No comment provided by engineer. + + Role will be changed to "%@". All chat members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All group members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All subscribers will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". The member will receive a new invitation. + No comment provided by engineer. + Run chat Chat uitvoeren @@ -8009,6 +8046,10 @@ chat item action Server No comment provided by engineer. + + Server %@ does not support name resolution. Configure servers, or use a connection link. + No comment provided by engineer. + Server added to operator %@. Server toegevoegd aan operator %@. @@ -8431,6 +8472,18 @@ chat item action SimpleX-links zijn niet toegestaan No comment provided by engineer. + + SimpleX name + No comment provided by engineer. + + + SimpleX name error + No comment provided by engineer. + + + SimpleX name not verified + alert title + SimpleX one-time invitation Eenmalige SimpleX uitnodiging @@ -8882,6 +8935,22 @@ It can happen because of some bug or when the connection is compromised. No comment provided by engineer. + + The SimpleX name #%@ is registered without channel link. Add channel link to the name via the registration page. + alert message + + + The SimpleX name %@ is registered, but it has no valid link. + No comment provided by engineer. + + + The SimpleX name %@ is registered, but not added to profile. Please add it to your address or channel profile, if you are the owner. + No comment provided by engineer. + + + The SimpleX name @%@ is registered without SimpleX address. Add your SimpleX address to the name via the registration page. + alert message + The address will be short, and your profile will be shared via the address. alert message @@ -9059,6 +9128,10 @@ your contacts and groups. Ze kunnen worden overschreven in contactinstellingen No comment provided by engineer. + + This SimpleX name is not registered. Please check the name. + No comment provided by engineer. + This action cannot be undone - all received and sent files and media will be deleted. Low resolution pictures will remain. Deze actie kan niet ongedaan worden gemaakt, alle ontvangen en verzonden bestanden en media worden verwijderd. Foto's met een lage resolutie blijven behouden. @@ -9234,6 +9307,10 @@ U wordt gevraagd de authenticatie te voltooien voordat deze functie wordt ingesc Geef toestemming om de microfoon te gebruiken om een spraakbericht op te nemen. No comment provided by engineer. + + To resolve names + No comment provided by engineer. + To reveal your hidden profile, enter a full password into a search field in **Your chat profiles** page. Om uw verborgen profiel te onthullen, voert u een volledig wachtwoord in een zoek veld in op de pagina **Uw chatprofielen**. @@ -9354,6 +9431,10 @@ U wordt gevraagd de authenticatie te voltooien voordat deze functie wordt ingesc Unblock subscriber for all? No comment provided by engineer. + + Unconfirmed name + No comment provided by engineer. + Undelivered messages Niet afgeleverde berichten @@ -9451,19 +9532,11 @@ Om verbinding te maken, vraagt u uw contact om een andere verbinding link te mak Ongelezen swipe action - - Unsupported channel name - alert title - Unsupported connection link Niet-ondersteunde verbindingslink conn error description - - Unsupported contact name - alert title - Unverified badge badge alert title @@ -9710,6 +9783,10 @@ Om verbinding te maken, vraagt u uw contact om een andere verbinding link te mak Verify relay test step + + Verify SimpleX names + No comment provided by engineer. + Verify code with desktop Code verifiëren met desktop @@ -9735,6 +9812,10 @@ Om verbinding te maken, vraagt u uw contact om een andere verbinding link te mak Controleer het wachtwoord van de database No comment provided by engineer. + + Verify name + No comment provided by engineer. + Verify passphrase Controleer het wachtwoord @@ -10367,6 +10448,10 @@ Verbindingsverzoek herhalen? Uw SimpleX adres No comment provided by engineer. + + Your SimpleX name + No comment provided by engineer. + Your business contact No comment provided by engineer. @@ -10836,6 +10921,10 @@ marked deleted chat item preview text contact should accept… No comment provided by engineer. + + contributor + member role + creator creator @@ -11475,6 +11564,10 @@ laatst ontvangen bericht: %2$@ staking No comment provided by engineer. + + subscriber + member role + this contact dit contact diff --git a/apps/ios/SimpleX Localizations/pl.xcloc/Localized Contents/pl.xliff b/apps/ios/SimpleX Localizations/pl.xcloc/Localized Contents/pl.xliff index 17c56468d0..879c32f9f7 100644 --- a/apps/ios/SimpleX Localizations/pl.xcloc/Localized Contents/pl.xliff +++ b/apps/ios/SimpleX Localizations/pl.xcloc/Localized Contents/pl.xliff @@ -197,6 +197,18 @@ %d miesięcy time interval + + %d owner + channel owners count + + + %d owners + channel owners count + + + %d owners & contributors + channel members count + %d relays failed channel relay bar @@ -1688,11 +1700,6 @@ new chat action Zmień tryb blokady authentication reason - - Change member role? - Zmienić rolę członka? - No comment provided by engineer. - Change passcode Zmień pin @@ -1713,6 +1720,10 @@ new chat action Zmień rolę No comment provided by engineer. + + Change role? + No comment provided by engineer. + Change self-destruct mode Zmień tryb samozniszczenia @@ -2278,14 +2289,6 @@ To jest twój jednorazowy link! Łączenie z komputerem No comment provided by engineer. - - Connecting via channel name requires a newer app version. - alert message - - - Connecting via contact name requires a newer app version. - alert message - Connection Połączenie @@ -2301,6 +2304,10 @@ To jest twój jednorazowy link! Połączenie zablokowane No comment provided by engineer. + + Connection blocked: %@ + conn error description + Connection error Błąd połączenia @@ -3080,7 +3087,7 @@ alert button No comment provided by engineer. - Destination server address of %@ is incompatible with forwarding server %@ settings. + Destination server address of %1$@ is incompatible with forwarding server %2$@ settings. Adres serwera docelowego %@ jest niekompatybilny z ustawieniami serwera przekazującego %@. No comment provided by engineer. @@ -3090,7 +3097,7 @@ alert button snd error text - Destination server version of %@ is incompatible with forwarding server %@. + Destination server version of %1$@ is incompatible with forwarding server %2$@. Wersja serwera docelowego %@ jest niekompatybilna z serwerem przekierowującym %@. No comment provided by engineer. @@ -3636,7 +3643,7 @@ chat item action Error Błąd - conn error description + No comment provided by engineer. Error aborting address change @@ -3933,6 +3940,10 @@ chat item action Błąd zapisu profilu grupy No comment provided by engineer. + + Error saving name + alert title + Error saving passcode Błąd zapisu pinu @@ -4066,6 +4077,7 @@ chat item action Error: %@ Błąd: %@ alert message +conn error description file error text snd error text @@ -5279,6 +5291,14 @@ To jest twój link do grupy %@! Mniejszy ruch w sieciach komórkowych. No comment provided by engineer. + + Let people connect to you via name registered with your SimpleX address. + No comment provided by engineer. + + + Let people join via name registered with this channel link. + No comment provided by engineer. + Let someone connect to you No comment provided by engineer. @@ -5457,21 +5477,6 @@ To jest twój link do grupy %@! Raporty członków chat feature - - Member role will be changed to "%@". All chat members will be notified. - Rola członka zostanie zmieniona na "%@". Wszyscy członkowie czatu zostaną o tym poinformowani. - No comment provided by engineer. - - - Member role will be changed to "%@". All group members will be notified. - Rola członka grupy zostanie zmieniona na "%@". Wszyscy członkowie grupy zostaną powiadomieni. - No comment provided by engineer. - - - Member role will be changed to "%@". The member will receive a new invitation. - Rola członka zostanie zmieniona na "%@". Członek otrzyma nowe zaproszenie. - No comment provided by engineer. - Member will be removed from chat - this cannot be undone! Członek zostanie usunięty z czatu – nie można tego cofnąć! @@ -5826,6 +5831,10 @@ To jest twój link do grupy %@! Nazwa swipe action + + Name not found + No comment provided by engineer. + Network & servers Sieć i serwery @@ -6147,6 +6156,10 @@ The most secure encryption. Brak serwerów aby otrzymać wiadomości. servers error + + No servers to resolve names. + servers warning + No servers to send files. Brak serwerów do wysyłania plików. @@ -6162,6 +6175,10 @@ The most secure encryption. Brak nieprzeczytanych czatów No comment provided by engineer. + + No valid link + No comment provided by engineer. + Nobody tracked your conversations. No one drew a map of where you'd been. Privacy was never a feature - it was the way of life. Nikt nie śledził twoich rozmów. Nikt nie rysował mapy miejsc, w których byłeś. Prywatność nigdy nie była funkcją - była sposobem na życie. @@ -6171,6 +6188,10 @@ The most secure encryption. Non-profit governance No comment provided by engineer. + + None of your servers are set to resolve SimpleX names. Configure servers, or use a connection link. + No comment provided by engineer. + Not a better lock on someone else's door. Not a nicer landlord that respects your privacy, but still keeps the record of all visitors. You are not a guest. You are home. No king can enter it - you are sovereign. Nie chodzi o lepszy zamek w drzwiach kogoś innego. Nie chodzi o milszego właściciela, który szanuje twoją prywatność, ale nadal prowadzi rejestr wszystkich odwiedzających. Nie jesteś gościem. Jesteś w domu. Żaden król nie może do niego wejść - jesteś suwerenem. @@ -6575,8 +6596,8 @@ alert button Owner No comment provided by engineer. - - Owners + + Owners & contributors No comment provided by engineer. @@ -6766,10 +6787,6 @@ Błąd: %@ Spróbuj wyłączyć, a następnie ponownie włączyć powiadomienia. token info - - Please upgrade the app. - alert message - Please wait for group moderators to review your request to join the group. Poczekaj, aż moderatorzy grupy rozpatrzą Twoją prośbę o dołączenie do grupy. @@ -7474,6 +7491,10 @@ swipe action Zresetuj do motywu użytkownika No comment provided by engineer. + + Resolver error: %@ + No comment provided by engineer. + Restart the app to create a new chat profile Uruchom ponownie aplikację, aby utworzyć nowy profil czatu @@ -7554,6 +7575,22 @@ swipe action Rola No comment provided by engineer. + + Role will be changed to "%@". All chat members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All group members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All subscribers will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". The member will receive a new invitation. + No comment provided by engineer. + Run chat Uruchom czat @@ -8089,6 +8126,10 @@ chat item action Serwer No comment provided by engineer. + + Server %@ does not support name resolution. Configure servers, or use a connection link. + No comment provided by engineer. + Server added to operator %@. Serwer został dodany do operatora %@. @@ -8517,6 +8558,18 @@ chat item action Linki SimpleX są niedozwolone No comment provided by engineer. + + SimpleX name + No comment provided by engineer. + + + SimpleX name error + No comment provided by engineer. + + + SimpleX name not verified + alert title + SimpleX one-time invitation Zaproszenie jednorazowe SimpleX @@ -8973,6 +9026,22 @@ It can happen because of some bug or when the connection is compromised. No comment provided by engineer. + + The SimpleX name #%@ is registered without channel link. Add channel link to the name via the registration page. + alert message + + + The SimpleX name %@ is registered, but it has no valid link. + No comment provided by engineer. + + + The SimpleX name %@ is registered, but not added to profile. Please add it to your address or channel profile, if you are the owner. + No comment provided by engineer. + + + The SimpleX name @%@ is registered without SimpleX address. Add your SimpleX address to the name via the registration page. + alert message + The address will be short, and your profile will be shared via the address. Adres będzie krótki, a Twój profil zostanie udostępniony za pośrednictwem adresu. @@ -9155,6 +9224,10 @@ your contacts and groups. Można je nadpisać w ustawieniach kontaktu. No comment provided by engineer. + + This SimpleX name is not registered. Please check the name. + No comment provided by engineer. + This action cannot be undone - all received and sent files and media will be deleted. Low resolution pictures will remain. Tego działania nie można cofnąć - wszystkie odebrane i wysłane pliki oraz media zostaną usunięte. Obrazy o niskiej rozdzielczości pozostaną. @@ -9332,6 +9405,10 @@ Przed włączeniem tej funkcji zostanie wyświetlony monit uwierzytelniania.Aby nagrać wiadomość głosową należy udzielić zgody na użycie Mikrofonu. No comment provided by engineer. + + To resolve names + No comment provided by engineer. + To reveal your hidden profile, enter a full password into a search field in **Your chat profiles** page. Aby ujawnić Twój ukryty profil, wprowadź pełne hasło w pole wyszukiwania na stronie **Twoich profili czatu**. @@ -9455,6 +9532,10 @@ Przed włączeniem tej funkcji zostanie wyświetlony monit uwierzytelniania.Unblock subscriber for all? No comment provided by engineer. + + Unconfirmed name + No comment provided by engineer. + Undelivered messages Niedostarczone wiadomości @@ -9552,19 +9633,11 @@ Aby się połączyć, poproś Twój kontakt o utworzenie kolejnego linku połąc Nieprzeczytane swipe action - - Unsupported channel name - alert title - Unsupported connection link Nieobsługiwane łącze połączenia conn error description - - Unsupported contact name - alert title - Unverified badge badge alert title @@ -9818,6 +9891,10 @@ Aby się połączyć, poproś Twój kontakt o utworzenie kolejnego linku połąc Verify relay test step + + Verify SimpleX names + No comment provided by engineer. + Verify code with desktop Zweryfikuj kod z komputera @@ -9843,6 +9920,10 @@ Aby się połączyć, poproś Twój kontakt o utworzenie kolejnego linku połąc Zweryfikuj hasło bazy danych No comment provided by engineer. + + Verify name + No comment provided by engineer. + Verify passphrase Zweryfikuj hasło @@ -10481,6 +10562,10 @@ Powtórzyć prośbę połączenia? Twój adres SimpleX No comment provided by engineer. + + Your SimpleX name + No comment provided by engineer. + Your business contact Twój kontakt biznesowy @@ -10956,6 +11041,10 @@ marked deleted chat item preview text kontakt powinien zaakceptować… No comment provided by engineer. + + contributor + member role + creator twórca @@ -11601,6 +11690,10 @@ ostatnia otrzymana wiadomość: %2$@ strajk No comment provided by engineer. + + subscriber + member role + this contact ten kontakt diff --git a/apps/ios/SimpleX Localizations/ru.xcloc/Localized Contents/ru.xliff b/apps/ios/SimpleX Localizations/ru.xcloc/Localized Contents/ru.xliff index 4574aa5ec1..70872257a6 100644 --- a/apps/ios/SimpleX Localizations/ru.xcloc/Localized Contents/ru.xliff +++ b/apps/ios/SimpleX Localizations/ru.xcloc/Localized Contents/ru.xliff @@ -197,6 +197,18 @@ %d мес time interval + + %d owner + channel owners count + + + %d owners + channel owners count + + + %d owners & contributors + channel members count + %d relays failed %d релеев с ошибками @@ -1720,11 +1732,6 @@ new chat action Изменить режим блокировки authentication reason - - Change member role? - Поменять роль члена группы? - No comment provided by engineer. - Change passcode Изменить код доступа @@ -1745,6 +1752,10 @@ new chat action Поменять роль No comment provided by engineer. + + Change role? + No comment provided by engineer. + Change self-destruct mode Изменить режим самоуничтожения @@ -2335,14 +2346,6 @@ This is your own one-time link! Подключение к компьютеру No comment provided by engineer. - - Connecting via channel name requires a newer app version. - alert message - - - Connecting via contact name requires a newer app version. - alert message - Connection Соединение @@ -2358,6 +2361,10 @@ This is your own one-time link! Соединение заблокировано No comment provided by engineer. + + Connection blocked: %@ + conn error description + Connection error Ошибка соединения @@ -3147,7 +3154,7 @@ alert button No comment provided by engineer. - Destination server address of %@ is incompatible with forwarding server %@ settings. + Destination server address of %1$@ is incompatible with forwarding server %2$@ settings. Адрес сервера назначения %@ несовместим с настройками пересылающего сервера %@. No comment provided by engineer. @@ -3157,7 +3164,7 @@ alert button snd error text - Destination server version of %@ is incompatible with forwarding server %@. + Destination server version of %1$@ is incompatible with forwarding server %2$@. Версия сервера назначения %@ несовместима с пересылающим сервером %@. No comment provided by engineer. @@ -3714,7 +3721,7 @@ chat item action Error Ошибка - conn error description + No comment provided by engineer. Error aborting address change @@ -4014,6 +4021,10 @@ chat item action Ошибка при сохранении профиля группы No comment provided by engineer. + + Error saving name + alert title + Error saving passcode Ошибка сохранения кода @@ -4148,6 +4159,7 @@ chat item action Error: %@ Ошибка: %@ alert message +conn error description file error text snd error text @@ -5370,6 +5382,14 @@ This is your link for group %@! Меньше трафик в мобильных сетях. No comment provided by engineer. + + Let people connect to you via name registered with your SimpleX address. + No comment provided by engineer. + + + Let people join via name registered with this channel link. + No comment provided by engineer. + Let someone connect to you Дайте собеседнику Вашу ссылку @@ -5550,21 +5570,6 @@ This is your link for group %@! Сообщения о нарушениях chat feature - - Member role will be changed to "%@". All chat members will be notified. - Роль участника будет изменена на "%@". Все участники разговора получат уведомление. - No comment provided by engineer. - - - Member role will be changed to "%@". All group members will be notified. - Роль члена будет изменена на "%@". Все члены группы получат уведомление. - No comment provided by engineer. - - - Member role will be changed to "%@". The member will receive a new invitation. - Роль члена будет изменена на "%@". Будет отправлено новое приглашение. - No comment provided by engineer. - Member will be removed from chat - this cannot be undone! Член будет удалён из разговора - это действие нельзя отменить! @@ -5924,6 +5929,10 @@ This is your link for group %@! Имя swipe action + + Name not found + No comment provided by engineer. + Network & servers Сеть и серверы @@ -6256,6 +6265,10 @@ The most secure encryption. Нет серверов для приёма сообщений. servers error + + No servers to resolve names. + servers warning + No servers to send files. Нет серверов для отправки файлов. @@ -6271,6 +6284,10 @@ The most secure encryption. Нет непрочитанных чатов No comment provided by engineer. + + No valid link + No comment provided by engineer. + Nobody tracked your conversations. No one drew a map of where you'd been. Privacy was never a feature - it was the way of life. Никто не отслеживал ваши разговоры. Никто не составлял карту ваших перемещений. Конфиденциальность не была функцией - это был образ жизни. @@ -6281,6 +6298,10 @@ The most secure encryption. Некоммерческое управление No comment provided by engineer. + + None of your servers are set to resolve SimpleX names. Configure servers, or use a connection link. + No comment provided by engineer. + Not a better lock on someone else's door. Not a nicer landlord that respects your privacy, but still keeps the record of all visitors. You are not a guest. You are home. No king can enter it - you are sovereign. Не более надёжный замок на чужой двери. Не более вежливый хозяин, который уважает вашу частную жизнь, но всё равно ведёт учёт всех посетителей. Вы не гость. Вы у себя дома. Ни один король не войдёт в ваш дом - вы суверенны. @@ -6699,9 +6720,8 @@ alert button Владелец No comment provided by engineer. - - Owners - Владельцы + + Owners & contributors No comment provided by engineer. @@ -6893,10 +6913,6 @@ Error: %@ Попробуйте выключить и снова включить уведомления. token info - - Please upgrade the app. - alert message - Please wait for group moderators to review your request to join the group. Пожалуйста, подождите, пока модераторы группы рассмотрят ваш запрос на вступление. @@ -7617,6 +7633,10 @@ swipe action Сбросить на тему пользователя No comment provided by engineer. + + Resolver error: %@ + No comment provided by engineer. + Restart the app to create a new chat profile Перезапустите приложение, чтобы создать новый профиль @@ -7697,6 +7717,22 @@ swipe action Роль No comment provided by engineer. + + Role will be changed to "%@". All chat members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All group members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All subscribers will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". The member will receive a new invitation. + No comment provided by engineer. + Run chat Запустить chat @@ -8241,6 +8277,10 @@ chat item action Сервер No comment provided by engineer. + + Server %@ does not support name resolution. Configure servers, or use a connection link. + No comment provided by engineer. + Server added to operator %@. Сервер добавлен к оператору %@. @@ -8677,6 +8717,18 @@ chat item action Ссылки SimpleX не разрешены No comment provided by engineer. + + SimpleX name + No comment provided by engineer. + + + SimpleX name error + No comment provided by engineer. + + + SimpleX name not verified + alert title + SimpleX one-time invitation SimpleX одноразовая ссылка @@ -9153,6 +9205,22 @@ It can happen because of some bug or when the connection is compromised. No comment provided by engineer. + + The SimpleX name #%@ is registered without channel link. Add channel link to the name via the registration page. + alert message + + + The SimpleX name %@ is registered, but it has no valid link. + No comment provided by engineer. + + + The SimpleX name %@ is registered, but not added to profile. Please add it to your address or channel profile, if you are the owner. + No comment provided by engineer. + + + The SimpleX name @%@ is registered without SimpleX address. Add your SimpleX address to the name via the registration page. + alert message + The address will be short, and your profile will be shared via the address. Адрес будет коротким, и Ваш профиль будет добавлен в адрес. @@ -9339,6 +9407,10 @@ your contacts and groups. Они могут быть изменены в настройках контактов и групп. No comment provided by engineer. + + This SimpleX name is not registered. Please check the name. + No comment provided by engineer. + This action cannot be undone - all received and sent files and media will be deleted. Low resolution pictures will remain. Это действие нельзя отменить - все полученные и отправленные файлы будут удалены. Изображения останутся в низком разрешении. @@ -9519,6 +9591,10 @@ You will be prompted to complete authentication before this feature is enabled.< Для записи голосового сообщения, пожалуйста разрешите доступ к микрофону. No comment provided by engineer. + + To resolve names + No comment provided by engineer. + To reveal your hidden profile, enter a full password into a search field in **Your chat profiles** page. Чтобы показать Ваш скрытый профиль, введите его пароль в поле поиска на странице **Ваши профили чата**. @@ -9644,6 +9720,10 @@ You will be prompted to complete authentication before this feature is enabled.< Разблокировать подписчика для всех? No comment provided by engineer. + + Unconfirmed name + No comment provided by engineer. + Undelivered messages Недоставленные сообщения @@ -9741,19 +9821,11 @@ To connect, please ask your contact to create another connection link and check Не прочитано swipe action - - Unsupported channel name - alert title - Unsupported connection link Ссылка не поддерживается conn error description - - Unsupported contact name - alert title - Unverified badge badge alert title @@ -10012,6 +10084,10 @@ To connect, please ask your contact to create another connection link and check Проверить relay test step + + Verify SimpleX names + No comment provided by engineer. + Verify code with desktop Сверьте код с компьютером @@ -10037,6 +10113,10 @@ To connect, please ask your contact to create another connection link and check Проверка пароля базы данных No comment provided by engineer. + + Verify name + No comment provided by engineer. + Verify passphrase Проверить пароль @@ -10686,6 +10766,10 @@ Repeat connection request? Ваш адрес SimpleX No comment provided by engineer. + + Your SimpleX name + No comment provided by engineer. + Your business contact Ваш бизнес-контакт @@ -11173,6 +11257,10 @@ marked deleted chat item preview text контакт должен принять… No comment provided by engineer. + + contributor + member role + creator создатель @@ -11825,6 +11913,10 @@ last received msg: %2$@ зачеркнуть No comment provided by engineer. + + subscriber + member role + this contact этот контакт diff --git a/apps/ios/SimpleX Localizations/th.xcloc/Localized Contents/th.xliff b/apps/ios/SimpleX Localizations/th.xcloc/Localized Contents/th.xliff index c6a57fb777..311a52159b 100644 --- a/apps/ios/SimpleX Localizations/th.xcloc/Localized Contents/th.xliff +++ b/apps/ios/SimpleX Localizations/th.xcloc/Localized Contents/th.xliff @@ -179,6 +179,18 @@ %d เดือน time interval + + %d owner + channel owners count + + + %d owners + channel owners count + + + %d owners & contributors + channel members count + %d relays failed channel relay bar @@ -1534,11 +1546,6 @@ new chat action เปลี่ยนโหมดล็อค authentication reason - - Change member role? - เปลี่ยนบทบาทของสมาชิก? - No comment provided by engineer. - Change passcode เปลี่ยนรหัสผ่าน @@ -1559,6 +1566,10 @@ new chat action เปลี่ยนบทบาท No comment provided by engineer. + + Change role? + No comment provided by engineer. + Change self-destruct mode เปลี่ยนโหมดทําลายตัวเอง @@ -2064,14 +2075,6 @@ This is your own one-time link! Connecting to desktop No comment provided by engineer. - - Connecting via channel name requires a newer app version. - alert message - - - Connecting via contact name requires a newer app version. - alert message - Connection การเชื่อมต่อ @@ -2085,6 +2088,10 @@ This is your own one-time link! Connection blocked No comment provided by engineer. + + Connection blocked: %@ + conn error description + Connection error การเชื่อมต่อผิดพลาด @@ -2802,7 +2809,7 @@ alert button No comment provided by engineer. - Destination server address of %@ is incompatible with forwarding server %@ settings. + Destination server address of %1$@ is incompatible with forwarding server %2$@ settings. No comment provided by engineer. @@ -2810,7 +2817,7 @@ alert button snd error text - Destination server version of %@ is incompatible with forwarding server %@. + Destination server version of %1$@ is incompatible with forwarding server %2$@. No comment provided by engineer. @@ -3312,7 +3319,7 @@ chat item action Error ผิดพลาด - conn error description + No comment provided by engineer. Error aborting address change @@ -3581,6 +3588,10 @@ chat item action เกิดข้อผิดพลาดในการบันทึกโปรไฟล์กลุ่ม No comment provided by engineer. + + Error saving name + alert title + Error saving passcode เกิดข้อผิดพลาดในการบันทึกรหัสผ่าน @@ -3704,6 +3715,7 @@ chat item action Error: %@ ข้อผิดพลาด: % @ alert message +conn error description file error text snd error text @@ -4808,6 +4820,14 @@ This is your link for group %@! Less traffic on mobile networks. No comment provided by engineer. + + Let people connect to you via name registered with your SimpleX address. + No comment provided by engineer. + + + Let people join via name registered with this channel link. + No comment provided by engineer. + Let someone connect to you No comment provided by engineer. @@ -4970,20 +4990,6 @@ This is your link for group %@! Member reports chat feature - - Member role will be changed to "%@". All chat members will be notified. - No comment provided by engineer. - - - Member role will be changed to "%@". All group members will be notified. - บทบาทของสมาชิกจะถูกเปลี่ยนเป็น "%@" สมาชิกกลุ่มทั้งหมดจะได้รับแจ้ง - No comment provided by engineer. - - - Member role will be changed to "%@". The member will receive a new invitation. - บทบาทของสมาชิกจะถูกเปลี่ยนเป็น "%@" สมาชิกจะได้รับคำเชิญใหม่ - No comment provided by engineer. - Member will be removed from chat - this cannot be undone! alert message @@ -5301,6 +5307,10 @@ This is your link for group %@! ชื่อ swipe action + + Name not found + No comment provided by engineer. + Network & servers เครือข่ายและเซิร์ฟเวอร์ @@ -5589,6 +5599,10 @@ The most secure encryption. No servers to receive messages. servers error + + No servers to resolve names. + servers warning + No servers to send files. servers error @@ -5601,6 +5615,10 @@ The most secure encryption. No unread chats No comment provided by engineer. + + No valid link + No comment provided by engineer. + Nobody tracked your conversations. No one drew a map of where you'd been. Privacy was never a feature - it was the way of life. No comment provided by engineer. @@ -5609,6 +5627,10 @@ The most secure encryption. Non-profit governance No comment provided by engineer. + + None of your servers are set to resolve SimpleX names. Configure servers, or use a connection link. + No comment provided by engineer. + Not a better lock on someone else's door. Not a nicer landlord that respects your privacy, but still keeps the record of all visitors. You are not a guest. You are home. No king can enter it - you are sovereign. No comment provided by engineer. @@ -5969,8 +5991,8 @@ alert button Owner No comment provided by engineer. - - Owners + + Owners & contributors No comment provided by engineer. @@ -6146,10 +6168,6 @@ Error: %@ Please try to disable and re-enable notfications. token info - - Please upgrade the app. - alert message - Please wait for group moderators to review your request to join the group. snd group event chat item @@ -6784,6 +6802,10 @@ swipe action Reset to user theme No comment provided by engineer. + + Resolver error: %@ + No comment provided by engineer. + Restart the app to create a new chat profile รีสตาร์ทแอปเพื่อสร้างโปรไฟล์แชทใหม่ @@ -6859,6 +6881,22 @@ swipe action บทบาท No comment provided by engineer. + + Role will be changed to "%@". All chat members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All group members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All subscribers will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". The member will receive a new invitation. + No comment provided by engineer. + Run chat เรียกใช้แชท @@ -7346,6 +7384,10 @@ chat item action Server No comment provided by engineer. + + Server %@ does not support name resolution. Configure servers, or use a connection link. + No comment provided by engineer. + Server added to operator %@. alert message @@ -7727,6 +7769,18 @@ chat item action SimpleX links not allowed No comment provided by engineer. + + SimpleX name + No comment provided by engineer. + + + SimpleX name error + No comment provided by engineer. + + + SimpleX name not verified + alert title + SimpleX one-time invitation คำเชิญ SimpleX แบบครั้งเดียว @@ -8147,6 +8201,22 @@ It can happen because of some bug or when the connection is compromised. No comment provided by engineer. + + The SimpleX name #%@ is registered without channel link. Add channel link to the name via the registration page. + alert message + + + The SimpleX name %@ is registered, but it has no valid link. + No comment provided by engineer. + + + The SimpleX name %@ is registered, but not added to profile. Please add it to your address or channel profile, if you are the owner. + No comment provided by engineer. + + + The SimpleX name @%@ is registered without SimpleX address. Add your SimpleX address to the name via the registration page. + alert message + The address will be short, and your profile will be shared via the address. alert message @@ -8310,6 +8380,10 @@ your contacts and groups. They can be overridden in contact and group settings. No comment provided by engineer. + + This SimpleX name is not registered. Please check the name. + No comment provided by engineer. + This action cannot be undone - all received and sent files and media will be deleted. Low resolution pictures will remain. การดำเนินการนี้ไม่สามารถยกเลิกได้ ไฟล์และสื่อที่ได้รับและส่งทั้งหมดจะถูกลบ รูปภาพความละเอียดต่ำจะยังคงอยู่ @@ -8469,6 +8543,10 @@ You will be prompted to complete authentication before this feature is enabled.< ในการบันทึกข้อความเสียง โปรดให้สิทธิ์ในการใช้ไมโครโฟน No comment provided by engineer. + + To resolve names + No comment provided by engineer. + To reveal your hidden profile, enter a full password into a search field in **Your chat profiles** page. หากต้องการเปิดเผยโปรไฟล์ที่ซ่อนอยู่ของคุณ ให้ป้อนรหัสผ่านแบบเต็มในช่องค้นหาในหน้า **โปรไฟล์แชทของคุณ** @@ -8576,6 +8654,10 @@ You will be prompted to complete authentication before this feature is enabled.< Unblock subscriber for all? No comment provided by engineer. + + Unconfirmed name + No comment provided by engineer. + Undelivered messages No comment provided by engineer. @@ -8669,18 +8751,10 @@ To connect, please ask your contact to create another connection link and check เปลี่ยนเป็นยังไม่ได้อ่าน swipe action - - Unsupported channel name - alert title - Unsupported connection link conn error description - - Unsupported contact name - alert title - Unverified badge badge alert title @@ -8901,6 +8975,10 @@ To connect, please ask your contact to create another connection link and check Verify relay test step + + Verify SimpleX names + No comment provided by engineer. + Verify code with desktop No comment provided by engineer. @@ -8922,6 +9000,10 @@ To connect, please ask your contact to create another connection link and check Verify database passphrase No comment provided by engineer. + + Verify name + No comment provided by engineer. + Verify passphrase No comment provided by engineer. @@ -9503,6 +9585,10 @@ Repeat connection request? ที่อยู่ SimpleX ของคุณ No comment provided by engineer. + + Your SimpleX name + No comment provided by engineer. + Your business contact No comment provided by engineer. @@ -9946,6 +10032,10 @@ marked deleted chat item preview text contact should accept… No comment provided by engineer. + + contributor + member role + creator ผู้สร้าง @@ -10547,6 +10637,10 @@ last received msg: %2$@ ตี No comment provided by engineer. + + subscriber + member role + this contact ผู้ติดต่อนี้ diff --git a/apps/ios/SimpleX Localizations/tr.xcloc/Localized Contents/tr.xliff b/apps/ios/SimpleX Localizations/tr.xcloc/Localized Contents/tr.xliff index f92ebbde0e..27095ac5b2 100644 --- a/apps/ios/SimpleX Localizations/tr.xcloc/Localized Contents/tr.xliff +++ b/apps/ios/SimpleX Localizations/tr.xcloc/Localized Contents/tr.xliff @@ -197,6 +197,18 @@ %d ay time interval + + %d owner + channel owners count + + + %d owners + channel owners count + + + %d owners & contributors + channel members count + %d relays failed %d aktarıcı başarısız oldu @@ -1694,11 +1706,6 @@ new chat action Kilit modunu değiştir authentication reason - - Change member role? - Üye rolünü değiştir? - No comment provided by engineer. - Change passcode Şifreyi değiştir @@ -1719,6 +1726,10 @@ new chat action Rolü değiştir No comment provided by engineer. + + Change role? + No comment provided by engineer. + Change self-destruct mode Kendini yok etme modunu değiştir @@ -2284,14 +2295,6 @@ Bu senin kendi tek kullanımlık bağlantın! Bilgisayara bağlanıyor No comment provided by engineer. - - Connecting via channel name requires a newer app version. - alert message - - - Connecting via contact name requires a newer app version. - alert message - Connection Bağlantı @@ -2307,6 +2310,10 @@ Bu senin kendi tek kullanımlık bağlantın! Bağlantı engellendi No comment provided by engineer. + + Connection blocked: %@ + conn error description + Connection error Bağlantı hatası @@ -3083,7 +3090,7 @@ alert button No comment provided by engineer. - Destination server address of %@ is incompatible with forwarding server %@ settings. + Destination server address of %1$@ is incompatible with forwarding server %2$@ settings. Hedef sunucu adresi %@, yönlendirme sunucusu %@ ayarlarıyla uyumlu değil. No comment provided by engineer. @@ -3093,7 +3100,7 @@ alert button snd error text - Destination server version of %@ is incompatible with forwarding server %@. + Destination server version of %1$@ is incompatible with forwarding server %2$@. Hedef sunucu %@ sürümü, yönlendirme sunucusu %@ ile uyumlu değil. No comment provided by engineer. @@ -3639,7 +3646,7 @@ chat item action Error Hata - conn error description + No comment provided by engineer. Error aborting address change @@ -3935,6 +3942,10 @@ chat item action Grup profili kaydedilirken sorun oluştu No comment provided by engineer. + + Error saving name + alert title + Error saving passcode Parola kaydedilirken sorun oluştu @@ -4068,6 +4079,7 @@ chat item action Error: %@ Hata: %@ alert message +conn error description file error text snd error text @@ -5273,6 +5285,14 @@ Bu senin grup için bağlantın %@! Mobil ağlarda daha az trafik. No comment provided by engineer. + + Let people connect to you via name registered with your SimpleX address. + No comment provided by engineer. + + + Let people join via name registered with this channel link. + No comment provided by engineer. + Let someone connect to you No comment provided by engineer. @@ -5449,21 +5469,6 @@ Bu senin grup için bağlantın %@! Üye raporları chat feature - - Member role will be changed to "%@". All chat members will be notified. - Üye rolü "%@" olarak değiştirilecektir. Tüm sohbet üyeleri bilgilendirilecektir. - No comment provided by engineer. - - - Member role will be changed to "%@". All group members will be notified. - Üye rolü "%@" olarak değiştirilecektir. Ve tüm grup üyeleri bilgilendirilecektir. - No comment provided by engineer. - - - Member role will be changed to "%@". The member will receive a new invitation. - Üye rolü "%@" olarak değiştirilecektir. Ve üye yeni bir davetiye alacaktır. - No comment provided by engineer. - Member will be removed from chat - this cannot be undone! Üye sohbetten kaldırılacak - bu geri alınamaz! @@ -5818,6 +5823,10 @@ Bu senin grup için bağlantın %@! İsim swipe action + + Name not found + No comment provided by engineer. + Network & servers Ağ & sunucular @@ -6139,6 +6148,10 @@ The most secure encryption. Mesaj almak için hiç sunucu yok. servers error + + No servers to resolve names. + servers warning + No servers to send files. Dosya göndermek için hiç sunucu yok. @@ -6154,6 +6167,10 @@ The most secure encryption. Okunmamış sohbet yok No comment provided by engineer. + + No valid link + No comment provided by engineer. + Nobody tracked your conversations. No one drew a map of where you'd been. Privacy was never a feature - it was the way of life. No comment provided by engineer. @@ -6162,6 +6179,10 @@ The most secure encryption. Non-profit governance No comment provided by engineer. + + None of your servers are set to resolve SimpleX names. Configure servers, or use a connection link. + No comment provided by engineer. + Not a better lock on someone else's door. Not a nicer landlord that respects your privacy, but still keeps the record of all visitors. You are not a guest. You are home. No king can enter it - you are sovereign. No comment provided by engineer. @@ -6565,8 +6586,8 @@ alert button Owner No comment provided by engineer. - - Owners + + Owners & contributors No comment provided by engineer. @@ -6756,10 +6777,6 @@ Hata: %@ Lütfen bildirimleri devre dışı bırakmayı ve yeniden etkinleştirmeyi deneyin. token info - - Please upgrade the app. - alert message - Please wait for group moderators to review your request to join the group. Lütfen grup moderatörlerinin gruba katılma isteğinizi incelemesini bekleyin. @@ -7463,6 +7480,10 @@ swipe action Kullanıcı temasına sıfırla No comment provided by engineer. + + Resolver error: %@ + No comment provided by engineer. + Restart the app to create a new chat profile Yeni bir sohbet profili oluşturmak için uygulamayı yeniden başlatın @@ -7543,6 +7564,22 @@ swipe action Rol No comment provided by engineer. + + Role will be changed to "%@". All chat members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All group members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All subscribers will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". The member will receive a new invitation. + No comment provided by engineer. + Run chat Sohbeti çalıştır @@ -8073,6 +8110,10 @@ chat item action Sunucu No comment provided by engineer. + + Server %@ does not support name resolution. Configure servers, or use a connection link. + No comment provided by engineer. + Server added to operator %@. Sunucu operatör %@'ya eklendi. @@ -8501,6 +8542,18 @@ chat item action SimpleX bağlantılarına izin verilmiyor No comment provided by engineer. + + SimpleX name + No comment provided by engineer. + + + SimpleX name error + No comment provided by engineer. + + + SimpleX name not verified + alert title + SimpleX one-time invitation SimpleX tek kullanımlık davet @@ -8957,6 +9010,22 @@ It can happen because of some bug or when the connection is compromised. No comment provided by engineer. + + The SimpleX name #%@ is registered without channel link. Add channel link to the name via the registration page. + alert message + + + The SimpleX name %@ is registered, but it has no valid link. + No comment provided by engineer. + + + The SimpleX name %@ is registered, but not added to profile. Please add it to your address or channel profile, if you are the owner. + No comment provided by engineer. + + + The SimpleX name @%@ is registered without SimpleX address. Add your SimpleX address to the name via the registration page. + alert message + The address will be short, and your profile will be shared via the address. Adres kısa olacak ve profiliniz bu adres üzerinden paylaşılacaktır. @@ -9136,6 +9205,10 @@ your contacts and groups. Bunlar kişi ve grup ayarlarında geçersiz kılınabilir. No comment provided by engineer. + + This SimpleX name is not registered. Please check the name. + No comment provided by engineer. + This action cannot be undone - all received and sent files and media will be deleted. Low resolution pictures will remain. Bu işlem geri alınamaz - alınan ve gönderilen tüm dosyalar ve medya silinecektir. Düşük çözünürlüklü resimler kalacaktır. @@ -9313,6 +9386,10 @@ Bu özellik etkinleştirilmeden önce kimlik doğrulamayı tamamlamanız istenec Sesli mesaj kaydetmek için lütfen Mikrofon kullanım izni verin. No comment provided by engineer. + + To resolve names + No comment provided by engineer. + To reveal your hidden profile, enter a full password into a search field in **Your chat profiles** page. Gizli profilinizi ortaya çıkarmak için **Sohbet profilleriniz** sayfasındaki arama alanına tam bir şifre girin. @@ -9435,6 +9512,10 @@ Bu özellik etkinleştirilmeden önce kimlik doğrulamayı tamamlamanız istenec Unblock subscriber for all? No comment provided by engineer. + + Unconfirmed name + No comment provided by engineer. + Undelivered messages Teslim edilmemiş mesajlar @@ -9532,19 +9613,11 @@ Bağlanmak için lütfen kişinizden başka bir bağlantı oluşturmasını iste Okunmamış swipe action - - Unsupported channel name - alert title - Unsupported connection link Desteklenmeyen bağlantı bağlantısı conn error description - - Unsupported contact name - alert title - Unverified badge badge alert title @@ -9798,6 +9871,10 @@ Bağlanmak için lütfen kişinizden başka bir bağlantı oluşturmasını iste Verify relay test step + + Verify SimpleX names + No comment provided by engineer. + Verify code with desktop Bilgisayarla kodu doğrula @@ -9823,6 +9900,10 @@ Bağlanmak için lütfen kişinizden başka bir bağlantı oluşturmasını iste Veritabanı parolasını doğrulayın No comment provided by engineer. + + Verify name + No comment provided by engineer. + Verify passphrase Parolayı doğrula @@ -10457,6 +10538,10 @@ Bağlantı isteği tekrarlansın mı? SimpleX adresin No comment provided by engineer. + + Your SimpleX name + No comment provided by engineer. + Your business contact İş bağlantınız @@ -10931,6 +11016,10 @@ marked deleted chat item preview text kişi kabul etmeli… No comment provided by engineer. + + contributor + member role + creator oluşturan @@ -11574,6 +11663,10 @@ son alınan msj: %2$@ çizik No comment provided by engineer. + + subscriber + member role + this contact Bu kişi diff --git a/apps/ios/SimpleX Localizations/uk.xcloc/Localized Contents/uk.xliff b/apps/ios/SimpleX Localizations/uk.xcloc/Localized Contents/uk.xliff index a356858ecd..1da658611d 100644 --- a/apps/ios/SimpleX Localizations/uk.xcloc/Localized Contents/uk.xliff +++ b/apps/ios/SimpleX Localizations/uk.xcloc/Localized Contents/uk.xliff @@ -197,6 +197,18 @@ %d місяців time interval + + %d owner + channel owners count + + + %d owners + channel owners count + + + %d owners & contributors + channel members count + %d relays failed channel relay bar @@ -1680,11 +1692,6 @@ new chat action Зміна режиму блокування authentication reason - - Change member role? - Змінити роль учасника? - No comment provided by engineer. - Change passcode Змінити код доступу @@ -1705,6 +1712,10 @@ new chat action Змінити роль No comment provided by engineer. + + Change role? + No comment provided by engineer. + Change self-destruct mode Змінити режим самознищення @@ -2270,14 +2281,6 @@ This is your own one-time link! Підключення до ПК No comment provided by engineer. - - Connecting via channel name requires a newer app version. - alert message - - - Connecting via contact name requires a newer app version. - alert message - Connection Підключення @@ -2293,6 +2296,10 @@ This is your own one-time link! Підключення заблоковано No comment provided by engineer. + + Connection blocked: %@ + conn error description + Connection error Помилка підключення @@ -3067,7 +3074,7 @@ alert button No comment provided by engineer. - Destination server address of %@ is incompatible with forwarding server %@ settings. + Destination server address of %1$@ is incompatible with forwarding server %2$@ settings. Адреса сервера призначення %@ несумісна з налаштуваннями сервера пересилання %@. No comment provided by engineer. @@ -3077,7 +3084,7 @@ alert button snd error text - Destination server version of %@ is incompatible with forwarding server %@. + Destination server version of %1$@ is incompatible with forwarding server %2$@. Версія сервера призначення %@ несумісна з версією сервера переадресації %@. No comment provided by engineer. @@ -3623,7 +3630,7 @@ chat item action Error Помилка - conn error description + No comment provided by engineer. Error aborting address change @@ -3919,6 +3926,10 @@ chat item action Помилка збереження профілю групи No comment provided by engineer. + + Error saving name + alert title + Error saving passcode Помилка збереження пароля @@ -4051,6 +4062,7 @@ chat item action Error: %@ Помилка: %@ alert message +conn error description file error text snd error text @@ -5255,6 +5267,14 @@ This is your link for group %@! Менше трафіку в мобільних мережах. No comment provided by engineer. + + Let people connect to you via name registered with your SimpleX address. + No comment provided by engineer. + + + Let people join via name registered with this channel link. + No comment provided by engineer. + Let someone connect to you No comment provided by engineer. @@ -5429,21 +5449,6 @@ This is your link for group %@! Повідомлення учасників chat feature - - Member role will be changed to "%@". All chat members will be notified. - Роль учасника буде змінено на "%@". Усі учасники чату отримають сповіщення. - No comment provided by engineer. - - - Member role will be changed to "%@". All group members will be notified. - Роль учасника буде змінено на "%@". Всі учасники групи будуть повідомлені про це. - No comment provided by engineer. - - - Member role will be changed to "%@". The member will receive a new invitation. - Роль учасника буде змінено на "%@". Учасник отримає нове запрошення. - No comment provided by engineer. - Member will be removed from chat - this cannot be undone! Учасника буде видалено з чату – це неможливо скасувати! @@ -5798,6 +5803,10 @@ This is your link for group %@! Ім'я swipe action + + Name not found + No comment provided by engineer. + Network & servers Мережа та сервери @@ -6119,6 +6128,10 @@ The most secure encryption. Немає серверів для отримання повідомлень. servers error + + No servers to resolve names. + servers warning + No servers to send files. Немає серверів для надсилання файлів. @@ -6134,6 +6147,10 @@ The most secure encryption. Немає непрочитаних чатів No comment provided by engineer. + + No valid link + No comment provided by engineer. + Nobody tracked your conversations. No one drew a map of where you'd been. Privacy was never a feature - it was the way of life. No comment provided by engineer. @@ -6142,6 +6159,10 @@ The most secure encryption. Non-profit governance No comment provided by engineer. + + None of your servers are set to resolve SimpleX names. Configure servers, or use a connection link. + No comment provided by engineer. + Not a better lock on someone else's door. Not a nicer landlord that respects your privacy, but still keeps the record of all visitors. You are not a guest. You are home. No king can enter it - you are sovereign. No comment provided by engineer. @@ -6540,8 +6561,8 @@ alert button Owner No comment provided by engineer. - - Owners + + Owners & contributors No comment provided by engineer. @@ -6731,10 +6752,6 @@ Error: %@ Будь ласка, спробуйте вимкнути та знову увімкнути сповіщення. token info - - Please upgrade the app. - alert message - Please wait for group moderators to review your request to join the group. Будь ласка, зачекайте, поки модератори групи розглянуть ваш запит на приєднання до групи. @@ -7437,6 +7454,10 @@ swipe action Повернутися до теми користувача No comment provided by engineer. + + Resolver error: %@ + No comment provided by engineer. + Restart the app to create a new chat profile Перезапустіть програму, щоб створити новий профіль чату @@ -7517,6 +7538,22 @@ swipe action Роль No comment provided by engineer. + + Role will be changed to "%@". All chat members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All group members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All subscribers will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". The member will receive a new invitation. + No comment provided by engineer. + Run chat Запустити чат @@ -8047,6 +8084,10 @@ chat item action Сервер No comment provided by engineer. + + Server %@ does not support name resolution. Configure servers, or use a connection link. + No comment provided by engineer. + Server added to operator %@. Сервер додано до оператора %@. @@ -8475,6 +8516,18 @@ chat item action Посилання SimpleX заборонені No comment provided by engineer. + + SimpleX name + No comment provided by engineer. + + + SimpleX name error + No comment provided by engineer. + + + SimpleX name not verified + alert title + SimpleX one-time invitation Одноразове запрошення SimpleX @@ -8930,6 +8983,22 @@ It can happen because of some bug or when the connection is compromised. No comment provided by engineer. + + The SimpleX name #%@ is registered without channel link. Add channel link to the name via the registration page. + alert message + + + The SimpleX name %@ is registered, but it has no valid link. + No comment provided by engineer. + + + The SimpleX name %@ is registered, but not added to profile. Please add it to your address or channel profile, if you are the owner. + No comment provided by engineer. + + + The SimpleX name @%@ is registered without SimpleX address. Add your SimpleX address to the name via the registration page. + alert message + The address will be short, and your profile will be shared via the address. Адреса буде короткою, і ваш профіль буде доступний за цією адресою. @@ -9109,6 +9178,10 @@ your contacts and groups. Їх можна перевизначити в налаштуваннях контактів і груп. No comment provided by engineer. + + This SimpleX name is not registered. Please check the name. + No comment provided by engineer. + This action cannot be undone - all received and sent files and media will be deleted. Low resolution pictures will remain. Цю дію неможливо скасувати - всі отримані та надіслані файли і медіа будуть видалені. Зображення з низькою роздільною здатністю залишаться. @@ -9285,6 +9358,10 @@ You will be prompted to complete authentication before this feature is enabled.< Щоб записати голосове повідомлення, будь ласка, надайте дозвіл на використання мікрофону. No comment provided by engineer. + + To resolve names + No comment provided by engineer. + To reveal your hidden profile, enter a full password into a search field in **Your chat profiles** page. Щоб відкрити свій прихований профіль, введіть повний пароль у поле пошуку на сторінці **Ваші профілі чату**. @@ -9406,6 +9483,10 @@ You will be prompted to complete authentication before this feature is enabled.< Unblock subscriber for all? No comment provided by engineer. + + Unconfirmed name + No comment provided by engineer. + Undelivered messages Недоставлені повідомлення @@ -9503,19 +9584,11 @@ To connect, please ask your contact to create another connection link and check Непрочитане swipe action - - Unsupported channel name - alert title - Unsupported connection link Несумісне посилання для підключення conn error description - - Unsupported contact name - alert title - Unverified badge badge alert title @@ -9769,6 +9842,10 @@ To connect, please ask your contact to create another connection link and check Verify relay test step + + Verify SimpleX names + No comment provided by engineer. + Verify code with desktop Перевірте код на робочому столі @@ -9794,6 +9871,10 @@ To connect, please ask your contact to create another connection link and check Перевірте пароль до бази даних No comment provided by engineer. + + Verify name + No comment provided by engineer. + Verify passphrase Підтвердіть парольну фразу @@ -10428,6 +10509,10 @@ Repeat connection request? Ваша адреса SimpleX No comment provided by engineer. + + Your SimpleX name + No comment provided by engineer. + Your business contact Ваш діловий контакт @@ -10902,6 +10987,10 @@ marked deleted chat item preview text контакт повинен прийняти… No comment provided by engineer. + + contributor + member role + creator творець @@ -11543,6 +11632,10 @@ last received msg: %2$@ закреслено No comment provided by engineer. + + subscriber + member role + this contact цей контакт diff --git a/apps/ios/SimpleX Localizations/zh-Hans.xcloc/Localized Contents/zh-Hans.xliff b/apps/ios/SimpleX Localizations/zh-Hans.xcloc/Localized Contents/zh-Hans.xliff index d2558bf6d8..ed361099e1 100644 --- a/apps/ios/SimpleX Localizations/zh-Hans.xcloc/Localized Contents/zh-Hans.xliff +++ b/apps/ios/SimpleX Localizations/zh-Hans.xcloc/Localized Contents/zh-Hans.xliff @@ -197,6 +197,18 @@ %d 月 time interval + + %d owner + channel owners count + + + %d owners + channel owners count + + + %d owners & contributors + channel members count + %d relays failed channel relay bar @@ -1688,11 +1700,6 @@ new chat action 更改锁定模式 authentication reason - - Change member role? - 更改成员角色? - No comment provided by engineer. - Change passcode 更改密码 @@ -1713,6 +1720,10 @@ new chat action 改变角色 No comment provided by engineer. + + Change role? + No comment provided by engineer. + Change self-destruct mode 更改自毁模式 @@ -2278,14 +2289,6 @@ This is your own one-time link! 正连接到桌面 No comment provided by engineer. - - Connecting via channel name requires a newer app version. - alert message - - - Connecting via contact name requires a newer app version. - alert message - Connection 连接 @@ -2301,6 +2304,10 @@ This is your own one-time link! 连接被阻止 No comment provided by engineer. + + Connection blocked: %@ + conn error description + Connection error 连接错误 @@ -3077,7 +3084,7 @@ alert button No comment provided by engineer. - Destination server address of %@ is incompatible with forwarding server %@ settings. + Destination server address of %1$@ is incompatible with forwarding server %2$@ settings. 目标服务器地址 %@ 与转发服务器 %@ 设置不兼容。 No comment provided by engineer. @@ -3087,7 +3094,7 @@ alert button snd error text - Destination server version of %@ is incompatible with forwarding server %@. + Destination server version of %1$@ is incompatible with forwarding server %2$@. 目标服务器版本 %@ 与转发服务器 %@ 不兼容。 No comment provided by engineer. @@ -3633,7 +3640,7 @@ chat item action Error 错误 - conn error description + No comment provided by engineer. Error aborting address change @@ -3929,6 +3936,10 @@ chat item action 保存群组资料错误 No comment provided by engineer. + + Error saving name + alert title + Error saving passcode 保存密码错误 @@ -4062,6 +4073,7 @@ chat item action Error: %@ 错误: %@ alert message +conn error description file error text snd error text @@ -5274,6 +5286,14 @@ This is your link for group %@! 消耗更少的移动网络数据。 No comment provided by engineer. + + Let people connect to you via name registered with your SimpleX address. + No comment provided by engineer. + + + Let people join via name registered with this channel link. + No comment provided by engineer. + Let someone connect to you No comment provided by engineer. @@ -5451,21 +5471,6 @@ This is your link for group %@! 成员举报 chat feature - - Member role will be changed to "%@". All chat members will be notified. - 将变更成员角色为“%@”。所有成员都会收到通知。 - No comment provided by engineer. - - - Member role will be changed to "%@". All group members will be notified. - 成员角色将更改为 "%@"。所有群成员将收到通知。 - No comment provided by engineer. - - - Member role will be changed to "%@". The member will receive a new invitation. - 成员角色将更改为 "%@"。该成员将收到一份新的邀请。 - No comment provided by engineer. - Member will be removed from chat - this cannot be undone! 将从聊天中删除成员 - 此操作无法撤销! @@ -5820,6 +5825,10 @@ This is your link for group %@! 名称 swipe action + + Name not found + No comment provided by engineer. + Network & servers 网络和服务器 @@ -6141,6 +6150,10 @@ The most secure encryption. 无消息接收服务器。 servers error + + No servers to resolve names. + servers warning + No servers to send files. 无文件发送服务器。 @@ -6156,6 +6169,10 @@ The most secure encryption. 没有未读聊天 No comment provided by engineer. + + No valid link + No comment provided by engineer. + Nobody tracked your conversations. No one drew a map of where you'd been. Privacy was never a feature - it was the way of life. 没有人追踪你的谈话内容。没有人绘制你去过的地方的地图。隐私从来都不是一项功能--而是一种生活方式。 @@ -6165,6 +6182,10 @@ The most secure encryption. Non-profit governance No comment provided by engineer. + + None of your servers are set to resolve SimpleX names. Configure servers, or use a connection link. + No comment provided by engineer. + Not a better lock on someone else's door. Not a nicer landlord that respects your privacy, but still keeps the record of all visitors. You are not a guest. You are home. No king can enter it - you are sovereign. 别人家的门锁再好也比不上这里。房东再好也比不上这里,他既尊重你的隐私,又保留着所有访客的记录。你不是客人,你是家。没有国王能闯入--你是主人。 @@ -6569,8 +6590,8 @@ alert button Owner No comment provided by engineer. - - Owners + + Owners & contributors No comment provided by engineer. @@ -6760,10 +6781,6 @@ Error: %@ 请尝试禁用并重新启用通知。 token info - - Please upgrade the app. - alert message - Please wait for group moderators to review your request to join the group. 请等待群的协管审核你加入该群的请求。 @@ -7467,6 +7484,10 @@ swipe action 重置为用户主题 No comment provided by engineer. + + Resolver error: %@ + No comment provided by engineer. + Restart the app to create a new chat profile 重新启动应用程序以创建新的聊天资料 @@ -7546,6 +7567,22 @@ swipe action 角色 No comment provided by engineer. + + Role will be changed to "%@". All chat members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All group members will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". All subscribers will be notified. + No comment provided by engineer. + + + Role will be changed to "%@". The member will receive a new invitation. + No comment provided by engineer. + Run chat 运行聊天 @@ -8081,6 +8118,10 @@ chat item action 服务器 No comment provided by engineer. + + Server %@ does not support name resolution. Configure servers, or use a connection link. + No comment provided by engineer. + Server added to operator %@. 服务器已添加到运营方 %@。 @@ -8509,6 +8550,18 @@ chat item action 不允许SimpleX 链接 No comment provided by engineer. + + SimpleX name + No comment provided by engineer. + + + SimpleX name error + No comment provided by engineer. + + + SimpleX name not verified + alert title + SimpleX one-time invitation SimpleX 一次性邀请 @@ -8964,6 +9017,22 @@ It can happen because of some bug or when the connection is compromised. No comment provided by engineer. + + The SimpleX name #%@ is registered without channel link. Add channel link to the name via the registration page. + alert message + + + The SimpleX name %@ is registered, but it has no valid link. + No comment provided by engineer. + + + The SimpleX name %@ is registered, but not added to profile. Please add it to your address or channel profile, if you are the owner. + No comment provided by engineer. + + + The SimpleX name @%@ is registered without SimpleX address. Add your SimpleX address to the name via the registration page. + alert message + The address will be short, and your profile will be shared via the address. 地址不会长,将通过该简短地址分享个人资料。 @@ -9144,6 +9213,10 @@ your contacts and groups. 可以在联系人和群组设置中覆盖它们。 No comment provided by engineer. + + This SimpleX name is not registered. Please check the name. + No comment provided by engineer. + This action cannot be undone - all received and sent files and media will be deleted. Low resolution pictures will remain. 此操作无法撤消——所有接收和发送的文件和媒体都将被删除。 低分辨率图片将保留。 @@ -9321,6 +9394,10 @@ You will be prompted to complete authentication before this feature is enabled.< 请授权使用麦克风以录制语音消息。 No comment provided by engineer. + + To resolve names + No comment provided by engineer. + To reveal your hidden profile, enter a full password into a search field in **Your chat profiles** page. 要显示您的隐藏的个人资料,请在**您的聊天个人资料**页面的搜索字段中输入完整密码。 @@ -9443,6 +9520,10 @@ You will be prompted to complete authentication before this feature is enabled.< Unblock subscriber for all? No comment provided by engineer. + + Unconfirmed name + No comment provided by engineer. + Undelivered messages 未送达的消息 @@ -9540,19 +9621,11 @@ To connect, please ask your contact to create another connection link and check 未读 swipe action - - Unsupported channel name - alert title - Unsupported connection link 不支持的连接链接 conn error description - - Unsupported contact name - alert title - Unverified badge badge alert title @@ -9806,6 +9879,10 @@ To connect, please ask your contact to create another connection link and check Verify relay test step + + Verify SimpleX names + No comment provided by engineer. + Verify code with desktop 用桌面端验证代码 @@ -9831,6 +9908,10 @@ To connect, please ask your contact to create another connection link and check 验证数据库密码短语 No comment provided by engineer. + + Verify name + No comment provided by engineer. + Verify passphrase 验证密码短语 @@ -10468,6 +10549,10 @@ Repeat connection request? 您的 SimpleX 地址 No comment provided by engineer. + + Your SimpleX name + No comment provided by engineer. + Your business contact 你的企业联系人 @@ -10940,6 +11025,10 @@ marked deleted chat item preview text 联系人应当接受… No comment provided by engineer. + + contributor + member role + creator 创建者 @@ -11583,6 +11672,10 @@ last received msg: %2$@ 删去 No comment provided by engineer. + + subscriber + member role + this contact 这个联系人 diff --git a/apps/ios/SimpleX.xcodeproj/project.pbxproj b/apps/ios/SimpleX.xcodeproj/project.pbxproj index ad9fc9acc2..4927fed5f9 100644 --- a/apps/ios/SimpleX.xcodeproj/project.pbxproj +++ b/apps/ios/SimpleX.xcodeproj/project.pbxproj @@ -188,8 +188,8 @@ 64C3B0212A0D359700E19930 /* CustomTimePicker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 64C3B0202A0D359700E19930 /* CustomTimePicker.swift */; }; 64C8299D2D54AEEE006B9E89 /* libgmp.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 64C829982D54AEED006B9E89 /* libgmp.a */; }; 64C8299E2D54AEEE006B9E89 /* libffi.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 64C829992D54AEEE006B9E89 /* libffi.a */; }; - 64C8299F2D54AEEE006B9E89 /* libHSsimplex-chat-7.0.0.6-IDb07VxlHBtGmeucUQceZv-ghc9.6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 64C8299A2D54AEEE006B9E89 /* libHSsimplex-chat-7.0.0.6-IDb07VxlHBtGmeucUQceZv-ghc9.6.3.a */; }; - 64C829A02D54AEEE006B9E89 /* libHSsimplex-chat-7.0.0.6-IDb07VxlHBtGmeucUQceZv.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 64C8299B2D54AEEE006B9E89 /* libHSsimplex-chat-7.0.0.6-IDb07VxlHBtGmeucUQceZv.a */; }; + 64C8299F2D54AEEE006B9E89 /* libHSsimplex-chat-7.0.0.6-67j0xDFDAaz6bMQcxTdG4Z-ghc9.6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 64C8299A2D54AEEE006B9E89 /* libHSsimplex-chat-7.0.0.6-67j0xDFDAaz6bMQcxTdG4Z-ghc9.6.3.a */; }; + 64C829A02D54AEEE006B9E89 /* libHSsimplex-chat-7.0.0.6-67j0xDFDAaz6bMQcxTdG4Z.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 64C8299B2D54AEEE006B9E89 /* libHSsimplex-chat-7.0.0.6-67j0xDFDAaz6bMQcxTdG4Z.a */; }; 64C829A12D54AEEE006B9E89 /* libgmpxx.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 64C8299C2D54AEEE006B9E89 /* libgmpxx.a */; }; 64D0C2C029F9688300B38D5F /* UserAddressView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 64D0C2BF29F9688300B38D5F /* UserAddressView.swift */; }; 64D0C2C229FA57AB00B38D5F /* UserAddressLearnMore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 64D0C2C129FA57AB00B38D5F /* UserAddressLearnMore.swift */; }; @@ -573,8 +573,8 @@ 64C3B0202A0D359700E19930 /* CustomTimePicker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomTimePicker.swift; sourceTree = ""; }; 64C829982D54AEED006B9E89 /* libgmp.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = libgmp.a; sourceTree = ""; }; 64C829992D54AEEE006B9E89 /* libffi.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = libffi.a; sourceTree = ""; }; - 64C8299A2D54AEEE006B9E89 /* libHSsimplex-chat-7.0.0.6-IDb07VxlHBtGmeucUQceZv-ghc9.6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libHSsimplex-chat-7.0.0.6-IDb07VxlHBtGmeucUQceZv-ghc9.6.3.a"; sourceTree = ""; }; - 64C8299B2D54AEEE006B9E89 /* libHSsimplex-chat-7.0.0.6-IDb07VxlHBtGmeucUQceZv.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libHSsimplex-chat-7.0.0.6-IDb07VxlHBtGmeucUQceZv.a"; sourceTree = ""; }; + 64C8299A2D54AEEE006B9E89 /* libHSsimplex-chat-7.0.0.6-67j0xDFDAaz6bMQcxTdG4Z-ghc9.6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libHSsimplex-chat-7.0.0.6-67j0xDFDAaz6bMQcxTdG4Z-ghc9.6.3.a"; sourceTree = ""; }; + 64C8299B2D54AEEE006B9E89 /* libHSsimplex-chat-7.0.0.6-67j0xDFDAaz6bMQcxTdG4Z.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libHSsimplex-chat-7.0.0.6-67j0xDFDAaz6bMQcxTdG4Z.a"; sourceTree = ""; }; 64C8299C2D54AEEE006B9E89 /* libgmpxx.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = libgmpxx.a; sourceTree = ""; }; 64D0C2BF29F9688300B38D5F /* UserAddressView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UserAddressView.swift; sourceTree = ""; }; 64D0C2C129FA57AB00B38D5F /* UserAddressLearnMore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UserAddressLearnMore.swift; sourceTree = ""; }; @@ -745,8 +745,8 @@ 64C8299D2D54AEEE006B9E89 /* libgmp.a in Frameworks */, 64C8299E2D54AEEE006B9E89 /* libffi.a in Frameworks */, 64C829A12D54AEEE006B9E89 /* libgmpxx.a in Frameworks */, - 64C8299F2D54AEEE006B9E89 /* libHSsimplex-chat-7.0.0.6-IDb07VxlHBtGmeucUQceZv-ghc9.6.3.a in Frameworks */, - 64C829A02D54AEEE006B9E89 /* libHSsimplex-chat-7.0.0.6-IDb07VxlHBtGmeucUQceZv.a in Frameworks */, + 64C8299F2D54AEEE006B9E89 /* libHSsimplex-chat-7.0.0.6-67j0xDFDAaz6bMQcxTdG4Z-ghc9.6.3.a in Frameworks */, + 64C829A02D54AEEE006B9E89 /* libHSsimplex-chat-7.0.0.6-67j0xDFDAaz6bMQcxTdG4Z.a in Frameworks */, CE38A29C2C3FCD72005ED185 /* SwiftyGif in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -832,8 +832,8 @@ 64C829992D54AEEE006B9E89 /* libffi.a */, 64C829982D54AEED006B9E89 /* libgmp.a */, 64C8299C2D54AEEE006B9E89 /* libgmpxx.a */, - 64C8299A2D54AEEE006B9E89 /* libHSsimplex-chat-7.0.0.6-IDb07VxlHBtGmeucUQceZv-ghc9.6.3.a */, - 64C8299B2D54AEEE006B9E89 /* libHSsimplex-chat-7.0.0.6-IDb07VxlHBtGmeucUQceZv.a */, + 64C8299A2D54AEEE006B9E89 /* libHSsimplex-chat-7.0.0.6-67j0xDFDAaz6bMQcxTdG4Z-ghc9.6.3.a */, + 64C8299B2D54AEEE006B9E89 /* libHSsimplex-chat-7.0.0.6-67j0xDFDAaz6bMQcxTdG4Z.a */, ); path = Libraries; sourceTree = ""; diff --git a/apps/ios/SimpleX.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/apps/ios/SimpleX.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000000..978e1d9630 --- /dev/null +++ b/apps/ios/SimpleX.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,66 @@ +{ + "originHash" : "60aeecb7917535a5e44ade0dbb5411ab112a959283e565a04c212c8af4e7dee9", + "pins" : [ + { + "identity" : "codescanner", + "kind" : "remoteSourceControl", + "location" : "https://github.com/twostraws/CodeScanner", + "state" : { + "revision" : "34da57fb63b47add20de8a85da58191523ccce57", + "version" : "2.5.0" + } + }, + { + "identity" : "elegant-emoji-picker", + "kind" : "remoteSourceControl", + "location" : "https://github.com/Finalet/Elegant-Emoji-Picker", + "state" : { + "branch" : "main", + "revision" : "71d2d46092b4d550cc593614efc06438f845f6e6" + } + }, + { + "identity" : "ink", + "kind" : "remoteSourceControl", + "location" : "https://github.com/johnsundell/ink", + "state" : { + "revision" : "bcc9f219900a62c4210e6db726035d7f03ae757b", + "version" : "0.6.0" + } + }, + { + "identity" : "lzstring-swift", + "kind" : "remoteSourceControl", + "location" : "https://github.com/Ibrahimhass/lzstring-swift", + "state" : { + "revision" : "7f62f21de5b18582a950e1753b775cc614722407" + } + }, + { + "identity" : "swiftygif", + "kind" : "remoteSourceControl", + "location" : "https://github.com/kirualex/SwiftyGif", + "state" : { + "revision" : "5e8619335d394901379c9add5c4c1c2f420b3800" + } + }, + { + "identity" : "webrtc", + "kind" : "remoteSourceControl", + "location" : "https://github.com/simplex-chat/WebRTC.git", + "state" : { + "revision" : "34bedc50f9c58dccf4967ea59c7e6a47d620803b" + } + }, + { + "identity" : "yams", + "kind" : "remoteSourceControl", + "location" : "https://github.com/jpsim/Yams", + "state" : { + "revision" : "9234124cff5e22e178988c18d8b95a8ae8007f76", + "version" : "5.1.2" + } + } + ], + "version" : 3 +} diff --git a/apps/ios/SimpleXChat/APITypes.swift b/apps/ios/SimpleXChat/APITypes.swift index 5f1d8ef6c2..636ba99927 100644 --- a/apps/ios/SimpleXChat/APITypes.swift +++ b/apps/ios/SimpleXChat/APITypes.swift @@ -84,10 +84,8 @@ extension ChatAPIResult { // Spec: spec/api.md#decodeAPIResult public func decodeAPIResult(_ d: Data) -> APIResult { -// print("decodeAPIResult \(String(describing: R.self))") do { -// return try withStackSizeLimit { try jsonDecoder.decode(APIResult.self, from: d) } - return try jsonDecoder.decode(APIResult.self, from: d) + return try withLargeStack { try jsonDecoder.decode(APIResult.self, from: d) } } catch {} if let j = try? JSONSerialization.jsonObject(with: d) as? NSDictionary { if let (_, jErr) = getOWSF(j, "error") { @@ -106,31 +104,50 @@ public func decodeAPIResult(_ d: Data) -> APIResult { // Default stack size for the main thread is 1mb, for secondary threads - 512 kb. // This function can be used to test what size is used (or to increase available stack size). // Stack size must be a multiple of system page size (16kb). -//private let stackSizeLimit: Int = 256 * 1024 -// -//private func withStackSizeLimit(_ f: @escaping () throws -> T) throws -> T { -// let semaphore = DispatchSemaphore(value: 0) -// var result: Result? -// let thread = Thread { -// do { -// result = .success(try f()) -// } catch { -// result = .failure(error) -// } -// semaphore.signal() -// } -// -// thread.stackSize = stackSizeLimit -// thread.qualityOfService = Thread.current.qualityOfService -// thread.start() -// -// semaphore.wait() -// -// switch result! { -// case let .success(r): return r -// case let .failure(e): throw e -// } -//} +private let stackSizeLimit: Int = 16 * 1024 * 1024 + +private final class LargeStackRunner: NSObject { + static let shared = LargeStackRunner() + + private let serialize = NSLock() // serialize submitters + private let jobReady = DispatchSemaphore(value: 0) + private let jobDone = DispatchSemaphore(value: 0) + private var job: (() -> Void)? + private var thread: Thread? = nil + + private override init() { + super.init() + let t = Thread(target: self, selector: #selector(loop), object: nil) + t.stackSize = stackSizeLimit + t.name = "chat.simplex.decoding" + t.qualityOfService = .default + t.start() + thread = t + } + + @objc private func loop() { + while true { + jobReady.wait() + job?() + jobDone.signal() + } + } + + func run(_ f: @escaping () throws -> T) throws -> T { + serialize.lock() + defer { serialize.unlock() } + var result: Result! + job = { result = Result(catching: f) } + jobReady.signal() + jobDone.wait() + job = nil + return try result.get() + } +} + +func withLargeStack(_ work: @escaping () throws -> T) throws -> T { + try LargeStackRunner.shared.run(work) +} public func parseApiChats(_ jResp: NSDictionary) -> (user: UserRef, chats: [ChatData])? { if let jApiChats = jResp["apiChats"] as? NSDictionary, @@ -167,6 +184,10 @@ public struct CreatedConnLink: Decodable, Hashable { public func simplexChatUri(short: Bool = true) -> String { short ? (connShortLink ?? simplexChatLink(connFullLink)) : simplexChatLink(connFullLink) } + + public var cmdString: String { + connFullLink + (connShortLink.map { " \($0)"} ?? "") + } } public func simplexChatLink(_ uri: String) -> String { @@ -741,6 +762,8 @@ public enum ChatErrorType: Decodable, Hashable { case chatNotStopped case chatStoreChanged case invalidConnReq + case simplexDomainNotReady(simplexDomain: SimplexDomain, simplexDomainError: SimplexDomainError) + case notResolvedLocally case unsupportedConnReq case invalidChatMessage(connection: Connection, message: String) case connReqMessageProhibited @@ -896,6 +919,13 @@ public enum AgentErrorType: Decodable, Hashable { case INTERNAL(internalErr: String) case CRITICAL(offerRestart: Bool, criticalErr: String) case INACTIVE + case NO_NAME_SERVERS +} + +public enum NameErrorType: Decodable, Hashable { + case NO_RESOLVER + case NOT_FOUND + case RESOLVER(resolverErr: String) } public enum CommandErrorType: Decodable, Hashable { @@ -937,6 +967,7 @@ public enum ProtocolErrorType: Decodable, Hashable { case LARGE_MSG case EXPIRED case INTERNAL + case NAME(nameErr: NameErrorType) } public enum ProxyError: Decodable, Hashable { diff --git a/apps/ios/SimpleXChat/ChatTypes.swift b/apps/ios/SimpleXChat/ChatTypes.swift index 8b186f168d..d85999a7e7 100644 --- a/apps/ios/SimpleXChat/ChatTypes.swift +++ b/apps/ios/SimpleXChat/ChatTypes.swift @@ -119,7 +119,8 @@ public struct Profile: Codable, NamedChat, Hashable { image: String? = nil, contactLink: String? = nil, preferences: Preferences? = nil, - peerType: ChatPeerType? = nil + peerType: ChatPeerType? = nil, + contactDomain: SimplexDomainClaim? = nil ) { self.displayName = displayName self.fullName = fullName @@ -127,6 +128,7 @@ public struct Profile: Codable, NamedChat, Hashable { self.image = image self.contactLink = contactLink self.preferences = preferences + self.contactDomain = contactDomain } public var displayName: String @@ -139,6 +141,7 @@ public struct Profile: Codable, NamedChat, Hashable { // the badge proof from the wire profile - opaque to the UI, round-tripped to the core (apiPrepareContact) public var badge: BadgeProof? public var localAlias: String { get { "" } } + public var contactDomain: SimplexDomainClaim? var profileViewName: String { (fullName == "" || displayName == fullName) ? displayName : "\(displayName) (\(fullName))" @@ -161,7 +164,9 @@ public struct LocalProfile: Codable, NamedChat, Hashable { preferences: Preferences? = nil, peerType: ChatPeerType? = nil, localBadge: LocalBadge? = nil, - localAlias: String + localAlias: String, + contactDomain: SimplexDomainClaim? = nil, + contactDomainVerified: Bool? = nil ) { self.profileId = profileId self.displayName = displayName @@ -173,6 +178,8 @@ public struct LocalProfile: Codable, NamedChat, Hashable { self.peerType = peerType self.localBadge = localBadge self.localAlias = localAlias + self.contactDomain = contactDomain + self.contactDomainVerified = contactDomainVerified } public var profileId: Int64 @@ -185,6 +192,8 @@ public struct LocalProfile: Codable, NamedChat, Hashable { public var peerType: ChatPeerType? public var localBadge: LocalBadge? public var localAlias: String + public var contactDomain: SimplexDomainClaim? + public var contactDomainVerified: Bool? var profileViewName: String { localAlias == "" @@ -1720,11 +1729,11 @@ public enum ChatInfo: Identifiable, Decodable, NamedChat, Hashable { if groupInfo.membership.memberActive { switch(groupChatScope) { case .none: - if allRelaysBroken && groupInfo.useRelays { return ("can't broadcast", nil) } if groupInfo.membership.memberPending { return ("reviewed by admins", "Please contact group admin.") } if groupInfo.membership.memberRole == .observer { return groupInfo.useRelays ? ("you are subscriber", nil) : ("you are observer", "Please contact group admin.") } + if allRelaysBroken && groupInfo.useRelays { return ("can't broadcast", nil) } return nil case let .some(.memberSupport(groupMember_: .some(supportMember))): if supportMember.versionRange.maxVersion < GROUP_KNOCKING_VERSION && !supportMember.memberPending { @@ -2507,7 +2516,7 @@ public struct GroupInfo: Identifiable, Decodable, NamedChat, Hashable { public var groupId: Int64 public var useRelays: Bool public var relayOwnStatus: RelayStatus? = nil - var localDisplayName: GroupName + public var localDisplayName: GroupName public var groupProfile: GroupProfile public var businessChat: BusinessChatInfo? public var fullGroupPreferences: FullGroupPreferences @@ -2534,6 +2543,7 @@ public struct GroupInfo: Identifiable, Decodable, NamedChat, Hashable { public var chatTags: [Int64] public var chatItemTTL: Int64? public var localAlias: String + public var groupDomainVerified: Bool? public var isOwner: Bool { return membership.memberRole == .owner && membership.memberCurrent @@ -2614,19 +2624,37 @@ public enum GroupType: Codable, Hashable { } public struct PublicGroupAccess: Codable, Hashable { - public init(groupWebPage: String? = nil, groupDomain: String? = nil, domainWebPage: Bool = false, allowEmbedding: Bool = false) { + public init(groupWebPage: String? = nil, groupDomainClaim: SimplexDomainClaim? = nil, domainWebPage: Bool = false, allowEmbedding: Bool = false) { self.groupWebPage = groupWebPage - self.groupDomain = groupDomain + self.groupDomainClaim = groupDomainClaim self.domainWebPage = domainWebPage self.allowEmbedding = allowEmbedding } public var groupWebPage: String? - public var groupDomain: String? + public var groupDomainClaim: SimplexDomainClaim? public var domainWebPage: Bool = false public var allowEmbedding: Bool = false } +public struct SimplexDomainClaim: Codable, Hashable { + public init(domain: String, proof: SimplexDomainProof? = nil) { + self.domain = domain + self.proof = proof + } + public var domain: String + public var proof: SimplexDomainProof? + + public var shortName: String { + domain.hasSuffix(".simplex") ? String(domain.dropLast(".simplex".count)) : domain + } +} + +public enum SimplexDomainError: Decodable, Hashable { + case noValidLink + case unknownDomain +} + public struct RelayCapabilities: Codable, Hashable { public var webDomain: String? } @@ -5258,28 +5286,69 @@ public enum SimplexLinkType: String, Decodable, Hashable { } } -public struct SimplexNameInfo: Decodable, Equatable, Hashable { +public struct SimplexNameInfo: Codable, Equatable, Hashable { public var nameType: SimplexNameType - public var nameDomain: SimplexNameDomain + public var nameDomain: SimplexDomain + + // mirrors backend shortNameInfoStr: "#name" for a simplex public group, else prefix + full domain + public var shortStr: String { + if nameType == .publicGroup && nameDomain.nameTLD == .simplex && nameDomain.subDomain.isEmpty { + return "#" + nameDomain.domain + } else { + return (nameType == .publicGroup ? "#" : "@") + nameDomain.fullDomainName + } + } + + public init(nameType: SimplexNameType, nameDomain: SimplexDomain) { + self.nameType = nameType + self.nameDomain = nameDomain + } } -public struct SimplexNameDomain: Decodable, Equatable, Hashable { +public struct SimplexDomain: Codable, Equatable, Hashable { public var nameTLD: SimplexTLD public var domain: String public var subDomain: [String] + + // mirrors backend fullDomainName: reverse(subDomain) ++ [domain] ++ tld + public var fullDomainName: String { + let tld: [String] + switch nameTLD { + case .simplex: tld = ["simplex"] + case .testing: tld = ["testing"] + case .web: tld = [] + } + return (subDomain.reversed() + [domain] + tld).joined(separator: ".") + } + + public var cmdString: String { + "domain=\(fullDomainName)" + } + + public init(nameTLD: SimplexTLD, domain: String, subDomain: [String]) { + self.nameTLD = nameTLD + self.domain = domain + self.subDomain = subDomain + } } -public enum SimplexTLD: String, Decodable, Hashable { +public enum SimplexTLD: String, Codable, Hashable { case simplex case testing case web } -public enum SimplexNameType: String, Decodable, Hashable { +public enum SimplexNameType: String, Codable, Hashable { case publicGroup case contact } +public struct SimplexDomainProof: Codable, Hashable { + public var linkOwnerId: String? + public var presHeader: String + public var signature: String +} + public enum FormatColor: String, Decodable, Hashable { case red = "red" case green = "green" diff --git a/apps/ios/SimpleXChat/ErrorAlert.swift b/apps/ios/SimpleXChat/ErrorAlert.swift index 2920c2383c..796b995138 100644 --- a/apps/ios/SimpleXChat/ErrorAlert.swift +++ b/apps/ios/SimpleXChat/ErrorAlert.swift @@ -34,20 +34,16 @@ public struct ErrorAlert: Error { } public init(_ error: any Error) { - self = if let e = error as? ChatError { - ErrorAlert(e) + self = if let chatError = error as? ChatError { + if let a = getNetworkErrorAlert(chatError) { + ErrorAlert(title: "\(a.title)", message: a.message.map { "\($0)" }) + } else { + ErrorAlert("\(chatErrorString(chatError))") + } } else { ErrorAlert("\(error.localizedDescription)") } } - - public init(_ chatError: ChatError) { - self = if let networkErrorAlert = getNetworkErrorAlert(chatError) { - networkErrorAlert - } else { - ErrorAlert("\(chatErrorString(chatError))") - } - } } extension LocalizedStringKey: @unchecked Sendable { } @@ -83,18 +79,33 @@ extension View { } } -public func getNetworkErrorAlert(_ e: ChatError) -> ErrorAlert? { +public func getNetworkErrorAlert(_ e: ChatError) -> (title: String, message: String?)? { switch e { case let .errorAgent(.BROKER(addr, .TIMEOUT)): - ErrorAlert(title: "Connection timeout", message: "Please check your network connection with \(serverHostname(addr)) and try again.") + ( + title: NSLocalizedString("Connection timeout", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("Please check your network connection with %@ and try again.", comment: ""), serverHostname(addr)) + ) case let .errorAgent(.BROKER(addr, .NETWORK(.unknownCAError))): - ErrorAlert(title: "Connection error", message: "Fingerprint in server address does not match certificate: \(serverHostname(addr)).") + ( + title: NSLocalizedString("Connection error", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("Fingerprint in server address does not match certificate: %@.", comment: ""), serverHostname(addr)) + ) case let .errorAgent(.BROKER(addr, .NETWORK)): - ErrorAlert(title: "Connection error", message: "Please check your network connection with \(serverHostname(addr)) and try again.") + ( + title: NSLocalizedString("Connection error", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("Please check your network connection with %@ and try again.", comment: ""), serverHostname(addr)) + ) case let .errorAgent(.BROKER(addr, .HOST)): - ErrorAlert(title: "Connection error", message: "Server address is incompatible with network settings: \(serverHostname(addr)).") + ( + title: NSLocalizedString("Connection error", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("Server address is incompatible with network settings: %@.", comment: ""), serverHostname(addr)) + ) case let .errorAgent(.BROKER(addr, .TRANSPORT(.version))): - ErrorAlert(title: "Connection error", message: "Server version is incompatible with your app: \(serverHostname(addr)).") + ( + title: NSLocalizedString("Connection error", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("Server version is incompatible with your app: %@.", comment: ""), serverHostname(addr)) + ) case let .errorAgent(.SMP(serverAddress, .PROXY(proxyErr))): smpProxyErrorAlert(proxyErr, serverAddress) case let .errorAgent(.PROXY(proxyServer, relayServer, .protocolError(.PROXY(proxyErr)))): @@ -103,39 +114,72 @@ public func getNetworkErrorAlert(_ e: ChatError) -> ErrorAlert? { } } -private func smpProxyErrorAlert(_ proxyErr: ProxyError, _ srvAddr: String) -> ErrorAlert? { +private func smpProxyErrorAlert(_ proxyErr: ProxyError, _ srvAddr: String) -> (title: String, message: String?)? { switch proxyErr { case .BROKER(brokerErr: .TIMEOUT): - return ErrorAlert(title: "Private routing error", message: "Error connecting to forwarding server \(serverHostname(srvAddr)). Please try later.") + ( + title: NSLocalizedString("Private routing error", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("Error connecting to forwarding server %@. Please try later.", comment: ""), serverHostname(srvAddr)) + ) case .BROKER(brokerErr: .NETWORK(.unknownCAError)): - return ErrorAlert(title: "Private routing error", message: "Fingerprint in forwarding server address does not match certificate: \(serverHostname(srvAddr)).") + ( + title: NSLocalizedString("Private routing error", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("Fingerprint in forwarding server address does not match certificate: %@.", comment: ""), serverHostname(srvAddr)) + ) case .BROKER(brokerErr: .NETWORK): - return ErrorAlert(title: "Private routing error", message: "Error connecting to forwarding server \(serverHostname(srvAddr)). Please try later.") + ( + title: NSLocalizedString("Private routing error", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("Error connecting to forwarding server %@. Please try later.", comment: ""), serverHostname(srvAddr)) + ) case .BROKER(brokerErr: .HOST): - return ErrorAlert(title: "Private routing error", message: "Forwarding server address is incompatible with network settings: \(serverHostname(srvAddr)).") + ( + title: NSLocalizedString("Private routing error", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("Forwarding server address is incompatible with network settings: %@.", comment: ""), serverHostname(srvAddr)) + ) case .BROKER(brokerErr: .TRANSPORT(.version)): - return ErrorAlert(title: "Private routing error", message: "Forwarding server version is incompatible with network settings: \(serverHostname(srvAddr)).") + ( + title: NSLocalizedString("Private routing error", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("Forwarding server version is incompatible with network settings: %@.", comment: ""), serverHostname(srvAddr)) + ) default: - return nil + nil } } -private func proxyDestinationErrorAlert(_ proxyErr: ProxyError, _ proxyServer: String, _ relayServer: String) -> ErrorAlert? { +private func proxyDestinationErrorAlert(_ proxyErr: ProxyError, _ proxyServer: String, _ relayServer: String) -> (title: String, message: String?)? { switch proxyErr { case .BROKER(brokerErr: .TIMEOUT): - return ErrorAlert(title: "Private routing error", message: "Forwarding server \(serverHostname(proxyServer)) failed to connect to destination server \(serverHostname(relayServer)). Please try later.") + ( + title: NSLocalizedString("Private routing error", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("Forwarding server %@ failed to connect to destination server %@. Please try later.", comment: ""), serverHostname(proxyServer), serverHostname(relayServer)) + ) case .BROKER(brokerErr: .NETWORK(.unknownCAError)): - return ErrorAlert(title: "Private routing error", message: "Fingerprint in destination server address does not match certificate: \(serverHostname(relayServer)).") + ( + title: NSLocalizedString("Private routing error", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("Fingerprint in destination server address does not match certificate: %@.", comment: ""), serverHostname(relayServer)) + ) case .BROKER(brokerErr: .NETWORK): - return ErrorAlert(title: "Private routing error", message: "Forwarding server \(serverHostname(proxyServer)) failed to connect to destination server \(serverHostname(relayServer)). Please try later.") + ( + title: NSLocalizedString("Private routing error", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("Forwarding server %@ failed to connect to destination server %@. Please try later.", comment: ""), serverHostname(proxyServer), serverHostname(relayServer)) + ) case .NO_SESSION: - return ErrorAlert(title: "Private routing error", message: "Forwarding server \(serverHostname(proxyServer)) failed to connect to destination server \(serverHostname(relayServer)). Please try later.") + ( + title: NSLocalizedString("Private routing error", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("Forwarding server %@ failed to connect to destination server %@. Please try later.", comment: ""), serverHostname(proxyServer), serverHostname(relayServer)) + ) case .BROKER(brokerErr: .HOST): - return ErrorAlert(title: "Private routing error", message: "Destination server address of \(serverHostname(relayServer)) is incompatible with forwarding server \(serverHostname(proxyServer)) settings.") + ( + title: NSLocalizedString("Private routing error", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("Destination server address of %@ is incompatible with forwarding server %@ settings.", comment: ""), serverHostname(relayServer), serverHostname(proxyServer)) + ) case .BROKER(brokerErr: .TRANSPORT(.version)): - return ErrorAlert(title: "Private routing error", message: "Destination server version of \(serverHostname(relayServer)) is incompatible with forwarding server \(serverHostname(proxyServer)).") + ( + title: NSLocalizedString("Private routing error", comment: ""), + message: String.localizedStringWithFormat(NSLocalizedString("Destination server version of %@ is incompatible with forwarding server %@.", comment: ""), serverHostname(relayServer), serverHostname(proxyServer)) + ) default: - return nil + nil } } diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/model/ChatModel.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/model/ChatModel.kt index c5dd81fec7..fd093f5761 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/model/ChatModel.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/model/ChatModel.kt @@ -1660,9 +1660,6 @@ sealed class ChatInfo: SomeChat, NamedChat { if (groupInfo.membership.memberActive) { when (groupChatScope) { null -> { - if (allRelaysBroken && groupInfo.useRelays) { - return generalGetString(MR.strings.cant_broadcast_message) to null - } if (groupInfo.membership.memberPending) { return generalGetString(MR.strings.reviewed_by_admins) to generalGetString(MR.strings.observer_cant_send_message_desc) } @@ -1673,6 +1670,9 @@ sealed class ChatInfo: SomeChat, NamedChat { generalGetString(MR.strings.observer_cant_send_message_title) to generalGetString(MR.strings.observer_cant_send_message_desc) } } + if (allRelaysBroken && groupInfo.useRelays) { + return generalGetString(MR.strings.cant_broadcast_message) to null + } return null } is GroupChatScopeInfo.MemberSupport -> @@ -2039,14 +2039,15 @@ data class Profile( val peerType: ChatPeerType? = null, // the badge proof from the wire profile: not interpreted by the UI (display uses crypto-free LocalBadge), // but preserved so passing a link profile back to the core (apiPrepareContact) keeps the proof - val badge: BadgeProof? = null + val badge: BadgeProof? = null, + val contactDomain: SimplexDomainClaim? = null ): NamedChat { val profileViewName: String get() { return if (fullName == "" || displayName == fullName) displayName else "$displayName ($fullName)" } - fun toLocalProfile(profileId: Long): LocalProfile = LocalProfile(profileId, displayName, fullName, shortDescr, image, localAlias, contactLink, preferences, peerType) + fun toLocalProfile(profileId: Long): LocalProfile = LocalProfile(profileId, displayName, fullName, shortDescr, image, localAlias, contactLink, preferences, peerType, contactDomain = contactDomain) companion object { val sampleData = Profile( @@ -2068,11 +2069,13 @@ data class LocalProfile( val contactLink: String? = null, val preferences: ChatPreferences? = null, val peerType: ChatPeerType? = null, - val localBadge: LocalBadge? = null + val localBadge: LocalBadge? = null, + val contactDomain: SimplexDomainClaim? = null, + val contactDomainVerified: Boolean? = null ): NamedChat { val profileViewName: String = localAlias.ifEmpty { if (fullName == "" || displayName == fullName) displayName else "$displayName ($fullName)" } - fun toProfile(): Profile = Profile(displayName, fullName, shortDescr, image, localAlias, contactLink, preferences, peerType) + fun toProfile(): Profile = Profile(displayName, fullName, shortDescr, image, localAlias, contactLink, preferences, peerType, contactDomain = contactDomain) companion object { val sampleData = LocalProfile( @@ -2198,6 +2201,7 @@ data class GroupInfo ( val chatTags: List, val chatItemTTL: Long?, override val localAlias: String, + val groupDomainVerified: Boolean? = null, ): SomeChat, NamedChat { override val chatType get() = ChatType.Group override val id get() = "#$groupId" @@ -2319,10 +2323,18 @@ object GroupTypeSerializer : KSerializer { } } +@Serializable +data class SimplexDomainClaim( + val domain: String, + val proof: SimplexDomainProof? = null +) { + val shortName: String get() = domain.removeSuffix(".simplex") +} + @Serializable data class PublicGroupAccess( val groupWebPage: String? = null, - val groupDomain: String? = null, + val groupDomainClaim: SimplexDomainClaim? = null, val domainWebPage: Boolean = false, val allowEmbedding: Boolean = false ) @@ -4874,15 +4886,33 @@ enum class SimplexLinkType(val linkType: String) { @Serializable data class SimplexNameInfo( val nameType: SimplexNameType, - val nameDomain: SimplexNameDomain -) + val nameDomain: SimplexDomain +) { + // mirrors backend shortNameInfoStr: "#name" for a simplex public group, else prefix + full domain + val shortStr: String get() = when { + nameType == SimplexNameType.publicGroup && nameDomain.nameTLD == SimplexTLD.simplex && nameDomain.subDomain.isEmpty() -> "#" + nameDomain.domain + else -> (if (nameType == SimplexNameType.publicGroup) "#" else "@") + nameDomain.fullDomainName + } +} @Serializable -data class SimplexNameDomain( +data class SimplexDomain( val nameTLD: SimplexTLD, val domain: String, val subDomain: List -) +) { + // mirrors backend fullDomainName: reverse(subDomain) + [domain] + tld + val fullDomainName: String get() { + val tld = when (nameTLD) { + SimplexTLD.simplex -> listOf("simplex") + SimplexTLD.testing -> listOf("testing") + SimplexTLD.web -> emptyList() + } + return (subDomain.reversed() + domain + tld).joinToString(".") + } + + val cmdString: String get() = "domain=$fullDomainName" +} @Serializable enum class SimplexTLD { @@ -4897,6 +4927,14 @@ enum class SimplexNameType { @SerialName("contact") contact } +// peer's signed name claim; UI only checks presence +@Serializable +data class SimplexDomainProof( + val linkOwnerId: String? = null, + val presHeader: String, + val signature: String +) + @Serializable enum class FormatColor(val color: String) { red("red"), diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/model/SimpleXAPI.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/model/SimpleXAPI.kt index 54986e1815..80b7d828ba 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/model/SimpleXAPI.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/model/SimpleXAPI.kt @@ -122,6 +122,7 @@ class AppPreferences { val privacyProtectScreen = mkBoolPreference(SHARED_PREFS_PRIVACY_PROTECT_SCREEN, true) val privacyAcceptImages = mkBoolPreference(SHARED_PREFS_PRIVACY_ACCEPT_IMAGES, true) val privacyLinkPreviews = mkBoolPreference(SHARED_PREFS_PRIVACY_LINK_PREVIEWS, true) + val privacyVerifySimplexNames = mkBoolPreference(SHARED_PREFS_PRIVACY_VERIFY_SIMPLEX_NAMES, false) val privacyLinkPreviewsShowAlert = mkBoolPreference(SHARED_PREFS_PRIVACY_LINK_PREVIEWS_SHOW_ALERT, true) val privacySanitizeLinks = mkBoolPreference(SHARED_PREFS_PRIVACY_SANITIZE_LINKS, false) // TODO remove @@ -397,6 +398,7 @@ class AppPreferences { private const val SHARED_PREFS_PRIVACY_ACCEPT_IMAGES = "PrivacyAcceptImages" private const val SHARED_PREFS_PRIVACY_TRANSFER_IMAGES_INLINE = "PrivacyTransferImagesInline" private const val SHARED_PREFS_PRIVACY_LINK_PREVIEWS = "PrivacyLinkPreviews" + private const val SHARED_PREFS_PRIVACY_VERIFY_SIMPLEX_NAMES = "PrivacyVerifySimplexNames" private const val SHARED_PREFS_PRIVACY_LINK_PREVIEWS_SHOW_ALERT = "PrivacyLinkPreviewsShowAlert" private const val SHARED_PREFS_PRIVACY_SANITIZE_LINKS = "PrivacySanitizeLinks" private const val SHARED_PREFS_PRIVACY_CHAT_LIST_OPEN_LINKS = "ChatListOpenLinks" // TODO remove @@ -1515,10 +1517,12 @@ object ChatController { return null } - suspend fun apiConnectPlan(rh: Long?, connLink: String, linkOwnerSig: LinkOwnerSig? = null, inProgress: MutableState): Pair? { + suspend fun apiConnectPlan(rh: Long?, connLink: String, resolveMode: PlanResolveMode = PlanResolveMode.PRMUnknown, linkOwnerSig: LinkOwnerSig? = null, inProgress: MutableState): ConnectionPlanResult? { val userId = kotlin.runCatching { currentUserId("apiConnectPlan") }.getOrElse { return null } - val r = sendCmdWithRetry(rh, CC.APIConnectPlan(userId, connLink, linkOwnerSig), inProgress = inProgress) - if (r is API.Result && r.res is CR.CRConnectionPlan) return r.res.connLink to r.res.connectionPlan + val r = sendCmdWithRetry(rh, CC.APIConnectPlan(userId, connLink, resolveMode, linkOwnerSig), inProgress = inProgress) + if (r is API.Result && r.res is CR.CRConnectionPlan) return ConnectionPlanResult(r.res.connLink, r.res.planSimplexName, r.res.otherSimplexName, r.res.connectionPlan) + // a PRMNever (typing) search that matches nothing locally is not an error to surface + if (r is API.Error && r.err is ChatError.ChatErrorChat && r.err.errorType is ChatErrorType.NotResolvedLocally) return null if (inProgress.value && r != null) apiConnectResponseAlert(r) return null } @@ -1555,6 +1559,46 @@ object ChatController { generalGetString(MR.strings.link_requires_newer_app_version_please_upgrade) ) } + r is API.Error && r.err is ChatError.ChatErrorChat + && r.err.errorType is ChatErrorType.SimplexDomainNotReady -> { + val domain = r.err.errorType.simplexDomain.fullDomainName + if (r.err.errorType.simplexDomainError is SimplexDomainError.NoValidLink) { + AlertManager.shared.showAlertMsg( + generalGetString(MR.strings.simplex_name_no_valid_link), + generalGetString(MR.strings.simplex_name_no_valid_link_desc).format(domain) + ) + } else { + AlertManager.shared.showAlertMsg( + generalGetString(MR.strings.simplex_name_unconfirmed), + generalGetString(MR.strings.simplex_name_unconfirmed_desc).format(domain) + ) + } + } + r is API.Error && r.err is ChatError.ChatErrorAgent + && r.err.agentError is AgentErrorType.NO_NAME_SERVERS -> { + AlertManager.shared.showAlertMsg( + generalGetString(MR.strings.simplex_name_error), + generalGetString(MR.strings.simplex_name_no_servers_desc) + ) + } + r is API.Error && r.err is ChatError.ChatErrorAgent + && r.err.agentError is AgentErrorType.SMP + && r.err.agentError.smpErr is SMPErrorType.NAME -> { + when (val nameErr = r.err.agentError.smpErr.nameErr) { + is NameErrorType.NOT_FOUND -> AlertManager.shared.showAlertMsg( + generalGetString(MR.strings.simplex_name_not_found), + generalGetString(MR.strings.simplex_name_not_found_desc) + ) + is NameErrorType.NO_RESOLVER -> AlertManager.shared.showAlertMsg( + generalGetString(MR.strings.simplex_name_error), + generalGetString(MR.strings.simplex_name_server_no_resolver_desc).format(r.err.agentError.serverAddress) + ) + is NameErrorType.RESOLVER -> AlertManager.shared.showAlertMsg( + generalGetString(MR.strings.simplex_name_error), + generalGetString(MR.strings.simplex_name_resolver_error_desc).format(nameErr.resolverErr) + ) + } + } r is API.Error && r.err is ChatError.ChatErrorAgent && r.err.agentError is AgentErrorType.SMP && r.err.agentError.smpErr is SMPErrorType.AUTH -> { @@ -1587,11 +1631,29 @@ object ChatController { } } + // owner-specific wording for setting one's own/channel name; null for other errors (handled by apiConnectResponseAlert) + fun simplexNameOwnerError(err: ChatError, isChannel: Boolean): String? = + if (err is ChatError.ChatErrorChat && err.errorType is ChatErrorType.SimplexDomainNotReady && err.errorType.simplexDomainError is SimplexDomainError.NoValidLink) { + val domain = err.errorType.simplexDomain.fullDomainName + if (isChannel) generalGetString(MR.strings.simplex_name_owner_no_channel_link).format(domain) + else generalGetString(MR.strings.simplex_name_owner_no_address).format(domain) + } else null + fun connErrorText(e: ChatError): String = when { e is ChatError.ChatErrorChat && e.errorType is ChatErrorType.InvalidConnReq -> generalGetString(MR.strings.invalid_connection_link) e is ChatError.ChatErrorChat && e.errorType is ChatErrorType.UnsupportedConnReq -> generalGetString(MR.strings.unsupported_connection_link) + e is ChatError.ChatErrorChat && e.errorType is ChatErrorType.SimplexDomainNotReady -> + if (e.errorType.simplexDomainError is SimplexDomainError.NoValidLink) + generalGetString(MR.strings.simplex_name_no_valid_link) + else generalGetString(MR.strings.simplex_name_unconfirmed) + e is ChatError.ChatErrorAgent && e.agentError is AgentErrorType.NO_NAME_SERVERS -> + generalGetString(MR.strings.simplex_name_error) + e is ChatError.ChatErrorAgent && e.agentError is AgentErrorType.SMP && e.agentError.smpErr is SMPErrorType.NAME -> + if (e.agentError.smpErr.nameErr is NameErrorType.NOT_FOUND) + generalGetString(MR.strings.simplex_name_not_found) + else generalGetString(MR.strings.simplex_name_error) e is ChatError.ChatErrorAgent && e.agentError is AgentErrorType.SMP && e.agentError.smpErr is SMPErrorType.AUTH -> generalGetString(MR.strings.connection_error_auth) e is ChatError.ChatErrorAgent && e.agentError is AgentErrorType.SMP && e.agentError.smpErr is SMPErrorType.BLOCKED -> @@ -1604,19 +1666,19 @@ object ChatController { "${generalGetString(MR.strings.error_prefix)}: ${e.string}" } - suspend fun apiPrepareContact(rh: Long?, connLink: CreatedConnLink, contactShortLinkData: ContactShortLinkData): Chat? { + suspend fun apiPrepareContact(rh: Long?, connLink: CreatedConnLink, contactShortLinkData: ContactShortLinkData, verifiedDomain: SimplexDomain? = null): Chat? { val userId = try { currentUserId("apiPrepareContact") } catch (e: Exception) { return null } - val r = sendCmd(rh, CC.APIPrepareContact(userId, connLink, contactShortLinkData)) - if (r is API.Result && r.res is CR.NewPreparedChat) return r.res.chat + val r = sendCmd(rh, CC.APIPrepareContact(userId, connLink, contactShortLinkData, verifiedDomain)) + if (r is API.Result && r.res is CR.NewPreparedChat) return if (rh == null) r.res.chat else r.res.chat.copy(remoteHostId = rh) Log.e(TAG, "apiPrepareContact bad response: ${r.responseType} ${r.details}") AlertManager.shared.showAlertMsg(generalGetString(MR.strings.error_preparing_contact), "${r.responseType}: ${r.details}") return null } - suspend fun apiPrepareGroup(rh: Long?, connLink: CreatedConnLink, directLink: Boolean, groupShortLinkData: GroupShortLinkData): Chat? { + suspend fun apiPrepareGroup(rh: Long?, connLink: CreatedConnLink, directLink: Boolean, groupShortLinkData: GroupShortLinkData, verifiedDomain: SimplexDomain? = null): Chat? { val userId = try { currentUserId("apiPrepareGroup") } catch (e: Exception) { return null } - val r = sendCmd(rh, CC.APIPrepareGroup(userId, connLink, directLink, groupShortLinkData)) - if (r is API.Result && r.res is CR.NewPreparedChat) return r.res.chat + val r = sendCmd(rh, CC.APIPrepareGroup(userId, connLink, directLink, groupShortLinkData, verifiedDomain)) + if (r is API.Result && r.res is CR.NewPreparedChat) return if (rh == null) r.res.chat else r.res.chat.copy(remoteHostId = rh) Log.e(TAG, "apiPrepareGroup bad response: ${r.responseType} ${r.details}") AlertManager.shared.showAlertMsg(generalGetString(MR.strings.error_preparing_group), "${r.responseType}: ${r.details}") return null @@ -1762,6 +1824,38 @@ object ChatController { } } + // name is the encoded SimplexName (e.g. "@alice.simplex"); null clears it. Throws on rejection. + suspend fun apiSetUserDomain(rh: Long?, simplexDomain: String?): User { + val userId = currentUserId("apiSetUserDomain") + val r = sendCmd(rh, CC.ApiSetUserDomain(userId, simplexDomain)) + return when { + r is API.Result && r.res is CR.UserProfileUpdated -> r.res.user.updateRemoteHostId(rh) + r is API.Result && r.res is CR.UserProfileNoChange -> r.res.user.updateRemoteHostId(rh) + else -> { + if (r is API.Error) { + val ownerMsg = simplexNameOwnerError(r.err, isChannel = false) + if (ownerMsg != null) AlertManager.shared.showAlertMsg(generalGetString(MR.strings.error_saving_simplex_name), ownerMsg) + else apiConnectResponseAlert(r) + } + throw Exception("failed to set SimpleX name: ${r.responseType} ${r.details}") + } + } + } + + suspend fun apiVerifyContactDomain(rh: Long?, contactId: Long): Pair? { + val r = sendCmd(rh, CC.ApiVerifyContactDomain(contactId)) + if (r is API.Result && r.res is CR.ContactDomainVerified) return r.res.contact to r.res.verificationFailure + Log.e(TAG, "apiVerifyContactDomain bad response: ${r.responseType} ${r.details}") + return null + } + + suspend fun apiVerifyGroupDomain(rh: Long?, groupId: Long): Pair? { + val r = sendCmd(rh, CC.ApiVerifyGroupDomain(groupId)) + if (r is API.Result && r.res is CR.GroupDomainVerified) return r.res.groupInfo to r.res.verificationFailure + Log.e(TAG, "apiVerifyGroupDomain bad response: ${r.responseType} ${r.details}") + return null + } + suspend fun apiSetContactPrefs(rh: Long?, contactId: Long, prefs: ChatPreferences): Contact? { val r = sendCmd(rh, CC.ApiSetContactPrefs(contactId, prefs)) if (r is API.Result && r.res is CR.ContactPrefsUpdated) return r.res.toContact @@ -2172,8 +2266,8 @@ object ChatController { return null } - suspend fun apiGetGroupRelays(groupId: Long): List { - val r = sendCmd(null, CC.ApiGetGroupRelays(groupId)) + suspend fun apiGetGroupRelays(rh: Long?, groupId: Long): List { + val r = sendCmd(rh, CC.ApiGetGroupRelays(groupId)) if (r is API.Result && r.res is CR.GroupRelays) return r.res.groupRelays return emptyList() } @@ -2183,8 +2277,8 @@ object ChatController { data class AddFailed(val addRelayResults: List): AddGroupRelaysResult() } - suspend fun apiAddGroupRelays(groupId: Long, relayIds: List): AddGroupRelaysResult? { - val r = sendCmdWithRetry(null, CC.ApiAddGroupRelays(groupId, relayIds)) + suspend fun apiAddGroupRelays(rh: Long?, groupId: Long, relayIds: List): AddGroupRelaysResult? { + val r = sendCmdWithRetry(rh, CC.ApiAddGroupRelays(groupId, relayIds)) if (r is API.Result && r.res is CR.GroupRelaysAdded) return AddGroupRelaysResult.Added(r.res.groupInfo, r.res.groupLink, r.res.groupRelays) if (r is API.Result && r.res is CR.GroupRelaysAddFailed) return AddGroupRelaysResult.AddFailed(r.res.addRelayResults) if (r != null) throw Exception("${r.responseType}: ${r.details}") @@ -2289,7 +2383,7 @@ object ChatController { return when { r is API.Result && r.res is CR.GroupUpdated -> r.res.toGroup r is API.Error -> { - AlertManager.shared.showAlertMsg(generalGetString(errorTitle), "${r.err.string}") + AlertManager.shared.showAlertMsg(generalGetString(errorTitle), r.err.string) null } else -> { @@ -2303,6 +2397,23 @@ object ChatController { } } + suspend fun apiSetPublicGroupAccess(rh: Long?, groupId: Long, access: PublicGroupAccess): GroupInfo? { + val r = sendCmd(rh, CC.ApiSetPublicGroupAccess(groupId, access)) + return when { + r is API.Result && r.res is CR.GroupUpdated -> r.res.toGroup + r is API.Error -> { + val ownerMsg = simplexNameOwnerError(r.err, isChannel = true) + if (ownerMsg != null) AlertManager.shared.showAlertMsg(generalGetString(MR.strings.error_saving_simplex_name), ownerMsg) + else apiConnectResponseAlert(r) + null + } + else -> { + Log.e(TAG, "apiSetPublicGroupAccess bad response: ${r.responseType} ${r.details}") + null + } + } + } + suspend fun apiCreateGroupLink(rh: Long?, groupId: Long, memberRole: GroupMemberRole = GroupMemberRole.Member): GroupLink? { val r = sendCmdWithRetry(rh, CC.APICreateGroupLink(groupId, memberRole)) if (r is API.Result && r.res is CR.GroupLinkCreated) return r.res.groupLink @@ -3705,6 +3816,7 @@ sealed class CC { class ApiLeaveGroup(val groupId: Long): CC() class ApiListMembers(val groupId: Long): CC() class ApiUpdateGroupProfile(val groupId: Long, val groupProfile: GroupProfile): CC() + class ApiSetPublicGroupAccess(val groupId: Long, val access: PublicGroupAccess): CC() class APICreateGroupLink(val groupId: Long, val memberRole: GroupMemberRole): CC() class APIGroupLinkMemberRole(val groupId: Long, val memberRole: GroupMemberRole): CC() class APIDeleteGroupLink(val groupId: Long): CC() @@ -3751,9 +3863,9 @@ sealed class CC { class APIAddContact(val userId: Long, val incognito: Boolean): CC() class ApiSetConnectionIncognito(val connId: Long, val incognito: Boolean): CC() class ApiChangeConnectionUser(val connId: Long, val userId: Long): CC() - class APIConnectPlan(val userId: Long, val connLink: String, val linkOwnerSig: LinkOwnerSig? = null): CC() - class APIPrepareContact(val userId: Long, val connLink: CreatedConnLink, val contactShortLinkData: ContactShortLinkData): CC() - class APIPrepareGroup(val userId: Long, val connLink: CreatedConnLink, val directLink: Boolean, val groupShortLinkData: GroupShortLinkData): CC() + class APIConnectPlan(val userId: Long, val connLink: String, val resolveMode: PlanResolveMode = PlanResolveMode.PRMUnknown, val linkOwnerSig: LinkOwnerSig? = null): CC() + class APIPrepareContact(val userId: Long, val connLink: CreatedConnLink, val contactShortLinkData: ContactShortLinkData, val verifiedDomain: SimplexDomain? = null): CC() + class APIPrepareGroup(val userId: Long, val connLink: CreatedConnLink, val directLink: Boolean, val groupShortLinkData: GroupShortLinkData, val verifiedDomain: SimplexDomain? = null): CC() class APIChangePreparedContactUser(val contactId: Long, val newUserId: Long): CC() class APIChangePreparedGroupUser(val groupId: Long, val newUserId: Long): CC() class APIConnectPreparedContact(val contactId: Long, val incognito: Boolean, val msg: MsgContent?): CC() @@ -3775,6 +3887,9 @@ sealed class CC { class ApiShowMyAddress(val userId: Long): CC() class ApiAddMyAddressShortLink(val userId: Long): CC() class ApiSetProfileAddress(val userId: Long, val on: Boolean): CC() + class ApiSetUserDomain(val userId: Long, val simplexDomain: String?): CC() + class ApiVerifyContactDomain(val contactId: Long): CC() + class ApiVerifyGroupDomain(val groupId: Long): CC() class ApiSetAddressSettings(val userId: Long, val addressSettings: AddressSettings): CC() class ApiGetCallInvitations: CC() class ApiSendCallInvitation(val contact: Contact, val callType: CallType): CC() @@ -3957,11 +4072,12 @@ sealed class CC { is ApiSetConnectionIncognito -> "/_set incognito :$connId ${onOff(incognito)}" is ApiChangeConnectionUser -> "/_set conn user :$connId $userId" is APIConnectPlan -> { + val resolveStr = if (resolveMode != PlanResolveMode.PRMUnknown) " resolve=${resolveMode.cmdString}" else "" val sigStr = if (linkOwnerSig != null) " sig=${json.encodeToString(linkOwnerSig)}" else "" - "/_connect plan $userId $connLink$sigStr" + "/_connect plan $userId $connLink$resolveStr$sigStr" } - is APIPrepareContact -> "/_prepare contact $userId ${connLink.connFullLink} ${connLink.connShortLink ?: ""} ${json.encodeToString(contactShortLinkData)}" - is APIPrepareGroup -> "/_prepare group $userId ${connLink.connFullLink} ${connLink.connShortLink ?: ""} direct=${onOff(directLink)} ${json.encodeToString(groupShortLinkData)}" + is APIPrepareContact -> "/_prepare contact $userId ${connLink.cmdString}${verifiedDomain?.let { " ${it.cmdString}" } ?: ""} ${json.encodeToString(contactShortLinkData)}" + is APIPrepareGroup -> "/_prepare group $userId ${connLink.cmdString} direct=${onOff(directLink)}${verifiedDomain?.let { " ${it.cmdString}" } ?: ""} ${json.encodeToString(groupShortLinkData)}" is APIChangePreparedContactUser -> "/_set contact user @$contactId $newUserId" is APIChangePreparedGroupUser -> "/_set group user #$groupId $newUserId" is APIConnectPreparedContact -> "/_connect contact @$contactId incognito=${onOff(incognito)}${maybeContent(msg)}" @@ -3983,6 +4099,10 @@ sealed class CC { is ApiShowMyAddress -> "/_show_address $userId" is ApiAddMyAddressShortLink -> "/_short_link_address $userId" is ApiSetProfileAddress -> "/_profile_address $userId ${onOff(on)}" + is ApiSetUserDomain -> "/_set domain $userId" + (if (simplexDomain != null) " $simplexDomain" else "") + is ApiSetPublicGroupAccess -> "/_public group access #$groupId ${json.encodeToString(access)}" + is ApiVerifyContactDomain -> "/_verify domain @$contactId" + is ApiVerifyGroupDomain -> "/_verify domain #$groupId" is ApiSetAddressSettings -> "/_address_settings $userId ${json.encodeToString(addressSettings)}" is ApiAcceptContact -> "/_accept incognito=${onOff(incognito)} $contactReqId" is ApiRejectContact -> "/_reject $contactReqId" @@ -4164,6 +4284,10 @@ sealed class CC { is ApiShowMyAddress -> "apiShowMyAddress" is ApiAddMyAddressShortLink -> "apiAddMyAddressShortLink" is ApiSetProfileAddress -> "apiSetProfileAddress" + is ApiSetUserDomain -> "apiSetUserDomain" + is ApiSetPublicGroupAccess -> "apiSetPublicGroupAccess" + is ApiVerifyContactDomain -> "apiVerifyContactDomain" + is ApiVerifyGroupDomain -> "apiVerifyGroupDomain" is ApiSetAddressSettings -> "apiSetAddressSettings" is ApiAcceptContact -> "apiAcceptContact" is ApiRejectContact -> "apiRejectContact" @@ -4443,8 +4567,8 @@ data class ServerOperator( serverDomains = listOf("simplex.im"), conditionsAcceptance = ConditionsAcceptance.Accepted(acceptedAt = null, autoAccepted = false), enabled = true, - smpRoles = ServerRoles(storage = true, proxy = true), - xftpRoles = ServerRoles(storage = true, proxy = true) + smpRoles = ServerRoles(storage = true, proxy = true, names = true), + xftpRoles = ServerRoles(storage = true, proxy = true, names = false) ) } @@ -4504,7 +4628,8 @@ data class ServerOperator( @Serializable data class ServerRoles( val storage: Boolean, - val proxy: Boolean + val proxy: Boolean, + val names: Boolean ) @Serializable @@ -4526,8 +4651,8 @@ data class UserOperatorServers( serverDomains = emptyList(), conditionsAcceptance = ConditionsAcceptance.Accepted(null, autoAccepted = false), enabled = false, - smpRoles = ServerRoles(storage = true, proxy = true), - xftpRoles = ServerRoles(storage = true, proxy = true) + smpRoles = ServerRoles(storage = true, proxy = true, names = true), + xftpRoles = ServerRoles(storage = true, proxy = true, names = false) ) companion object { @@ -4613,6 +4738,7 @@ sealed class UserServersError { @Serializable sealed class UserServersWarning { @Serializable @SerialName("noChatRelays") data class NoChatRelays(val user: UserRef? = null): UserServersWarning() + @Serializable @SerialName("noNamesServers") data class NoNamesServers(val user: UserRef? = null): UserServersWarning() val globalWarning: String? get() = when (this) { @@ -4622,6 +4748,12 @@ sealed class UserServersWarning { String.format(generalGetString(MR.strings.for_chat_profile), user.localDisplayName) + " " + text } else text } + is NoNamesServers -> { + val text = generalGetString(MR.strings.no_names_servers_enabled) + if (user != null) { + String.format(generalGetString(MR.strings.for_chat_profile), user.localDisplayName) + " " + text + } else text + } } } @@ -6384,7 +6516,7 @@ sealed class CR { @Serializable @SerialName("invitation") class Invitation(val user: UserRef, val connLinkInvitation: CreatedConnLink, val connection: PendingContactConnection): CR() @Serializable @SerialName("connectionIncognitoUpdated") class ConnectionIncognitoUpdated(val user: UserRef, val toConnection: PendingContactConnection): CR() @Serializable @SerialName("connectionUserChanged") class ConnectionUserChanged(val user: UserRef, val fromConnection: PendingContactConnection, val toConnection: PendingContactConnection, val newUser: UserRef): CR() - @Serializable @SerialName("connectionPlan") class CRConnectionPlan(val user: UserRef, val connLink: CreatedConnLink, val connectionPlan: ConnectionPlan): CR() + @Serializable @SerialName("connectionPlan") class CRConnectionPlan(val user: UserRef, val connLink: CreatedConnLink, val planSimplexName: SimplexNameInfo? = null, val otherSimplexName: SimplexNameInfo? = null, val connectionPlan: ConnectionPlan): CR() @Serializable @SerialName("newPreparedChat") class NewPreparedChat(val user: UserRef, val chat: Chat): CR() @Serializable @SerialName("contactUserChanged") class ContactUserChanged(val user: UserRef, val fromContact: Contact, val newUser: UserRef, val toContact: Contact): CR() @Serializable @SerialName("groupUserChanged") class GroupUserChanged(val user: UserRef, val fromGroup: GroupInfo, val newUser: UserRef, val toGroup: GroupInfo): CR() @@ -6462,6 +6594,8 @@ sealed class CR { @Serializable @SerialName("joinedGroupMember") class JoinedGroupMember(val user: UserRef, val groupInfo: GroupInfo, val member: GroupMember): CR() @Serializable @SerialName("connectedToGroupMember") class ConnectedToGroupMember(val user: UserRef, val groupInfo: GroupInfo, val member: GroupMember, val memberContact: Contact? = null): CR() @Serializable @SerialName("groupUpdated") class GroupUpdated(val user: UserRef, val toGroup: GroupInfo): CR() + @Serializable @SerialName("contactDomainVerified") class ContactDomainVerified(val user: UserRef, val contact: Contact, val verificationFailure: String? = null): CR() + @Serializable @SerialName("groupDomainVerified") class GroupDomainVerified(val user: UserRef, val groupInfo: GroupInfo, val verificationFailure: String? = null): CR() @Serializable @SerialName("groupLinkDataUpdated") class GroupLinkDataUpdated(val user: UserRef, val groupInfo: GroupInfo, val groupLink: GroupLink, val groupRelays: List, val relaysChanged: Boolean): CR() @Serializable @SerialName("groupRelayUpdated") class GroupRelayUpdated(val user: UserRef, val groupInfo: GroupInfo, val member: GroupMember, val groupRelay: GroupRelay): CR() @Serializable @SerialName("groupLinkCreated") class GroupLinkCreated(val user: UserRef, val groupInfo: GroupInfo, val groupLink: GroupLink): CR() @@ -6653,6 +6787,8 @@ sealed class CR { is JoinedGroupMember -> "joinedGroupMember" is ConnectedToGroupMember -> "connectedToGroupMember" is GroupUpdated -> "groupUpdated" + is ContactDomainVerified -> "contactDomainVerified" + is GroupDomainVerified -> "groupDomainVerified" is GroupLinkDataUpdated -> "groupLinkDataUpdated" is GroupRelayUpdated -> "groupRelayUpdated" is GroupLinkCreated -> "groupLinkCreated" @@ -6837,6 +6973,8 @@ sealed class CR { is JoinedGroupMember -> withUser(user, "groupInfo: $groupInfo\nmember: $member") is ConnectedToGroupMember -> withUser(user, "groupInfo: $groupInfo\nmember: $member\nmemberContact: $memberContact") is GroupUpdated -> withUser(user, json.encodeToString(toGroup)) + is ContactDomainVerified -> withUser(user, "contact: ${json.encodeToString(contact)}\nverificationFailure: $verificationFailure") + is GroupDomainVerified -> withUser(user, "groupInfo: ${json.encodeToString(groupInfo)}\nverificationFailure: $verificationFailure") is GroupLinkDataUpdated -> withUser(user, "groupInfo: $groupInfo\ngroupLink: $groupLink\ngroupRelays: $groupRelays\nrelaysChanged: $relaysChanged") is GroupRelayUpdated -> withUser(user, "groupInfo: $groupInfo\nmember: $member\ngroupRelay: $groupRelay") is GroupLinkCreated -> withUser(user, "groupInfo: $groupInfo\ngroupLink: $groupLink") @@ -6948,6 +7086,8 @@ data class CreatedConnLink(val connFullLink: String, val connShortLink: String?) fun simplexChatUri(short: Boolean): String = if (short) connShortLink ?: simplexChatLink(connFullLink) else simplexChatLink(connFullLink) + + val cmdString: String get() = connFullLink + (if (connShortLink == null) "" else " $connShortLink") } fun simplexChatLink(uri: String): String = @@ -6960,6 +7100,29 @@ sealed class OwnerVerification { @Serializable @SerialName("failed") class Failed(val reason: String) : OwnerVerification() } +@Serializable +sealed class SimplexDomainError { + @Serializable @SerialName("noValidLink") object NoValidLink : SimplexDomainError() + @Serializable @SerialName("unknownDomain") object UnknownDomain : SimplexDomainError() +} + +data class ConnectionPlanResult( + val connLink: CreatedConnLink, + val planSimplexName: SimplexNameInfo?, + val otherSimplexName: SimplexNameInfo?, + val connectionPlan: ConnectionPlan, +) + +// APIConnectPlan resolution scope; PRMNever is local-store-only (no network), used for per-keystroke name search +enum class PlanResolveMode { + PRMAllGroups, PRMUnknown, PRMNever; + val cmdString: String get() = when (this) { + PRMAllGroups -> "allGroups" + PRMUnknown -> "unknown" + PRMNever -> "never" + } +} + @Serializable sealed class ConnectionPlan { @Serializable @SerialName("invitationLink") class InvitationLink(val invitationLinkPlan: InvitationLinkPlan): ConnectionPlan() @@ -7297,6 +7460,8 @@ sealed class ChatErrorType { is ChatStoreChanged -> "chatStoreChanged" is ConnectionPlanChatError -> "connectionPlan" is InvalidConnReq -> "invalidConnReq" + is SimplexDomainNotReady -> "simplexDomainNotReady" + is NotResolvedLocally -> "notResolvedLocally" is UnsupportedConnReq -> "unsupportedConnReq" is InvalidChatMessage -> "invalidChatMessage" is ConnReqMessageProhibited -> "connReqMessageProhibited" @@ -7379,6 +7544,8 @@ sealed class ChatErrorType { @Serializable @SerialName("chatStoreChanged") object ChatStoreChanged: ChatErrorType() @Serializable @SerialName("connectionPlan") class ConnectionPlanChatError(val connectionPlan: ConnectionPlan): ChatErrorType() @Serializable @SerialName("invalidConnReq") object InvalidConnReq: ChatErrorType() + @Serializable @SerialName("simplexDomainNotReady") class SimplexDomainNotReady(val simplexDomain: SimplexDomain, val simplexDomainError: SimplexDomainError): ChatErrorType() + @Serializable @SerialName("notResolvedLocally") object NotResolvedLocally: ChatErrorType() @Serializable @SerialName("unsupportedConnReq") object UnsupportedConnReq: ChatErrorType() @Serializable @SerialName("invalidChatMessage") class InvalidChatMessage(val connection: Connection, val message: String): ChatErrorType() @Serializable @SerialName("connReqMessageProhibited") object ConnReqMessageProhibited: ChatErrorType() @@ -7647,6 +7814,7 @@ sealed class AgentErrorType { is INTERNAL -> "INTERNAL $internalErr" is CRITICAL -> "CRITICAL $offerRestart $criticalErr" is INACTIVE -> "INACTIVE" + is NO_NAME_SERVERS -> "NO_NAME_SERVERS" } @Serializable @SerialName("CMD") class CMD(val cmdErr: CommandErrorType, val errContext: String): AgentErrorType() @Serializable @SerialName("CONN") class CONN(val connErr: ConnectionErrorType, val errContext: String): AgentErrorType() @@ -7661,6 +7829,19 @@ sealed class AgentErrorType { @Serializable @SerialName("INTERNAL") class INTERNAL(val internalErr: String): AgentErrorType() @Serializable @SerialName("CRITICAL") data class CRITICAL(val offerRestart: Boolean, val criticalErr: String): AgentErrorType() @Serializable @SerialName("INACTIVE") object INACTIVE: AgentErrorType() + @Serializable @SerialName("NO_NAME_SERVERS") object NO_NAME_SERVERS: AgentErrorType() +} + +@Serializable +sealed class NameErrorType { + val string: String get() = when (this) { + is NO_RESOLVER -> "NO_RESOLVER" + is NOT_FOUND -> "NOT_FOUND" + is RESOLVER -> "RESOLVER $resolverErr" + } + @Serializable @SerialName("NO_RESOLVER") object NO_RESOLVER: NameErrorType() + @Serializable @SerialName("NOT_FOUND") object NOT_FOUND: NameErrorType() + @Serializable @SerialName("RESOLVER") class RESOLVER(val resolverErr: String): NameErrorType() } @Serializable @@ -7730,6 +7911,7 @@ sealed class SMPErrorType { is LARGE_MSG -> "LARGE_MSG" is EXPIRED -> "EXPIRED" is INTERNAL -> "INTERNAL" + is NAME -> "NAME ${nameErr.string}" } @Serializable @SerialName("BLOCK") class BLOCK: SMPErrorType() @Serializable @SerialName("SESSION") class SESSION: SMPErrorType() @@ -7744,6 +7926,7 @@ sealed class SMPErrorType { @Serializable @SerialName("LARGE_MSG") class LARGE_MSG: SMPErrorType() @Serializable @SerialName("EXPIRED") class EXPIRED: SMPErrorType() @Serializable @SerialName("INTERNAL") class INTERNAL: SMPErrorType() + @Serializable @SerialName("NAME") class NAME(val nameErr: NameErrorType): SMPErrorType() } @Serializable diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/ChatInfoView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/ChatInfoView.kt index a099bf333b..e43cc357a0 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/ChatInfoView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/ChatInfoView.kt @@ -757,6 +757,20 @@ fun ChatInfoHeader(cInfo: ChatInfo, contact: Contact) { modifier = Modifier.combinedClickable(onClick = copyDisplayName, onLongClick = copyDisplayName).onRightClick(copyDisplayName) ) ChatInfoDescription(cInfo, displayName, copyNameToClipboard) + val domain = contact.profile.contactDomain + if (domain != null && (contact.profile.contactDomainVerified != null || domain.proof != null)) { + SimplexNameView( + simplexName = "@${domain.shortName}", + verified = contact.profile.contactDomainVerified, + verify = { + val rhId = chatModel.remoteHostId() + chatModel.controller.apiVerifyContactDomain(rhId, contact.contactId)?.let { (ct, reason) -> + chatModel.chatsContext.updateContact(rhId, ct) + ct.profile.contactDomainVerified to reason + } + } + ) + } } } diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/ChatView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/ChatView.kt index cc9e71354c..4a3bfe4208 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/ChatView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/ChatView.kt @@ -208,7 +208,7 @@ fun ChatView( withBGApi { setGroupMembers(chatRh, cInfo.groupInfo, chatModel) if (cInfo.groupInfo.membership.memberRole == GroupMemberRole.Owner) { - val relays = chatModel.controller.apiGetGroupRelays(cInfo.groupInfo.groupId) + val relays = chatModel.controller.apiGetGroupRelays(chatRh, cInfo.groupInfo.groupId) withContext(Dispatchers.Main) { ChannelRelaysModel.set(cInfo.groupInfo.groupId, relays) } @@ -2084,7 +2084,7 @@ fun BoxScope.ChatItemsList( } Row( Modifier - .padding(start = 8.dp + (MEMBER_IMAGE_SIZE * fontSizeSqrtMultiplier) + 4.dp, end = if (voiceWithTransparentBack || chatInfo.isChannel) 12.dp else adjustTailPaddingOffset(66.dp, start = false)) + .padding(start = if (chatInfo.isChannel) 12.dp else 8.dp + (MEMBER_IMAGE_SIZE * fontSizeSqrtMultiplier) + 4.dp, end = if (voiceWithTransparentBack || chatInfo.isChannel) 12.dp else adjustTailPaddingOffset(66.dp, start = false)) .chatItemOffset(cItem, itemSeparation.largeGap, revealed = revealed.value) .then(swipeableOrSelectionModifier) ) { @@ -2167,7 +2167,7 @@ fun BoxScope.ChatItemsList( } Row( Modifier - .padding(start = 8.dp + (MEMBER_IMAGE_SIZE * fontSizeSqrtMultiplier) + 4.dp, end = if (voiceWithTransparentBack || chatInfo.isChannel) 12.dp else adjustTailPaddingOffset(66.dp, start = false)) + .padding(start = if (chatInfo.isChannel) 12.dp else 8.dp + (MEMBER_IMAGE_SIZE * fontSizeSqrtMultiplier) + 4.dp, end = if (voiceWithTransparentBack || chatInfo.isChannel) 12.dp else adjustTailPaddingOffset(66.dp, start = false)) .chatItemOffset(cItem, itemSeparation.largeGap, revealed = revealed.value) .then(swipeableOrSelectionModifier) ) { diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/ComposeView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/ComposeView.kt index 21290b99b8..c37aa0a77f 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/ComposeView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/ComposeView.kt @@ -1203,8 +1203,9 @@ fun ComposeView( } val ownerRelayState = ownerRelayState(chat, chatModel) + val subscriberRelayState = subscriberRelayState(chat, chatModel) - val userCantSendReason = rememberUpdatedState(chat.chatInfo.userCantSendReason(ownerRelayState?.noActiveRelays == true)) + val userCantSendReason = rememberUpdatedState(chat.chatInfo.userCantSendReason((ownerRelayState?.noActiveRelays ?: subscriberRelayState?.noActiveRelays) == true)) val sendMsgEnabled = rememberUpdatedState(userCantSendReason.value == null) val nextSendGrpInv = rememberUpdatedState(chat.nextSendGrpInv) @@ -1575,18 +1576,12 @@ fun ComposeView( } } } else { - val hostnames = (chatModel.channelRelayHostnames[gInfo.groupId] ?: emptyList()).sorted() - val relayMembers = chatModel.groupMembers.value - .filter { it.memberRole == GroupMemberRole.Relay && it.memberStatus !in listOf(GroupMemberStatus.MemRemoved, GroupMemberStatus.MemGroupDeleted) } - .sortedBy { hostFromRelayLink(it.relayLink ?: "") } - val showProgress = !gInfo.nextConnectPrepared || composeState.value.inProgress - val removedCount = relayMembers.count { relayMemberRemoved(it.memberStatus) } - val connectedCount = relayMembers.count { !relayMemberRemoved(it.memberStatus) && it.activeConn?.connStatus == ConnStatus.Ready && it.activeConn?.connFailedErr == null } - val failedCount = relayMembers.count { !relayMemberRemoved(it.memberStatus) && it.activeConn?.connFailedErr != null } - val resolvedCount = connectedCount + removedCount + failedCount - val total = if (relayMembers.isNotEmpty()) relayMembers.size else hostnames.size - if (total == 0 || removedCount + failedCount > 0 || resolvedCount < total) { - SubscriberChannelRelayBar(hostnames, relayMembers, connectedCount, removedCount, failedCount, total, showProgress, relayListExpanded) + subscriberRelayState?.let { s -> + val showProgress = !gInfo.nextConnectPrepared || composeState.value.inProgress + val resolvedCount = s.connectedCount + s.removedCount + s.failedCount + if (s.total == 0 || s.removedCount + s.failedCount > 0 || resolvedCount < s.total) { + SubscriberChannelRelayBar(s.hostnames, s.relayMembers, s.connectedCount, s.removedCount, s.failedCount, s.total, showProgress, relayListExpanded) + } } } } @@ -2052,6 +2047,33 @@ private data class OwnerRelayState( val noActiveRelays: Boolean ) +private fun subscriberRelayState(chat: Chat, chatModel: ChatModel): SubscriberRelayState? { + val gInfo = (chat.chatInfo as? ChatInfo.Group)?.groupInfo ?: return null + if (!gInfo.useRelays || gInfo.membership.memberRole == GroupMemberRole.Owner || + gInfo.membership.memberStatus in listOf(GroupMemberStatus.MemRejected, GroupMemberStatus.MemLeft, GroupMemberStatus.MemRemoved, GroupMemberStatus.MemGroupDeleted) + ) return null + val hostnames = (chatModel.channelRelayHostnames[gInfo.groupId] ?: emptyList()).sorted() + val relayMembers = chatModel.groupMembers.value + .filter { it.memberRole == GroupMemberRole.Relay && it.memberStatus !in listOf(GroupMemberStatus.MemRemoved, GroupMemberStatus.MemGroupDeleted) } + .sortedBy { hostFromRelayLink(it.relayLink ?: "") } + val removedCount = relayMembers.count { relayMemberRemoved(it.memberStatus) } + val connectedCount = relayMembers.count { !relayMemberRemoved(it.memberStatus) && it.activeConn?.connStatus == ConnStatus.Ready && it.activeConn?.connFailedErr == null } + val failedCount = relayMembers.count { !relayMemberRemoved(it.memberStatus) && it.activeConn?.connFailedErr != null } + val total = if (relayMembers.isNotEmpty()) relayMembers.size else hostnames.size + val noActiveRelays = connectedCount == 0 && (removedCount + failedCount) == total + return SubscriberRelayState(hostnames, relayMembers, connectedCount, removedCount, failedCount, total, noActiveRelays) +} + +private data class SubscriberRelayState( + val hostnames: List, + val relayMembers: List, + val connectedCount: Int, + val removedCount: Int, + val failedCount: Int, + val total: Int, + val noActiveRelays: Boolean +) + private fun relayMemberRemoved(status: GroupMemberStatus?): Boolean = status in listOf(GroupMemberStatus.MemLeft, GroupMemberStatus.MemRemoved, GroupMemberStatus.MemGroupDeleted) diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/SimplexNameView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/SimplexNameView.kt new file mode 100644 index 0000000000..ccee6a9035 --- /dev/null +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/SimplexNameView.kt @@ -0,0 +1,94 @@ +package chat.simplex.common.views.chat + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.material.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.unit.dp +import chat.simplex.common.model.SimplexNameInfo +import chat.simplex.common.platform.* +import chat.simplex.common.ui.theme.DEFAULT_PADDING_HALF +import chat.simplex.common.views.helpers.* +import chat.simplex.res.MR +import dev.icerock.moko.resources.compose.painterResource +import dev.icerock.moko.resources.compose.stringResource +import kotlinx.coroutines.* + +// Renders a contact's / channel's SimpleX name with its 3-state verification indicator. +// `verification`: null = not attempted, false = failed, true = verified. +// `verify` runs the verify API, updates the model and returns (newVerification, failureReason); +// null on network error. With `autoVerify`, it runs once on open when state is null. +@Composable +fun SimplexNameView( + simplexName: String, + verified: Boolean?, + verify: suspend () -> Pair? +) { + val scope = rememberCoroutineScope() + val inFlight = remember { mutableStateOf(false) } + val showSpinner = remember { mutableStateOf(false) } + + fun runVerify(manual: Boolean) { + if (inFlight.value) return + inFlight.value = true + scope.launch { + // delay the spinner so a fast result on open doesn't flash it + val spinner = launch { delay(300); if (inFlight.value) showSpinner.value = true } + val res = try { + verify() + } catch (e: Exception) { + Log.e(TAG, "verify SimplexName: ${e.stackTraceToString()}") + null + } + spinner.cancel() + inFlight.value = false + showSpinner.value = false + if (res != null) { + val (newV, reason) = res + // show the reason on a manual run, or on an inconclusive auto run (state stayed null) + if (reason != null && (manual || newV == null)) { + AlertManager.shared.showAlertMsg(generalGetString(MR.strings.simplex_name_not_verified), reason) + } + } + } + } + + LaunchedEffect(Unit) { + if (chatModel.controller.appPrefs.privacyVerifySimplexNames.get() && verified == null) runVerify(manual = false) + } + + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.padding(top = DEFAULT_PADDING_HALF) + ) { + Text( + simplexName, + style = MaterialTheme.typography.body2.copy( + color = if (verified == true) MaterialTheme.colors.primary else MaterialTheme.colors.secondary, + fontFamily = if (verified == true) FontFamily.Default else FontFamily.Monospace + ) + ) + when { + showSpinner.value -> + CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp, color = MaterialTheme.colors.secondary) + verified == true -> + Icon(painterResource(MR.images.ic_check_filled), null, Modifier.size(18.dp), tint = MaterialTheme.colors.onBackground) + verified == false -> + Icon( + painterResource(MR.images.ic_close), null, tint = Color.Red, + modifier = Modifier.size(18.dp).clickable { runVerify(manual = true) } + ) + else -> + Text( + stringResource(MR.strings.verify_simplex_name_action), + color = MaterialTheme.colors.primary, + modifier = Modifier.clickable { runVerify(manual = true) } + ) + } + } +} diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/group/AddGroupRelayView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/group/AddGroupRelayView.kt index 1ed75bd2a2..95ce003caa 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/group/AddGroupRelayView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/group/AddGroupRelayView.kt @@ -31,6 +31,7 @@ data class AvailableRelay( @Composable fun AddGroupRelayView( + rhId: Long?, groupInfo: GroupInfo, existingRelayIds: Set, onRelayAdded: () -> Unit, @@ -46,7 +47,7 @@ fun AddGroupRelayView( LaunchedEffect(Unit) { try { - val servers = ChatController.getUserServers(null) + val servers = ChatController.getUserServers(rhId) if (servers != null) { val relays = mutableListOf() for (op in servers) { @@ -80,7 +81,7 @@ fun AddGroupRelayView( if (relayIds.isEmpty()) return@AddGroupRelayLayout isAdding = true scope.launch { - addSelectedRelays(groupInfo, relayIds, selectedRelayIds, availableRelays, onRelayAdded, close) { newSelectedIds, newAvailableRelays -> + addSelectedRelays(rhId, groupInfo, relayIds, selectedRelayIds, availableRelays, onRelayAdded, close) { newSelectedIds, newAvailableRelays -> selectedRelayIds = newSelectedIds availableRelays = newAvailableRelays isAdding = false @@ -183,6 +184,7 @@ private fun AddRelaysButton(onClick: () -> Unit, disabled: Boolean) { } private suspend fun addSelectedRelays( + rhId: Long?, groupInfo: GroupInfo, relayIds: List, selectedRelayIds: Set, @@ -192,7 +194,7 @@ private suspend fun addSelectedRelays( updateState: (Set, List) -> Unit ) { try { - val result = ChatController.apiAddGroupRelays(groupInfo.groupId, relayIds) + val result = ChatController.apiAddGroupRelays(rhId, groupInfo.groupId, relayIds) if (result == null) { updateState(selectedRelayIds, availableRelays) return diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/group/ChannelRelaysView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/group/ChannelRelaysView.kt index d7ffde71c8..60cc19bb1b 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/group/ChannelRelaysView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/group/ChannelRelaysView.kt @@ -37,7 +37,7 @@ fun ChannelRelaysView( LaunchedEffect(Unit) { setGroupMembers(rhId, groupInfo, chatModel) if (groupInfo.isOwner) { - val relays = chatModel.controller.apiGetGroupRelays(groupInfo.groupId) + val relays = chatModel.controller.apiGetGroupRelays(rhId, groupInfo.groupId) ChannelRelaysModel.set(groupId = groupInfo.groupId, groupRelays = relays) } } @@ -114,6 +114,7 @@ private fun ChannelRelaysLayout( val existingRelayIds = groupRelays.mapNotNull { it.userChatRelay.chatRelayId }.toSet() ModalManager.end.showModalCloseable(showClose = true, cardScreen = true) { close -> AddGroupRelayView( + rhId = rhId, groupInfo = groupInfo, existingRelayIds = existingRelayIds, onRelayAdded = { withBGApi { setGroupMembers(rhId, groupInfo, chatModel) } }, diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/group/ChannelWebPageView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/group/ChannelWebPageView.kt index 98067e49dd..18a944f671 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/group/ChannelWebPageView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/group/ChannelWebPageView.kt @@ -49,7 +49,7 @@ fun ChannelWebPageView( val trimmedPage = webPage.value.trim() val newAccess = PublicGroupAccess( groupWebPage = trimmedPage.ifEmpty { null }, - groupDomain = access?.groupDomain, + groupDomainClaim = access?.groupDomainClaim, domainWebPage = access?.domainWebPage ?: false, allowEmbedding = allowEmbedding.value ) @@ -81,7 +81,7 @@ fun ChannelWebPageView( } LaunchedEffect(Unit) { - val relays = chatModel.controller.apiGetGroupRelays(groupInfo.groupId) + val relays = chatModel.controller.apiGetGroupRelays(rhId, groupInfo.groupId) groupRelays.clear() groupRelays.addAll(relays) } diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/group/GroupChatInfoView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/group/GroupChatInfoView.kt index 2b1c7bcd09..c54ca148d4 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/group/GroupChatInfoView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/group/GroupChatInfoView.kt @@ -178,6 +178,27 @@ fun ModalData.GroupChatInfoView( manageWebPage = { ModalManager.end.showCustomModal { close -> ChannelWebPageView(rhId, groupInfo, chatModel, close) } }, + setSimplexName = { + ModalManager.end.showCustomModal { close -> + val domain = groupInfo.groupProfile.publicGroup?.publicGroupAccess?.groupDomainClaim?.shortName + SetSimplexDomainView( + title = generalGetString(MR.strings.set_simplex_name), + footer = generalGetString(MR.strings.set_channel_simplex_name_footer), + placeholder = "#channelname.testing", + simplexName = if (domain == null) "" else "#$domain", + save = { domain -> + val access = groupInfo.groupProfile.publicGroup?.publicGroupAccess ?: PublicGroupAccess() + val newAccess = access.copy(groupDomainClaim = domain?.let { SimplexDomainClaim(it) }) + val gInfo = chatModel.controller.apiSetPublicGroupAccess(rhId, groupInfo.groupId, newAccess) + if (gInfo != null) { + withContext(Dispatchers.Main) { chatModel.chatsContext.updateGroup(rhId, gInfo) } + true + } else false + }, + close = close + ) + } + }, onSearchClicked = onSearchClicked, deletingItems = deletingItems ) @@ -510,6 +531,7 @@ fun ModalData.GroupChatInfoLayout( leaveGroup: () -> Unit, manageGroupLink: () -> Unit, manageWebPage: () -> Unit, + setSimplexName: () -> Unit, close: () -> Unit = { ModalManager.closeAllModalsEverywhere()}, onSearchClicked: () -> Unit, deletingItems: State @@ -616,6 +638,12 @@ fun ModalData.GroupChatInfoLayout( if (groupInfo.isOwner && groupLink != null) { anyTopSectionRowShow = true ChannelLinkButton(manageGroupLink) + SettingsActionItem( + painterResource(MR.images.ic_tag), + stringResource(MR.strings.simplex_name), + setSimplexName, + iconColor = MaterialTheme.colors.secondary + ) } else if (channelLink != null) { anyTopSectionRowShow = true ChannelLinkQRCodeSection(channelLink) @@ -945,6 +973,21 @@ private fun GroupChatInfoHeader(cInfo: ChatInfo, groupInfo: GroupInfo) { modifier = Modifier.combinedClickable(onClick = copyDisplayName, onLongClick = copyDisplayName).onRightClick(copyDisplayName) ) ChatInfoDescription(cInfo, displayName, copyNameToClipboard) + val access = groupInfo.groupProfile.publicGroup?.publicGroupAccess + val domain = access?.groupDomainClaim?.shortName + if (domain != null && (groupInfo.groupDomainVerified != null || access.groupDomainClaim?.proof != null)) { + SimplexNameView( + simplexName = "#${domain}", + verified = groupInfo.groupDomainVerified, + verify = { + val rhId = chatModel.remoteHostId() + chatModel.controller.apiVerifyGroupDomain(rhId, groupInfo.groupId)?.let { (gInfo, reason) -> + chatModel.chatsContext.updateGroup(rhId, gInfo) + gInfo.groupDomainVerified to reason + } + } + ) + } val webPage = groupInfo.groupProfile.publicGroup?.publicGroupAccess?.groupWebPage if (webPage != null) { val uriHandler = LocalUriHandler.current @@ -1436,6 +1479,7 @@ fun PreviewGroupChatInfoLayout() { manageGroupLink = {}, manageWebPage = {}, onSearchClicked = {}, + setSimplexName = {}, deletingItems = remember { mutableStateOf(true) } ) } diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIFileView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIFileView.kt index 02bee37c24..b2b89ca041 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIFileView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIFileView.kt @@ -15,7 +15,9 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalUriHandler +import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.* import dev.icerock.moko.resources.compose.painterResource import dev.icerock.moko.resources.compose.stringResource @@ -30,7 +32,10 @@ import java.net.URI @Composable fun CIFileView( file: CIFile?, - edited: Boolean, + meta: CIMeta, + chatTTL: Int?, + showViaProxy: Boolean, + showTimestamp: Boolean, showMenu: MutableState, smallView: Boolean = false, senderProfile: LocalProfile?, @@ -202,10 +207,13 @@ fun CIFileView( ) { fileIndicator() if (!smallView) { - val metaReserve = if (edited) - " " - else - " " + val secondaryColor = MaterialTheme.colors.secondary + val encrypted = if (file?.fileSource == null) null else file.fileSource.cryptoArgs != null + val metaReserve = buildAnnotatedString { + withStyle(reserveTimestampStyle) { + append(reserveSpaceForMeta(meta, chatTTL, encrypted, secondaryColor = secondaryColor, showViaProxy = showViaProxy, showTimestamp = showTimestamp)) + } + } if (file != null) { Column { Text( @@ -213,8 +221,11 @@ fun CIFileView( maxLines = 1 ) Text( - formatBytes(file.fileSize) + metaReserve, - color = MaterialTheme.colors.secondary, + buildAnnotatedString { + append(formatBytes(file.fileSize)) + append(metaReserve) + }, + color = secondaryColor, fontSize = 14.sp, maxLines = 1 ) diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIImageView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIImageView.kt index 65dbe7cb02..ef561fc3e0 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIImageView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIImageView.kt @@ -176,7 +176,7 @@ fun CIImageView( .then( if (!smallView) { val w = if (previewBitmap.width * 0.97 <= previewBitmap.height) imageViewFullWidth() * 0.75f else DEFAULT_MAX_IMAGE_WIDTH - Modifier.width(w).aspectRatio((previewBitmap.width.toFloat() / previewBitmap.height.toFloat()).coerceIn(1f / 2.33f, 2.33f)) + Modifier.width(w).height(w * (previewBitmap.height.toFloat() / previewBitmap.width.toFloat()).coerceAtMost(2.33f)) } else Modifier ) .desktopModifyBlurredState(!smallView, blurred, showMenu), diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/FramedItemView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/FramedItemView.kt index 5c07fe3abf..2e1db8928e 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/FramedItemView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/FramedItemView.kt @@ -201,7 +201,7 @@ fun FramedItemView( @Composable fun ciFileView(ci: ChatItem, text: String) { - CIFileView(ci.file, ci.meta.itemEdited, showMenu, false, ciSenderProfile(ci, chatInfo), receiveFile) + CIFileView(ci.file, ci.meta, chatTTL, showViaProxy, showTimestamp, showMenu, false, ciSenderProfile(ci, chatInfo), receiveFile) if (text != "" || ci.meta.isLive) { CIMarkdownText(chatsCtx, ci, chat, chatTTL, linkMode = linkMode, uriHandler, showViaProxy = showViaProxy, showTimestamp = showTimestamp) } diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TextItemView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TextItemView.kt index c9f7d96f39..c7c96cd731 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TextItemView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TextItemView.kt @@ -338,13 +338,10 @@ fun MarkdownText ( withAnnotation("SIMPLEX_URL") { a -> uriHandler.openVerifiedSimplexUri(a.item) } withAnnotation("SIMPLEX_NAME") { a -> val idx = a.item.toIntOrNull() - val nameInfo = (idx?.let { formattedText.getOrNull(it) }?.format as? Format.SimplexName)?.nameInfo - val (title, msg) = if (nameInfo?.nameType == SimplexNameType.contact) { - generalGetString(MR.strings.unsupported_contact_name) to generalGetString(MR.strings.contact_name_requires_newer_app_version) - } else { - generalGetString(MR.strings.unsupported_channel_name) to generalGetString(MR.strings.channel_name_requires_newer_app_version) - } - AlertManager.shared.showAlertMsg(title, "$msg ${generalGetString(MR.strings.please_upgrade_the_app)}") + val nameText = idx?.let { formattedText.getOrNull(it) }?.text + // The name string is routed through the same connect path as a + // link; planAndConnect resolves it on the core (name target). + if (nameText != null) uriHandler.openVerifiedSimplexUri(nameText) } } if (hasSecrets) { diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chatlist/ChatListView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chatlist/ChatListView.kt index 3012525f9b..439d1af189 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chatlist/ChatListView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chatlist/ChatListView.kt @@ -49,6 +49,7 @@ import dev.icerock.moko.resources.ImageResource import dev.icerock.moko.resources.StringResource import kotlinx.coroutines.* import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.serialization.json.Json import kotlin.time.Duration.Companion.seconds @@ -745,7 +746,7 @@ fun connectIfOpenedViaUri(rhId: Long?, uri: String, chatModel: ChatModel) { } @Composable -private fun ChatListSearchBar(listState: LazyListState, searchText: MutableState, searchShowingSimplexLink: MutableState, searchChatFilteredBySimplexLink: MutableState) { +private fun ChatListSearchBar(listState: LazyListState, searchText: MutableState, searchShowingSimplexLink: MutableState, searchChatFilteredBySimplexLink: MutableState>, connectNameCandidate: MutableState) { Box { Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { val focusRequester = remember { FocusRequester() } @@ -763,6 +764,8 @@ private fun ChatListSearchBar(listState: LazyListState, searchText: MutableState searchText = searchText, enabled = !remember { searchShowingSimplexLink }.value, trailingContent = null, + // the clear button must line up with the filter icon it replaces, so no reduction here + reducedCloseButtonPadding = 0.dp, ) { searchText.value = searchText.value.copy(it) } @@ -791,17 +794,35 @@ private fun ChatListSearchBar(listState: LazyListState, searchText: MutableState LaunchedEffect(Unit) { snapshotFlow { searchText.value.text } .distinctUntilChanged() - .collect { - when (val target = strConnectTarget(it.trim())) { - is ConnectTarget.Link -> { - hideKeyboard(view) - searchText.value = searchText.value.copy(target.linkText, selection = TextRange.Zero) - searchShowingSimplexLink.value = true - searchChatFilteredBySimplexLink.value = null - connect(target.text, searchChatFilteredBySimplexLink) { searchText.value = TextFieldValue() } - } - is ConnectTarget.Name -> showUnsupportedNameAlert(target.nameInfo) - null -> if (!searchShowingSimplexLink.value || it.isEmpty()) { + .collectLatest { + val target = strConnectTarget(it.trim()) + if (target is ConnectTarget.Link) { + hideKeyboard(view) + searchText.value = searchText.value.copy(target.linkText, selection = TextRange.Zero) + searchShowingSimplexLink.value = true + searchChatFilteredBySimplexLink.value = emptySet() + connectNameCandidate.value = null + connect(target.text, searchChatFilteredBySimplexLink) { searchText.value = TextFieldValue() } + } else { + val candidate = nameSearchCandidate(it.trim()) + connectNameCandidate.value = candidate + // clear the previous match immediately so the list falls back to text search during the debounce, + // instead of showing a stale filtered chat while the new search runs + searchChatFilteredBySimplexLink.value = emptySet() + if (candidate != null) { + // resolve the name locally on each keystroke, debounced; collectLatest cancels the in-flight + // search when the next keystroke arrives. A bare name can be a contact or a channel, so search + // both and filter every known chat found; drop the row only when both types are already known. + delay(NAME_SEARCH_DEBOUNCE_MS) + val rhId = chatModel.remoteHostId() + val inProgress = mutableStateOf(false) // background search: no spinner, no error alerts + val targets = if (candidate.startsWith("@") || candidate.startsWith("#")) listOf(candidate) else listOf("@$candidate", "#$candidate") + val ids = targets.mapNotNull { name -> + knownChatId(rhId, chatModel.controller.apiConnectPlan(rhId, name, PlanResolveMode.PRMNever, inProgress = inProgress)) + } + searchChatFilteredBySimplexLink.value = ids.toSet() + if (ids.size == targets.size) connectNameCandidate.value = null + } else if (!searchShowingSimplexLink.value || it.isEmpty()) { if (it.isNotEmpty()) { focusRequester.requestFocus() } else { @@ -813,7 +834,7 @@ private fun ChatListSearchBar(listState: LazyListState, searchText: MutableState } } searchShowingSimplexLink.value = false - searchChatFilteredBySimplexLink.value = null + searchChatFilteredBySimplexLink.value = emptySet() } } } @@ -824,13 +845,13 @@ private fun ChatListSearchBar(listState: LazyListState, searchText: MutableState } } -private fun connect(link: String, searchChatFilteredBySimplexLink: MutableState, cleanup: (() -> Unit)?) { +private fun connect(link: String, searchChatFilteredBySimplexLink: MutableState>, cleanup: (() -> Unit)?) { withBGApi { planAndConnect( chatModel.remoteHostId(), link, - filterKnownContact = { searchChatFilteredBySimplexLink.value = it.id }, - filterKnownGroup = { searchChatFilteredBySimplexLink.value = it.id }, + filterKnownContact = { searchChatFilteredBySimplexLink.value = setOf(it.id) }, + filterKnownGroup = { searchChatFilteredBySimplexLink.value = setOf(it.id) }, close = null, cleanup = cleanup, ) @@ -917,7 +938,8 @@ private fun BoxScope.ChatList(searchText: MutableState, listStat // which is related to [derivedStateOf]. Using safe alternative instead // val chats by remember(search, showUnreadAndFavorites) { derivedStateOf { filteredChats(showUnreadAndFavorites, search, allChats.toList()) } } val searchShowingSimplexLink = remember { mutableStateOf(false) } - val searchChatFilteredBySimplexLink = remember { mutableStateOf(null) } + val searchChatFilteredBySimplexLink = remember { mutableStateOf>(emptySet()) } + val connectNameCandidate = remember { mutableStateOf(null) } val chats = filteredChats(searchShowingSimplexLink, searchChatFilteredBySimplexLink, searchText.value.text, allChats.value.toList(), activeFilter.value) val topPaddingToContent = topPaddingToContent(false) val blankSpaceSize = if (oneHandUI.value) WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding() + AppBarHeight * fontSizeSqrtMultiplier else topPaddingToContent @@ -950,13 +972,23 @@ private fun BoxScope.ChatList(searchText: MutableState, listStat if (oneHandUI.value) { Column(Modifier.consumeWindowInsets(WindowInsets.navigationBars).consumeWindowInsets(PaddingValues(bottom = AppBarHeight))) { Divider() - TagsView(searchText) - ChatListSearchBar(listState, searchText, searchShowingSimplexLink, searchChatFilteredBySimplexLink) + // bottom toolbar: search bar below, so on desktop the connect row goes below the tags + TagsOrConnectByName(searchText, connectNameCandidate) { candidate -> + TagsView(searchText) + Divider() + ConnectByNameRow(candidate, searchText, connectNameCandidate, close = null) + } + ChatListSearchBar(listState, searchText, searchShowingSimplexLink, searchChatFilteredBySimplexLink, connectNameCandidate) Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.ime)) } } else { - ChatListSearchBar(listState, searchText, searchShowingSimplexLink, searchChatFilteredBySimplexLink) - TagsView(searchText) + ChatListSearchBar(listState, searchText, searchShowingSimplexLink, searchChatFilteredBySimplexLink, connectNameCandidate) + // top toolbar: search bar above, so on desktop the connect row goes above the tags + TagsOrConnectByName(searchText, connectNameCandidate) { candidate -> + ConnectByNameRow(candidate, searchText, connectNameCandidate, close = null) + Divider() + TagsView(searchText) + } Divider() } } @@ -1004,6 +1036,105 @@ private fun BoxScope.ChatList(searchText: MutableState, listStat } } +// Default top-level part used to complete a bare name typed in the search field (search field only; +// the message parser and the wire format are unchanged). +private const val DEFAULT_NAME_TLD = "testing" +// Shortest name that offers the button, so it is discoverable but does not flash on a single letter. +private const val MIN_NAME_LENGTH = 2 +// Wait this long after the last keystroke before the local name search runs. +internal const val NAME_SEARCH_DEBOUNCE_MS = 300L + +private val nameLabelRegex = Regex("[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*") +private fun isNameLabel(s: String): Boolean = s.length in 1..63 && nameLabelRegex.matches(s) + +// On-device candidate for connecting by SimpleX name: the string sent to the core to resolve it. +// Mirrors the domain grammar (nameLabelP/mkDomain in SimplexName.hs): an optional @/# prefix, then +// dot-separated ASCII labels; a dotless word is completed with the default top-level part. Returns +// the string to send (keeping @/# so the type is preserved), or null when the text is not a name. +internal fun nameSearchCandidate(str: String): String? { + val text = str.trim() + val prefix = text.firstOrNull()?.takeIf { it == '@' || it == '#' } + val core = if (prefix != null) text.substring(1) else text + val labels = core.split(".") + if (core.isEmpty() || labels.any { !isNameLabel(it) }) return null + return when { + labels.size > 1 -> text // already has a top-level part + core.length >= MIN_NAME_LENGTH -> "${prefix ?: ""}$core.$DEFAULT_NAME_TLD" + else -> null + } +} + +// The chat id a local (PRMNever) search resolved to — a contact, a business, or a channel — or null on a miss. +// The core returns the correct type for @ vs # (getContactToConnect / type-filtered getGroupToConnect), so no +// client-side type check is needed. +internal suspend fun knownChatId(rhId: Long?, result: ConnectionPlanResult?): String? = when (val plan = result?.connectionPlan) { + is ConnectionPlan.ContactAddress -> (plan.contactAddressPlan as? ContactAddressPlan.Known)?.contact?.let { contact -> + // a name-resolved chat may be prepared in the store but not yet listed, so add it (as the tap path does) + if (chatModel.getContactChat(contact.contactId) == null) { + chatModel.chatsContext.addChat(Chat(remoteHostId = rhId, chatInfo = ChatInfo.Direct(contact), chatItems = emptyList())) + } + contact.id + } + is ConnectionPlan.GroupLink -> (when (val g = plan.groupLinkPlan) { + is GroupLinkPlan.Known -> g.groupInfo + is GroupLinkPlan.OwnLink -> g.groupInfo + else -> null + })?.let { gInfo -> + if (chatModel.getGroupChat(gInfo.groupId) == null) { + chatModel.chatsContext.addChat(Chat(remoteHostId = rhId, chatInfo = ChatInfo.Group(gInfo, groupChatScope = null), chatItems = emptyList())) + } + gInfo.id + } + else -> null +} + +// The list tags and the connect-by-name row share one slot. When there is no name, the tags show; on +// mobile the row replaces the tags while shown. On desktop both show, arranged by the caller (which +// knows whether the search bar is above or below), passed as desktopView. +@Composable +private fun TagsOrConnectByName( + searchText: MutableState, + connectNameCandidate: MutableState, + desktopView: @Composable (candidate: String) -> Unit, +) { + val candidate = connectNameCandidate.value + when { + candidate == null -> TagsView(searchText) + !appPlatform.isDesktop -> ConnectByNameRow(candidate, searchText, connectNameCandidate, close = null) + else -> desktopView(candidate) + } +} + +@Composable +internal fun ConnectByNameRow(name: String, searchText: MutableState, connectNameCandidate: MutableState, close: (() -> Unit)?) { + val view = LocalMultiplatformView() + Row( + Modifier + .fillMaxWidth() + .clickable { + hideKeyboard(view) + withBGApi { + planAndConnect( + chatModel.remoteHostId(), + name, + close = close, + cleanup = { + searchText.value = TextFieldValue() + connectNameCandidate.value = null + }, + ) + } + } + .padding(vertical = DEFAULT_PADDING_HALF), + verticalAlignment = Alignment.CenterVertically + ) { + // icon and text aligned with the search bar's icon and text (same paddings and icon size) + val icon = if (name.startsWith("@")) MR.images.ic_at else MR.images.ic_tag + Icon(painterResource(icon), null, Modifier.padding(start = DEFAULT_PADDING, end = DEFAULT_PADDING_HALF).size(22.dp * fontSizeSqrtMultiplier), tint = MaterialTheme.colors.primary) + Text(String.format(generalGetString(MR.strings.connect_plan_connect_to_name), name), color = MaterialTheme.colors.primary) + } +} + @Composable private fun NoChatsView(searchText: MutableState) { val activeFilter = remember { chatModel.activeChatTagFilter }.value @@ -1311,14 +1442,14 @@ fun ItemPresetFilterAction( fun filteredChats( searchShowingSimplexLink: State, - searchChatFilteredBySimplexLink: State, + searchChatFilteredBySimplexLink: State>, searchText: String, chats: List, activeFilter: ActiveFilter? = null, ): List { - val linkChatId = searchChatFilteredBySimplexLink.value - return if (linkChatId != null) { - chats.filter { it.id == linkChatId } + val linkChatIds = searchChatFilteredBySimplexLink.value + return if (linkChatIds.isNotEmpty()) { + chats.filter { it.id in linkChatIds } } else { val s = if (searchShowingSimplexLink.value) "" else searchText.trim().lowercase() if (s.isEmpty()) diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chatlist/ChatPreviewView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chatlist/ChatPreviewView.kt index 2c7e443b4d..fbc4c7e336 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chatlist/ChatPreviewView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chatlist/ChatPreviewView.kt @@ -342,7 +342,7 @@ fun ChatPreviewView( } } is MsgContent.MCFile -> SmallContentPreviewFile { - CIFileView(ci.file, false, remember { mutableStateOf(false) }, smallView = true, senderProfile = ciSenderProfile(ci, chat.chatInfo)) { + CIFileView(ci.file, ci.meta, cInfo.timedMessagesTTL, showViaProxy = false, showTimestamp = true, showMenu = remember { mutableStateOf(false) }, smallView = true, senderProfile = ciSenderProfile(ci, chat.chatInfo)) { val user = chatModel.currentUser.value ?: return@CIFileView withBGApi { chatModel.controller.receiveFile(chat.remoteHostId, user, it) } } diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chatlist/ShareListView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chatlist/ShareListView.kt index 96af5337d0..4e58501b19 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chatlist/ShareListView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chatlist/ShareListView.kt @@ -197,7 +197,7 @@ private fun ShareList( val chats by remember(search) { derivedStateOf { val sorted = chatModel.chats.value.toList().filter { it.chatInfo.ready && it.chatInfo.sendMsgEnabled && !(chatModel.sharedContent.value is SharedContent.ChatLink && it.chatInfo is ChatInfo.Local) }.sortedByDescending { it.chatInfo is ChatInfo.Local } - filteredChats(mutableStateOf(false), mutableStateOf(null), search, sorted) + filteredChats(mutableStateOf(false), mutableStateOf>(emptySet()), search, sorted) } } val topPaddingToContent = topPaddingToContent(false) diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/helpers/AlertManager.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/helpers/AlertManager.kt index b4680a4259..f70e4d0048 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/helpers/AlertManager.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/helpers/AlertManager.kt @@ -291,10 +291,13 @@ class AlertManager { profileFullName: String, profileImage: @Composable () -> Unit, profileBadge: LocalBadge? = null, + nameCaption: String? = null, subtitle: String? = null, information: String? = null, confirmText: String? = generalGetString(MR.strings.connect_plan_open_chat), onConfirm: (() -> Unit)? = null, + connectOtherButton: String? = null, + onConnectOther: (() -> Unit)? = null, dismissText: String = generalGetString(MR.strings.cancel_verb), onDismiss: (() -> Unit)? = null, ) { @@ -337,6 +340,17 @@ class AlertManager { modifier = Modifier.fillMaxWidth() ) + if (nameCaption != null) { + Spacer(Modifier.height(DEFAULT_PADDING_HALF)) + Text( + nameCaption, + textAlign = TextAlign.Center, + style = MaterialTheme.typography.body2, + color = MaterialTheme.colors.secondary, + maxLines = 1, + modifier = Modifier.fillMaxWidth() + ) + } if (profileFullName.isNotEmpty() && profileFullName != profileName) { Spacer(Modifier.height(DEFAULT_PADDING_HALF)) Text( @@ -388,6 +402,14 @@ class AlertManager { Text(confirmText) } } + if (connectOtherButton != null && onConnectOther != null) { + TextButton(onClick = { + onConnectOther.invoke() + hideAlert() + }) { + Text(connectOtherButton) + } + } TextButton(onClick = { onDismiss?.invoke() hideAlert() diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/helpers/SearchTextField.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/helpers/SearchTextField.kt index a122ddd885..cc6b1c40a4 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/helpers/SearchTextField.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/helpers/SearchTextField.kt @@ -36,7 +36,7 @@ fun SearchTextField( placeholder: String = stringResource(MR.strings.search_verb), enabled: Boolean = true, trailingContent: @Composable (() -> Unit)? = null, - reducedCloseButtonPadding: Dp = 0.dp, + reducedCloseButtonPadding: Dp = 8.dp, onValueChange: (String) -> Unit ) { val focusRequester = remember { FocusRequester() } @@ -116,7 +116,7 @@ fun SearchTextField( trailingIcon = if (searchText.value.text.isNotEmpty() || trailingContent != null) {{ Row( verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.offset(x = 8.dp) + modifier = Modifier.offset(x = reducedCloseButtonPadding) ) { if (searchText.value.text.isNotEmpty()) { IconButton({ diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/helpers/Section.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/helpers/Section.kt index 9afcdd0b94..5196a144b1 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/helpers/Section.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/helpers/Section.kt @@ -1,4 +1,5 @@ import androidx.compose.foundation.* +import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* @@ -27,7 +28,7 @@ import chat.simplex.common.views.onboarding.SelectableCard import chat.simplex.common.views.usersettings.SettingsActionItemWithContent import chat.simplex.res.MR -private val SectionCardShape = RoundedCornerShape(16.dp) +val SectionCardShape = RoundedCornerShape(16.dp) val CARD_PADDING = 18.dp val ICON_TEXT_SPACING = 8.dp @@ -113,15 +114,18 @@ fun SectionView( iconTint: Color = MaterialTheme.colors.secondary, leadingIcon: Boolean = false, padding: PaddingValues = PaddingValues(), + onIconClick: (() -> Unit)? = null, content: (@Composable ColumnScope.() -> Unit) ) { val card = LocalCardScreen.current Column { val iconSize = with(LocalDensity.current) { 21.sp.toDp() } + val interactionSource = remember { MutableInteractionSource() } + val iconClickable = if (onIconClick != null) Modifier.clickable(interactionSource = interactionSource, indication = ripple(bounded = false, radius = iconSize * 0.75f), onClick = onIconClick) else Modifier Row(Modifier.padding(start = if (card) DEFAULT_PADDING + DEFAULT_PADDING_HALF else DEFAULT_PADDING, bottom = 5.dp), verticalAlignment = Alignment.CenterVertically) { - if (leadingIcon) Icon(icon, null, Modifier.padding(end = DEFAULT_PADDING_HALF).size(iconSize), tint = iconTint) + if (leadingIcon) Icon(icon, null, Modifier.padding(end = DEFAULT_PADDING_HALF).size(iconSize).then(iconClickable), tint = iconTint) Text(title, color = MaterialTheme.colors.secondary, style = MaterialTheme.typography.body2, fontSize = if (card) 14.sp else 12.sp, fontWeight = if (card) FontWeight.Medium else FontWeight.Normal) - if (!leadingIcon) Icon(icon, null, Modifier.padding(start = DEFAULT_PADDING_HALF).size(iconSize), tint = iconTint) + if (!leadingIcon) Icon(icon, null, Modifier.padding(start = DEFAULT_PADDING_HALF).size(iconSize).then(iconClickable), tint = iconTint) } CardColumn(padding) { content() } } diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/helpers/TextEditor.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/helpers/TextEditor.kt index cd40585cad..833f53f2af 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/helpers/TextEditor.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/helpers/TextEditor.kt @@ -31,6 +31,7 @@ fun TextEditor( modifier: Modifier, placeholder: String? = null, contentPadding: PaddingValues = PaddingValues(horizontal = DEFAULT_PADDING), + shape: Shape = RoundedCornerShape(14.dp), isValid: (String) -> Boolean = { true }, focusRequester: FocusRequester? = null, enabled: Boolean = true @@ -53,7 +54,7 @@ fun TextEditor( .fillMaxWidth() .padding(contentPadding) .heightIn(min = 52.dp) - .border(border = BorderStroke(1.dp, strokeColor), shape = RoundedCornerShape(14.dp)), + .border(border = BorderStroke(1.dp, strokeColor), shape = shape), contentAlignment = Alignment.Center, ) { val textFieldModifier = modifier diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/newchat/AddChannelView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/newchat/AddChannelView.kt index b5188178fa..639a5cc78e 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/newchat/AddChannelView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/newchat/AddChannelView.kt @@ -38,7 +38,8 @@ import dev.icerock.moko.resources.compose.painterResource import kotlinx.coroutines.* @Composable -fun AddChannelView(chatModel: ChatModel, close: () -> Unit, closeAll: () -> Unit) { +fun AddChannelView(chatModel: ChatModel, rh: RemoteHostInfo?, close: () -> Unit, closeAll: () -> Unit) { + val rhId = rh?.remoteHostId val view = LocalMultiplatformView() val bottomSheetModalState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden) val scope = rememberCoroutineScope() @@ -56,7 +57,7 @@ fun AddChannelView(chatModel: ChatModel, close: () -> Unit, closeAll: () -> Unit val gInfo = groupInfo.value if (showLinkStep.value && gInfo != null) { - LinkStepView(chatModel, gInfo, groupLink, closeAll) + LinkStepView(chatModel, rhId, gInfo, groupLink, closeAll) } else if (gInfo != null) { ProgressStepView( chatModel, gInfo, groupRelays, relayListExpanded, @@ -65,9 +66,9 @@ fun AddChannelView(chatModel: ChatModel, close: () -> Unit, closeAll: () -> Unit chatModel.creatingChannelId.value = null closeAll() withBGApi { - openGroupChat(null, gInfo.groupId) + openGroupChat(rhId, gInfo.groupId) ModalManager.end.showModalCloseable(showClose = true, cardScreen = true) { close -> - GroupLinkView(chatModel, rhId = null, groupInfo = gInfo, groupLink = groupLink.value, onGroupLinkUpdated = null, creatingGroup = true, isChannel = true, shareGroupInfo = gInfo, close = close) + GroupLinkView(chatModel, rhId = rhId, groupInfo = gInfo, groupLink = groupLink.value, onGroupLinkUpdated = null, creatingGroup = true, isChannel = true, shareGroupInfo = gInfo, close = close) } } } @@ -80,9 +81,9 @@ fun AddChannelView(chatModel: ChatModel, close: () -> Unit, closeAll: () -> Unit closeAll() withBGApi { try { - chatModel.controller.apiDeleteChat(rh = null, type = ChatType.Group, id = gInfo.apiId) + chatModel.controller.apiDeleteChat(rh = rhId, type = ChatType.Group, id = gInfo.apiId) withContext(Dispatchers.Main) { - chatModel.chatsContext.removeChat(null, gInfo.id) + chatModel.chatsContext.removeChat(rhId, gInfo.id) } } catch (e: Exception) { Log.e(TAG, "cancelChannelCreation error: ${e.message}") @@ -93,6 +94,7 @@ fun AddChannelView(chatModel: ChatModel, close: () -> Unit, closeAll: () -> Unit } else { ProfileStepView( chatModel = chatModel, + rhId = rhId, displayName = displayName, profileImage = profileImage, chosenImage = chosenImage, @@ -120,7 +122,7 @@ fun AddChannelView(chatModel: ChatModel, close: () -> Unit, closeAll: () -> Unit creationInProgress.value = true withBGApi { try { - val enabledRelays = chooseRandomRelays() + val enabledRelays = chooseRandomRelays(rhId) val relayIds = enabledRelays.mapNotNull { it.chatRelayId } if (relayIds.isEmpty()) { withContext(Dispatchers.Main) { @@ -130,7 +132,7 @@ fun AddChannelView(chatModel: ChatModel, close: () -> Unit, closeAll: () -> Unit return@withBGApi } val result = chatModel.controller.apiNewPublicGroup( - rh = null, + rh = rhId, incognito = false, relayIds = relayIds, groupProfile = profile @@ -138,7 +140,7 @@ fun AddChannelView(chatModel: ChatModel, close: () -> Unit, closeAll: () -> Unit when (result) { is ChatController.PublicGroupCreationResult.Created -> { withContext(Dispatchers.Main) { - chatModel.chatsContext.updateGroup(rhId = null, result.groupInfo) + chatModel.chatsContext.updateGroup(rhId = rhId, result.groupInfo) chatModel.creatingChannelId.value = result.groupInfo.id groupInfo.value = result.groupInfo groupLink.value = result.groupLink @@ -178,8 +180,8 @@ fun AddChannelView(chatModel: ChatModel, close: () -> Unit, closeAll: () -> Unit private const val maxRelays = 3 -private suspend fun chooseRandomRelays(): List { - val servers = getUserServers(rh = null) ?: return emptyList() +private suspend fun chooseRandomRelays(rhId: Long?): List { + val servers = getUserServers(rh = rhId) ?: return emptyList() // Operator relays are grouped per operator; custom relays (null operator) // are treated independently to maximize trust distribution. val operatorGroups = mutableListOf>() @@ -215,8 +217,8 @@ private suspend fun chooseRandomRelays(): List { return selected } -private suspend fun checkHasRelays(): Boolean { - val servers = try { getUserServers(rh = null) } catch (_: Exception) { null } ?: return false +private suspend fun checkHasRelays(rhId: Long?): Boolean { + val servers = try { getUserServers(rh = rhId) } catch (_: Exception) { null } ?: return false return servers.any { op -> (op.operator?.enabled ?: true) && op.chatRelays.any { it.enabled && !it.deleted && it.chatRelayId != null } @@ -226,6 +228,7 @@ private suspend fun checkHasRelays(): Boolean { @Composable private fun ProfileStepView( chatModel: ChatModel, + rhId: Long?, displayName: MutableState, profileImage: MutableState, chosenImage: MutableState, @@ -239,7 +242,7 @@ private fun ProfileStepView( createChannel: () -> Unit ) { LaunchedEffect(Unit) { - hasRelays.value = checkHasRelays() + hasRelays.value = checkHasRelays(rhId) } ModalBottomSheetLayout( @@ -553,6 +556,7 @@ private fun RelayRow(relay: GroupRelay, connFailed: Boolean) { @Composable private fun LinkStepView( chatModel: ChatModel, + rhId: Long?, gInfo: GroupInfo, groupLink: MutableState, closeAll: () -> Unit @@ -563,14 +567,14 @@ private fun LinkStepView( delay(500) withContext(Dispatchers.Main) { ModalManager.start.closeModals() - openGroupChat(null, gInfo.groupId) + openGroupChat(rhId, gInfo.groupId) } } } ModalView(close = close, showClose = false, cardScreen = true) { GroupLinkView( chatModel = chatModel, - rhId = null, + rhId = rhId, groupInfo = gInfo, groupLink = groupLink.value, onGroupLinkUpdated = { groupLink.value = it }, @@ -660,6 +664,6 @@ fun RelayProgressIndicator(active: Int, total: Int) { @Composable fun PreviewAddChannelView() { SimpleXTheme { - AddChannelView(chatModel = ChatModel, close = {}, closeAll = {}) + AddChannelView(chatModel = ChatModel, rh = null, close = {}, closeAll = {}) } } diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/newchat/ConnectPlan.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/newchat/ConnectPlan.kt index e5dbe01d68..161681c91d 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/newchat/ConnectPlan.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/newchat/ConnectPlan.kt @@ -31,11 +31,6 @@ suspend fun planAndConnect( filterKnownGroup: ((GroupInfo) -> Unit)? = null, ): CompletableDeferred { when (val target = strConnectTarget(shortOrFullLink.trim())) { - is ConnectTarget.Name -> { - showUnsupportedNameAlert(target.nameInfo) - cleanup?.invoke() - return CompletableDeferred(false) - } is ConnectTarget.Link -> { if (target.linkType == SimplexLinkType.relay) { AlertManager.privacySensitive.showAlertMsg( @@ -46,7 +41,9 @@ suspend fun planAndConnect( return CompletableDeferred(false) } } - null -> {} + // A SimplexName falls through to apiConnectPlan, which resolves it on the + // core (the /_connect plan command accepts a name target, not only a link). + is ConnectTarget.Name, null -> {} } connectProgressManager.cancelConnectProgress() val inProgress = mutableStateOf(true) @@ -77,13 +74,19 @@ private suspend fun planAndConnectTask( cleanup?.invoke() completable.complete(!completable.isActive) } - val result = chatModel.controller.apiConnectPlan(rhId, shortOrFullLink, linkOwnerSig, inProgress = inProgress) + val result = chatModel.controller.apiConnectPlan(rhId, shortOrFullLink, linkOwnerSig = linkOwnerSig, inProgress = inProgress) connectProgressManager.stopConnectProgress() if (!inProgress.value) { return completable } if (result != null) { - val (connectionLink, connectionPlan) = result + val (connectionLink, planSimplexName, otherSimplexName, connectionPlan) = result val target = strConnectTarget(shortOrFullLink.trim()) val linkText = if (target is ConnectTarget.Link) "

${target.linkText}" else "" + // the name can also resolve to the other kind; its type picks the verb, its short form the label and target + val connectOtherLink = otherSimplexName?.shortStr + val connectOtherButton = otherSimplexName?.let { + val label = if (it.nameType == SimplexNameType.publicGroup) MR.strings.connect_plan_join_name else MR.strings.connect_plan_connect_to_name + generalGetString(label).format(it.shortStr) + } when (connectionPlan) { is ConnectionPlan.InvitationLink -> when (connectionPlan.invitationLinkPlan) { is InvitationLinkPlan.Ok -> @@ -94,8 +97,8 @@ private suspend fun planAndConnectTask( connectionLink, connectionPlan.invitationLinkPlan.contactSLinkData_, ownerVerification = connectionPlan.invitationLinkPlan.ownerVerification, - close, - cleanup + close = close, + cleanup = cleanup ) } else { Log.d(TAG, "planAndConnect, .InvitationLink, .Ok, no short link data") @@ -157,6 +160,9 @@ private suspend fun planAndConnectTask( connectionLink, connectionPlan.contactAddressPlan.contactSLinkData_, ownerVerification = connectionPlan.contactAddressPlan.ownerVerification, + planSimplexName = planSimplexName, + connectOtherButton = connectOtherButton, + connectOtherLink = connectOtherLink, close, cleanup ) @@ -169,6 +175,8 @@ private suspend fun planAndConnectTask( connectDestructive = false, cleanup, ownerVerification = connectionPlan.contactAddressPlan.ownerVerification, + connectOtherButton = connectOtherButton, + connectOtherLink = connectOtherLink, ) } ContactAddressPlan.OwnLink -> { @@ -179,6 +187,8 @@ private suspend fun planAndConnectTask( text = generalGetString(MR.strings.connect_plan_this_is_your_own_simplex_address) + linkText, connectDestructive = true, cleanup = cleanup, + connectOtherButton = connectOtherButton, + connectOtherLink = connectOtherLink, ) } ContactAddressPlan.ConnectingConfirmReconnect -> { @@ -189,6 +199,8 @@ private suspend fun planAndConnectTask( text = generalGetString(MR.strings.connect_plan_you_have_already_requested_connection_via_this_address) + linkText, connectDestructive = true, cleanup = cleanup, + connectOtherButton = connectOtherButton, + connectOtherLink = connectOtherLink, ) } is ContactAddressPlan.ConnectingProhibit -> { @@ -197,25 +209,40 @@ private suspend fun planAndConnectTask( if (filterKnownContact != null) { filterKnownContact(contact) } else { - showOpenKnownContactAlert(chatModel, rhId, close, contact) + showOpenKnownContactAlert(chatModel, rhId, close, contact, planSimplexName = planSimplexName, connectOtherButton = connectOtherButton, connectOtherLink = connectOtherLink) cleanup() } } is ContactAddressPlan.Known -> { Log.d(TAG, "planAndConnect, .ContactAddress, .Known") val contact = connectionPlan.contactAddressPlan.contact + // A name-resolved contact is prepared in the store but not yet in the + // chat list (link-prepared chats arrive via NewPreparedChat). Surface it + // so it's visible and openable; no-op if already present. + if (chatModel.getContactChat(contact.contactId) == null) { + chatModel.chatsContext.addChat(Chat(remoteHostId = rhId, chatInfo = ChatInfo.Direct(contact), chatItems = emptyList())) + } if (filterKnownContact != null) { filterKnownContact(contact) } else { - showOpenKnownContactAlert(chatModel, rhId, close, contact) + showOpenKnownContactAlert(chatModel, rhId, close, contact, planSimplexName = planSimplexName, connectOtherButton = connectOtherButton, connectOtherLink = connectOtherLink) cleanup() } } is ContactAddressPlan.ContactViaAddress -> { Log.d(TAG, "planAndConnect, .ContactAddress, .ContactViaAddress") val contact = connectionPlan.contactAddressPlan.contact - askCurrentOrIncognitoProfileConnectContactViaAddress(chatModel, rhId, contact, close, openChat = false) - cleanup() + // the contact is already prepared in the store, so open the existing chat instead of sending a new + // connection request; surface it in the chat list first if it is not there yet (as for Known above) + if (chatModel.getContactChat(contact.contactId) == null) { + chatModel.chatsContext.addChat(Chat(remoteHostId = rhId, chatInfo = ChatInfo.Direct(contact), chatItems = emptyList())) + } + if (filterKnownContact != null) { + filterKnownContact(contact) + } else { + showOpenKnownContactAlert(chatModel, rhId, close, contact, planSimplexName = planSimplexName, connectOtherButton = connectOtherButton, connectOtherLink = connectOtherLink) + cleanup() + } } } is ConnectionPlan.GroupLink -> when (connectionPlan.groupLinkPlan) { @@ -228,6 +255,9 @@ private suspend fun planAndConnectTask( connectionPlan.groupLinkPlan.groupSLinkInfo_, connectionPlan.groupLinkPlan.groupSLinkData_, ownerVerification = connectionPlan.groupLinkPlan.ownerVerification, + planSimplexName = planSimplexName, + connectOtherButton = connectOtherButton, + connectOtherLink = connectOtherLink, close, cleanup ) @@ -240,6 +270,8 @@ private suspend fun planAndConnectTask( connectDestructive = false, cleanup = cleanup, ownerVerification = connectionPlan.groupLinkPlan.ownerVerification, + connectOtherButton = connectOtherButton, + connectOtherLink = connectOtherLink, ) } is GroupLinkPlan.OwnLink -> { @@ -248,7 +280,7 @@ private suspend fun planAndConnectTask( if (filterKnownGroup != null) { filterKnownGroup(groupInfo) } else { - ownGroupLinkConfirmConnect(chatModel, rhId, connectionLink, linkText, connectionPlan, groupInfo, close, cleanup) + ownGroupLinkConfirmConnect(chatModel, rhId, connectionLink, linkText, connectionPlan, groupInfo, close, cleanup, planSimplexName = planSimplexName, connectOtherButton = connectOtherButton, connectOtherLink = connectOtherLink) } } GroupLinkPlan.ConnectingConfirmReconnect -> { @@ -259,6 +291,8 @@ private suspend fun planAndConnectTask( text = generalGetString(MR.strings.connect_plan_you_are_already_joining_the_group_via_this_link) + linkText, connectDestructive = true, cleanup = cleanup, + connectOtherButton = connectOtherButton, + connectOtherLink = connectOtherLink, ) } is GroupLinkPlan.ConnectingProhibit -> { @@ -288,10 +322,15 @@ private suspend fun planAndConnectTask( is GroupLinkPlan.Known -> { Log.d(TAG, "planAndConnect, .GroupLink, .Known") val groupInfo = connectionPlan.groupLinkPlan.groupInfo + // Same as ContactAddress.Known: surface a name-resolved (prepared) + // group in the chat list so it's visible and openable. + if (chatModel.getGroupChat(groupInfo.groupId) == null) { + chatModel.chatsContext.addChat(Chat(remoteHostId = rhId, chatInfo = ChatInfo.Group(groupInfo, groupChatScope = null), chatItems = emptyList())) + } if (filterKnownGroup != null) { filterKnownGroup(groupInfo) } else { - showOpenKnownGroupAlert(chatModel, rhId, close, groupInfo) + showOpenKnownGroupAlert(chatModel, rhId, close, groupInfo, planSimplexName = planSimplexName, connectOtherButton = connectOtherButton, connectOtherLink = connectOtherLink) cleanup() } } @@ -417,6 +456,8 @@ fun askCurrentOrIncognitoProfileAlert( connectDestructive: Boolean, cleanup: (() -> Unit)?, ownerVerification: OwnerVerification? = null, + connectOtherButton: String? = null, + connectOtherLink: String? = null, ) { val fullText = listOfNotNull(text, ownerVerificationMessage(ownerVerification)).joinToString("\n\n").ifEmpty { null } AlertManager.privacySensitive.showAlertDialogButtonsColumn( @@ -441,6 +482,14 @@ fun askCurrentOrIncognitoProfileAlert( }) { Text(generalGetString(MR.strings.connect_use_new_incognito_profile), Modifier.fillMaxWidth(), textAlign = TextAlign.Center, color = connectColor) } + if (connectOtherButton != null && connectOtherLink != null) { + SectionItemView({ + AlertManager.privacySensitive.hideAlert() + withBGApi { planAndConnect(rhId, connectOtherLink, close = close, cleanup = cleanup) } + }) { + Text(connectOtherButton, Modifier.fillMaxWidth(), textAlign = TextAlign.Center, color = MaterialTheme.colors.primary) + } + } SectionItemView({ AlertManager.privacySensitive.hideAlert() cleanup?.invoke() @@ -463,7 +512,11 @@ fun openChat_(chatModel: ChatModel, rhId: Long?, close: (() -> Unit)?, chat: Cha val alertProfileImageSize = 138.dp -private fun showOpenKnownContactAlert(chatModel: ChatModel, rhId: Long?, close: (() -> Unit)?, contact: Contact) { +// For alerts that show the name inline (not as a profile with an avatar): "Alice" -> "Alice (@alice.testing)". +private fun nameWithDomain(name: String, planSimplexName: SimplexNameInfo?): String = + name + (planSimplexName?.let { " (${it.shortStr})" } ?: "") + +private fun showOpenKnownContactAlert(chatModel: ChatModel, rhId: Long?, close: (() -> Unit)?, contact: Contact, planSimplexName: SimplexNameInfo? = null, connectOtherButton: String? = null, connectOtherLink: String? = null) { AlertManager.privacySensitive.showOpenChatAlert( profileName = contact.profile.displayName, profileFullName = contact.profile.fullName, @@ -476,10 +529,13 @@ private fun showOpenKnownContactAlert(chatModel: ChatModel, rhId: Long?, close: }, // the alert shows the badge inline, so it skips the long-expired (ExpiredOld) badge here too profileBadge = if (contact.active && contact.profile.localBadge?.status != BadgeStatus.ExpiredOld) contact.profile.localBadge else null, + nameCaption = planSimplexName?.shortStr, confirmText = generalGetString(if (contact.nextConnectPrepared) MR.strings.connect_plan_open_new_chat else MR.strings.connect_plan_open_chat), onConfirm = { openKnownContact(chatModel, rhId, close, contact) }, + connectOtherButton = connectOtherButton, + onConnectOther = connectOtherLink?.let { link -> { withBGApi { planAndConnect(rhId, link, close = close) } } }, onDismiss = null ) } @@ -503,11 +559,14 @@ fun ownGroupLinkConfirmConnect( groupInfo: GroupInfo, close: (() -> Unit)?, cleanup: (() -> Unit)?, + planSimplexName: SimplexNameInfo? = null, + connectOtherButton: String? = null, + connectOtherLink: String? = null, ) { if (groupInfo.useRelays) { AlertManager.privacySensitive.showAlertDialogButtonsColumn( title = generalGetString(MR.strings.connect_plan_this_is_your_link_for_channel), - text = String.format(generalGetString(MR.strings.connect_plan_this_is_your_link_for_channel_vName), groupInfo.displayName), + text = String.format(generalGetString(MR.strings.connect_plan_this_is_your_link_for_channel_vName), nameWithDomain(groupInfo.displayName, planSimplexName)), buttons = { Column { SectionItemView({ @@ -517,6 +576,14 @@ fun ownGroupLinkConfirmConnect( }) { Text(generalGetString(MR.strings.connect_plan_open_channel), Modifier.fillMaxWidth(), textAlign = TextAlign.Center, color = MaterialTheme.colors.primary) } + if (connectOtherButton != null && connectOtherLink != null) { + SectionItemView({ + AlertManager.privacySensitive.hideAlert() + withBGApi { planAndConnect(rhId, connectOtherLink, close = close, cleanup = cleanup) } + }) { + Text(connectOtherButton, Modifier.fillMaxWidth(), textAlign = TextAlign.Center, color = MaterialTheme.colors.primary) + } + } SectionItemView({ AlertManager.privacySensitive.hideAlert() cleanup?.invoke() @@ -575,7 +642,7 @@ fun ownGroupLinkConfirmConnect( } } -private fun showOpenKnownGroupAlert(chatModel: ChatModel, rhId: Long?, close: (() -> Unit)?, groupInfo: GroupInfo) { +private fun showOpenKnownGroupAlert(chatModel: ChatModel, rhId: Long?, close: (() -> Unit)?, groupInfo: GroupInfo, planSimplexName: SimplexNameInfo? = null, connectOtherButton: String? = null, connectOtherLink: String? = null) { val subscriberCount = if (groupInfo.useRelays) groupInfo.groupSummary.publicMemberCount?.let { subscriberCountStr(it) } else null AlertManager.privacySensitive.showOpenChatAlert( profileName = groupInfo.groupProfile.displayName, @@ -587,6 +654,7 @@ private fun showOpenKnownGroupAlert(chatModel: ChatModel, rhId: Long?, close: (( icon = groupInfo.chatIconName ) }, + nameCaption = planSimplexName?.shortStr, subtitle = subscriberCount, confirmText = generalGetString( if (groupInfo.useRelays) { @@ -600,6 +668,8 @@ private fun showOpenKnownGroupAlert(chatModel: ChatModel, rhId: Long?, close: (( onConfirm = { openKnownGroup(chatModel, rhId, close, groupInfo) }, + connectOtherButton = connectOtherButton, + onConnectOther = connectOtherLink?.let { link -> { withBGApi { planAndConnect(rhId, link, close = close) } } }, onDismiss = null ) } @@ -619,6 +689,9 @@ fun showPrepareContactAlert( connectionLink: CreatedConnLink, contactShortLinkData: ContactShortLinkData, ownerVerification: OwnerVerification? = null, + planSimplexName: SimplexNameInfo? = null, + connectOtherButton: String? = null, + connectOtherLink: String? = null, close: (() -> Unit)?, cleanup: (() -> Unit)? ) { @@ -636,13 +709,14 @@ fun showPrepareContactAlert( ) }, profileBadge = if (contactShortLinkData.localBadge?.status == BadgeStatus.ExpiredOld) null else contactShortLinkData.localBadge, + nameCaption = planSimplexName?.shortStr, information = ownerVerificationMessage(ownerVerification), confirmText = generalGetString(MR.strings.connect_plan_open_new_chat), onConfirm = { AlertManager.privacySensitive.hideAlert() ModalManager.closeAllModalsEverywhere() withBGApi { - val chat = chatModel.controller.apiPrepareContact(rhId, connectionLink, contactShortLinkData) + val chat = chatModel.controller.apiPrepareContact(rhId, connectionLink, contactShortLinkData, planSimplexName?.nameDomain) if (chat != null) { withContext(Dispatchers.Main) { ChatController.chatModel.chatsContext.addChat(chat) @@ -652,6 +726,8 @@ fun showPrepareContactAlert( cleanup?.invoke() } }, + connectOtherButton = connectOtherButton, + onConnectOther = connectOtherLink?.let { link -> { withBGApi { planAndConnect(rhId, link, close = close, cleanup = cleanup) } } }, onDismiss = { cleanup?.invoke() } @@ -664,6 +740,9 @@ fun showPrepareGroupAlert( groupShortLinkInfo: GroupShortLinkInfo?, groupShortLinkData: GroupShortLinkData, ownerVerification: OwnerVerification? = null, + planSimplexName: SimplexNameInfo? = null, + connectOtherButton: String? = null, + connectOtherLink: String? = null, close: (() -> Unit)?, cleanup: (() -> Unit)? ) { @@ -679,6 +758,7 @@ fun showPrepareGroupAlert( icon = if (isChannel) MR.images.ic_bigtop_updates_circle_filled else MR.images.ic_supervised_user_circle_filled ) }, + nameCaption = planSimplexName?.shortStr, subtitle = subscriberCount, information = ownerVerificationMessage(ownerVerification), confirmText = generalGetString(if (isChannel) MR.strings.connect_plan_open_new_channel else MR.strings.connect_plan_open_new_group), @@ -686,7 +766,7 @@ fun showPrepareGroupAlert( AlertManager.privacySensitive.hideAlert() withBGApi { val directLink = groupShortLinkInfo?.direct ?: true - val chat = chatModel.controller.apiPrepareGroup(rhId, connectionLink, directLink = directLink, groupShortLinkData) + val chat = chatModel.controller.apiPrepareGroup(rhId, connectionLink, directLink = directLink, groupShortLinkData, planSimplexName?.nameDomain) if (chat != null) { withContext(Dispatchers.Main) { val relays = groupShortLinkInfo?.groupRelays @@ -703,6 +783,8 @@ fun showPrepareGroupAlert( cleanup?.invoke() } }, + connectOtherButton = connectOtherButton, + onConnectOther = connectOtherLink?.let { link -> { withBGApi { planAndConnect(rhId, link, close = close, cleanup = cleanup) } } }, onDismiss = { cleanup?.invoke() } diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/newchat/NewChatSheet.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/newchat/NewChatSheet.kt index af7f59496b..2419b11c6c 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/newchat/NewChatSheet.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/newchat/NewChatSheet.kt @@ -64,7 +64,7 @@ fun ModalData.NewChatSheet(rh: RemoteHostInfo?, close: () -> Unit) { ModalManager.start.showCustomModal { close -> AddGroupView(chatModel, chatModel.currentRemoteHost.value, close, closeAll) } }, createChannel = { - ModalManager.start.showCustomModal { close -> AddChannelView(chatModel, close, closeAll) } + ModalManager.start.showCustomModal { close -> AddChannelView(chatModel, chatModel.currentRemoteHost.value, close, closeAll) } }, rh = rh, close = close @@ -136,7 +136,8 @@ private fun ModalData.NewChatSheetLayout( } val searchText = rememberSaveable(stateSaver = TextFieldValue.Saver) { mutableStateOf(TextFieldValue("")) } val searchShowingSimplexLink = remember { mutableStateOf(false) } - val searchChatFilteredBySimplexLink = remember { mutableStateOf(null) } + val searchChatFilteredBySimplexLink = remember { mutableStateOf>(emptySet()) } + val connectNameCandidate = remember { mutableStateOf(null) } val showUnreadAndFavorites = remember { ChatController.appPrefs.showUnreadAndFavorites.state }.value val baseContactTypes = remember { listOf(ContactType.CARD, ContactType.CONTACT_WITH_REQUEST, ContactType.REQUEST, ContactType.RECENT) } val contactTypes by remember(searchText.value.text.isEmpty()) { @@ -313,8 +314,13 @@ private fun ModalData.NewChatSheetLayout( searchText = searchText, searchShowingSimplexLink = searchShowingSimplexLink, searchChatFilteredBySimplexLink = searchChatFilteredBySimplexLink, + connectNameCandidate = connectNameCandidate, close = close, ) + connectNameCandidate.value?.let { candidate -> + Divider() + ConnectByNameRow(candidate, searchText, connectNameCandidate, close = close) + } Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.ime)) } } @@ -399,8 +405,13 @@ private fun ModalData.NewChatSheetLayout( searchText = searchText, searchShowingSimplexLink = searchShowingSimplexLink, searchChatFilteredBySimplexLink = searchChatFilteredBySimplexLink, + connectNameCandidate = connectNameCandidate, close = close, ) + connectNameCandidate.value?.let { candidate -> + Divider() + ConnectByNameRow(candidate, searchText, connectNameCandidate, close = close) + } Divider() } } @@ -466,7 +477,8 @@ private fun ContactsSearchBar( listState: LazyListState, searchText: MutableState, searchShowingSimplexLink: MutableState, - searchChatFilteredBySimplexLink: MutableState, + searchChatFilteredBySimplexLink: MutableState>, + connectNameCandidate: MutableState, close: () -> Unit, ) { var focused by remember { mutableStateOf(false) } @@ -485,6 +497,8 @@ private fun ContactsSearchBar( alwaysVisible = true, searchText = searchText, trailingContent = null, + // the clear button must line up with the filter icon it replaces, so no reduction here + reducedCloseButtonPadding = 0.dp, ) { searchText.value = searchText.value.copy(it) } @@ -523,21 +537,26 @@ private fun ContactsSearchBar( snapshotFlow { searchText.value.text } .distinctUntilChanged() .collect { - when (val target = strConnectTarget(it.trim())) { - is ConnectTarget.Link -> { - hideKeyboard(view) - searchText.value = searchText.value.copy(target.linkText, selection = TextRange.Zero) - searchShowingSimplexLink.value = true - searchChatFilteredBySimplexLink.value = null - connect( - link = target.text, - searchChatFilteredBySimplexLink = searchChatFilteredBySimplexLink, - close = close, - cleanup = { searchText.value = TextFieldValue() } - ) - } - is ConnectTarget.Name -> showUnsupportedNameAlert(target.nameInfo) - null -> if (!searchShowingSimplexLink.value || it.isEmpty()) { + val target = strConnectTarget(it.trim()) + if (target is ConnectTarget.Link) { + hideKeyboard(view) + searchText.value = searchText.value.copy(target.linkText, selection = TextRange.Zero) + searchShowingSimplexLink.value = true + searchChatFilteredBySimplexLink.value = emptySet() + connectNameCandidate.value = null + connect( + link = target.text, + searchChatFilteredBySimplexLink = searchChatFilteredBySimplexLink, + close = close, + cleanup = { searchText.value = TextFieldValue() } + ) + } else { + // A name is resolved only when its "Connect to …" row is tapped, not on every keystroke. The + // simplex-name filter is chat-list only: this contacts/deleted view is a scoped subset, so a + // resolved chat id (channel, business, unlisted or active-only contact) may not be present in it. + val candidate = nameSearchCandidate(it.trim()) + connectNameCandidate.value = candidate + if (candidate == null && (!searchShowingSimplexLink.value || it.isEmpty())) { if (it.isNotEmpty()) { focusRequester.requestFocus() } else { @@ -547,7 +566,7 @@ private fun ContactsSearchBar( } } searchShowingSimplexLink.value = false - searchChatFilteredBySimplexLink.value = null + searchChatFilteredBySimplexLink.value = emptySet() } } } @@ -574,12 +593,12 @@ private fun ToggleFilterButton() { } } -private fun connect(link: String, searchChatFilteredBySimplexLink: MutableState, close: () -> Unit, cleanup: (() -> Unit)?) { +private fun connect(link: String, searchChatFilteredBySimplexLink: MutableState>, close: () -> Unit, cleanup: (() -> Unit)?) { withBGApi { planAndConnect( chatModel.remoteHostId(), link, - filterKnownContact = { searchChatFilteredBySimplexLink.value = it.id }, + filterKnownContact = { searchChatFilteredBySimplexLink.value = setOf(it.id) }, close = close, cleanup = cleanup, ) @@ -589,15 +608,15 @@ private fun connect(link: String, searchChatFilteredBySimplexLink: MutableState< private fun filteredContactChats( showUnreadAndFavorites: Boolean, searchShowingSimplexLink: State, - searchChatFilteredBySimplexLink: State, + searchChatFilteredBySimplexLink: State>, searchText: String, contactChats: List ): List { - val linkChatId = searchChatFilteredBySimplexLink.value + val linkChatIds = searchChatFilteredBySimplexLink.value val s = if (searchShowingSimplexLink.value) "" else searchText.trim().lowercase() - return if (linkChatId != null) { - contactChats.filter { it.id == linkChatId } + return if (linkChatIds.isNotEmpty()) { + contactChats.filter { it.id in linkChatIds } } else { contactChats.filter { chat -> filterChat( @@ -653,7 +672,9 @@ private fun ModalData.DeletedContactsView(rh: RemoteHostInfo?, closeDeletedChats val listState = remember { appBarHandler.listState } val searchText = rememberSaveable(stateSaver = TextFieldValue.Saver) { mutableStateOf(TextFieldValue("")) } val searchShowingSimplexLink = remember { mutableStateOf(false) } - val searchChatFilteredBySimplexLink = remember { mutableStateOf(null) } + val searchChatFilteredBySimplexLink = remember { mutableStateOf>(emptySet()) } + // deleted contacts are not connected to by name, so this candidate only stops per-keystroke resolution + val connectNameCandidate = remember { mutableStateOf(null) } val showUnreadAndFavorites = remember { appPrefs.showUnreadAndFavorites.state }.value val allChats by remember(chatModel.chats.value) { derivedStateOf { filterContactTypes(chatModel.chats.value, listOf(ContactType.CHAT_DELETED)) } @@ -696,6 +717,7 @@ private fun ModalData.DeletedContactsView(rh: RemoteHostInfo?, closeDeletedChats searchText = searchText, searchShowingSimplexLink = searchShowingSimplexLink, searchChatFilteredBySimplexLink = searchChatFilteredBySimplexLink, + connectNameCandidate = connectNameCandidate, close = close, ) } else { @@ -705,6 +727,7 @@ private fun ModalData.DeletedContactsView(rh: RemoteHostInfo?, closeDeletedChats searchText = searchText, searchShowingSimplexLink = searchShowingSimplexLink, searchChatFilteredBySimplexLink = searchChatFilteredBySimplexLink, + connectNameCandidate = connectNameCandidate, close = close, ) Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.ime)) diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/newchat/NewChatView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/newchat/NewChatView.kt index 6799fa1300..d3bca178aa 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/newchat/NewChatView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/newchat/NewChatView.kt @@ -679,7 +679,11 @@ private fun PasteLinkView(rhId: Long?, pastedLink: MutableState, showQRC showQRCodeScanner.value = false withBGApi { connect(rhId, target.text, close) { pastedLink.value = "" } } } - is ConnectTarget.Name -> showUnsupportedNameAlert(target.nameInfo) + is ConnectTarget.Name -> { + pastedLink.value = target.text + showQRCodeScanner.value = false + withBGApi { connect(rhId, target.text, close) { pastedLink.value = "" } } + } null -> AlertManager.shared.showAlertMsg( title = generalGetString(MR.strings.invalid_contact_link), text = generalGetString(MR.strings.the_text_you_pasted_is_not_a_link) @@ -824,7 +828,7 @@ fun strIsSimplexLink(str: String): Boolean { sealed class ConnectTarget { class Link(val text: String, val linkType: SimplexLinkType, val linkText: String) : ConnectTarget() - class Name(val nameInfo: SimplexNameInfo) : ConnectTarget() + class Name(val text: String, val nameInfo: SimplexNameInfo) : ConnectTarget() } fun strConnectTarget(str: String): ConnectTarget? { @@ -835,21 +839,13 @@ fun strConnectTarget(str: String): ConnectTarget? { return ConnectTarget.Link(links[0].text, fmt.linkType, fmt.simplexLinkText) } if (links.isEmpty()) { - val nameInfo = parsedMd.firstNotNullOfOrNull { (it.format as? Format.SimplexName)?.nameInfo } - if (nameInfo != null) return ConnectTarget.Name(nameInfo) + val nameFt = parsedMd.firstOrNull { it.format is Format.SimplexName } + val nameInfo = (nameFt?.format as? Format.SimplexName)?.nameInfo + if (nameFt != null && nameInfo != null) return ConnectTarget.Name(nameFt.text, nameInfo) } return null } -fun showUnsupportedNameAlert(nameInfo: SimplexNameInfo) { - val (title, msg) = if (nameInfo.nameType == SimplexNameType.contact) { - generalGetString(MR.strings.unsupported_contact_name) to generalGetString(MR.strings.contact_name_requires_newer_app_version) - } else { - generalGetString(MR.strings.unsupported_channel_name) to generalGetString(MR.strings.channel_name_requires_newer_app_version) - } - AlertManager.shared.showAlertMsg(title, "$msg ${generalGetString(MR.strings.please_upgrade_the_app)}") -} - @Composable fun IncognitoToggle( incognitoPref: SharedPreference, diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/remote/ConnectDesktopView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/remote/ConnectDesktopView.kt index 81e1afd22c..86be99d1bf 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/remote/ConnectDesktopView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/remote/ConnectDesktopView.kt @@ -148,7 +148,6 @@ private fun ConnectingDesktop(session: RemoteCtrlSession, rc: RemoteCtrlInfo?) { AppBarTitle(stringResource(MR.strings.connecting_to_desktop)) SectionView(stringResource(MR.strings.connecting_to_desktop), contentPadding = PaddingValues(horizontal = DEFAULT_PADDING)) { CtrlDeviceNameText(session, rc) - Spacer(Modifier.height(DEFAULT_PADDING_HALF)) CtrlDeviceVersionText(session) } @@ -257,7 +256,6 @@ private fun VerifySession(session: RemoteCtrlSession, rc: RemoteCtrlInfo?, sessC AppBarTitle(stringResource(MR.strings.verify_connection)) SectionView(stringResource(MR.strings.connected_to_desktop), contentPadding = PaddingValues(horizontal = DEFAULT_PADDING)) { CtrlDeviceNameText(session, rc) - Spacer(Modifier.height(DEFAULT_PADDING_HALF)) CtrlDeviceVersionText(session) } @@ -265,16 +263,15 @@ private fun VerifySession(session: RemoteCtrlSession, rc: RemoteCtrlInfo?, sessC SectionView(stringResource(MR.strings.verify_code_with_desktop)) { SessionCodeText(sessCode) + SectionItemView({ verifyDesktopSessionCode(remoteCtrls, sessCode) }) { + Icon(painterResource(MR.images.ic_check), generalGetString(MR.strings.confirm_verb), tint = MaterialTheme.colors.secondary) + TextIconSpaced(false) + Text(generalGetString(MR.strings.confirm_verb)) + } } SectionDividerSpaced() - SectionItemView({ verifyDesktopSessionCode(remoteCtrls, sessCode) }) { - Icon(painterResource(MR.images.ic_check), generalGetString(MR.strings.confirm_verb), tint = MaterialTheme.colors.secondary) - TextIconSpaced(false) - Text(generalGetString(MR.strings.confirm_verb)) - } - SectionView { DisconnectButton(onClick = ::disconnectDesktop) } @@ -312,7 +309,6 @@ private fun ActiveSession(session: RemoteCtrlSession, rc: RemoteCtrlInfo, close: AppBarTitle(stringResource(MR.strings.connected_to_desktop)) SectionView(stringResource(MR.strings.connected_desktop), contentPadding = PaddingValues(horizontal = DEFAULT_PADDING)) { Text(rc.deviceViewName) - Spacer(Modifier.height(DEFAULT_PADDING_HALF)) CtrlDeviceVersionText(session) } diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/CallSettings.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/CallSettings.kt index cb36e4ae1a..43863d5794 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/CallSettings.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/CallSettings.kt @@ -17,6 +17,7 @@ import androidx.compose.ui.unit.dp import chat.simplex.common.views.helpers.* import chat.simplex.common.model.* import chat.simplex.common.platform.ColumnWithScrollBar +import chat.simplex.common.platform.appPlatform import chat.simplex.res.MR @Composable @@ -38,12 +39,14 @@ fun CallSettingsLayout( ) { ColumnWithScrollBar { AppBarTitle(stringResource(MR.strings.your_calls)) - val lockCallState = remember { mutableStateOf(callOnLockScreen.get()) } SectionView(stringResource(MR.strings.settings_section_title_settings)) { SectionItemView(editIceServers) { Text(stringResource(MR.strings.webrtc_ice_servers)) } - val enabled = remember { mutableStateOf(true) } - LockscreenOpts(lockCallState, enabled, onSelected = { callOnLockScreen.set(it); lockCallState.value = it }) + if (appPlatform.isAndroid) { + val lockCallState = remember { mutableStateOf(callOnLockScreen.get()) } + val enabled = remember { mutableStateOf(true) } + LockscreenOpts(lockCallState, enabled, onSelected = { callOnLockScreen.set(it); lockCallState.value = it }) + } SettingsPreferenceItem(null, stringResource(MR.strings.always_use_relay), webrtcPolicyRelay) } SectionTextFooter( diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/PrivacySettings.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/PrivacySettings.kt index cf34fd5a44..f8bb2d64f9 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/PrivacySettings.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/PrivacySettings.kt @@ -134,6 +134,11 @@ fun MorePrivacyView(chatModel: ChatModel) { chatModel.draftChatId.value = null } }) + SettingsPreferenceItem( + painterResource(MR.images.ic_tag), + stringResource(MR.strings.verify_simplex_names), + chatModel.controller.appPrefs.privacyVerifySimplexNames + ) } SectionDividerSpaced() @@ -665,46 +670,46 @@ fun SimplexLockView( } } } - if (performLA.value && laMode.value == LAMode.PASSCODE) { - SectionDividerSpaced() - SectionView(stringResource(MR.strings.self_destruct_passcode)) { - val openInfo = { - ModalManager.start.showModal { - SelfDestructInfoView() - } + } + if (performLA.value && laMode.value == LAMode.PASSCODE) { + SectionDividerSpaced() + SectionView(stringResource(MR.strings.self_destruct_passcode)) { + val openInfo = { + ModalManager.start.showModal { + SelfDestructInfoView() } - SettingsActionItemWithContent(null, null, click = openInfo) { - SharedPreferenceToggleWithIcon( - stringResource(MR.strings.enable_self_destruct), - painterResource(MR.images.ic_info), - openInfo, - remember { selfDestructPref.state }.value - ) { - toggleSelfDestruct(selfDestructPref) - } + } + SettingsActionItemWithContent(null, null, click = openInfo) { + SharedPreferenceToggleWithIcon( + stringResource(MR.strings.enable_self_destruct), + painterResource(MR.images.ic_info), + openInfo, + remember { selfDestructPref.state }.value + ) { + toggleSelfDestruct(selfDestructPref) } + } - if (remember { selfDestructPref.state }.value) { - Column(Modifier.padding(horizontal = DEFAULT_PADDING, vertical = DEFAULT_PADDING_HALF)) { - Text( - stringResource(MR.strings.self_destruct_new_display_name), - fontSize = 16.sp, - modifier = Modifier.padding(bottom = DEFAULT_PADDING_HALF) - ) - ProfileNameField(selfDestructDisplayName, "", { isValidDisplayName(it.trim()) }) - LaunchedEffect(selfDestructDisplayName.value) { - val new = selfDestructDisplayName.value - if (isValidDisplayName(new) && selfDestructDisplayNamePref.get() != new) { - selfDestructDisplayNamePref.set(new) - } + if (remember { selfDestructPref.state }.value) { + Column(Modifier.padding(horizontal = DEFAULT_PADDING, vertical = DEFAULT_PADDING_HALF)) { + Text( + stringResource(MR.strings.self_destruct_new_display_name), + fontSize = 16.sp, + modifier = Modifier.padding(bottom = DEFAULT_PADDING_HALF) + ) + ProfileNameField(selfDestructDisplayName, "", { isValidDisplayName(it.trim()) }) + LaunchedEffect(selfDestructDisplayName.value) { + val new = selfDestructDisplayName.value + if (isValidDisplayName(new) && selfDestructDisplayNamePref.get() != new) { + selfDestructDisplayNamePref.set(new) } } - SectionItemView({ changeSelfDestructPassword() }) { - Text( - stringResource(MR.strings.change_self_destruct_passcode), - color = MaterialTheme.colors.primary - ) - } + } + SectionItemView({ changeSelfDestructPassword() }) { + Text( + stringResource(MR.strings.change_self_destruct_passcode), + color = MaterialTheme.colors.primary + ) } } } diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/SetSimplexNameView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/SetSimplexNameView.kt new file mode 100644 index 0000000000..c4cf0d1714 --- /dev/null +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/SetSimplexNameView.kt @@ -0,0 +1,79 @@ +package chat.simplex.common.views.usersettings + +import SectionBottomSpacer +import SectionDividerSpaced +import SectionItemView +import SectionTextFooter +import SectionView +import androidx.compose.material.* +import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveable +import chat.simplex.common.platform.* +import chat.simplex.common.views.* +import chat.simplex.common.views.helpers.* +import chat.simplex.res.MR +import dev.icerock.moko.resources.compose.stringResource +import kotlinx.coroutines.* + +// Set the user's own (prefix "@") or a channel's (prefix "#") SimpleX name. +// The field is prefilled with the full prefixed name; `save` receives the encoded name (or null to +// clear) and returns true on success (it shows its own error alert otherwise). +@Composable +fun SetSimplexDomainView( + title: String, + footer: String, + placeholder: String, + simplexName: String, + save: suspend (String?) -> Boolean, + close: () -> Unit +) { + val name = rememberSaveable { mutableStateOf(simplexName) } + val saving = remember { mutableStateOf(false) } + val unchanged = name.value.trim() == simplexName.trim() + + fun addSimplexTLD(s: String): String { + return if (s.contains(".")) s else "$s.simplex" + } + + fun normalized(): String? { + val s = name.value.trim() + return when { + s.isEmpty() -> null + s.startsWith("@") || s.startsWith("#") -> addSimplexTLD(s.substring(1)) + else -> addSimplexTLD(s) + } + } + + val doSave: () -> Unit = { + withBGApi { + saving.value = true + val ok = try { save(normalized()) } catch (e: Exception) { + Log.e(TAG, "SetSimplexDomainView save: ${e.stackTraceToString()}") + AlertManager.shared.showAlertMsg(generalGetString(MR.strings.error_saving_simplex_name), e.message ?: "") + false + } + saving.value = false + if (ok) withContext(Dispatchers.Main) { close() } + } + } + + ModalView(close = close) { + ColumnWithScrollBar { + AppBarTitle(title) + SectionView { + PlainTextEditor(name, placeholder) + } + SectionTextFooter(footer) + SectionDividerSpaced() + SectionView { + SectionItemView(doSave, disabled = unchanged || saving.value) { + Text( + stringResource(MR.strings.save_verb), + color = if (unchanged || saving.value) MaterialTheme.colors.secondary else MaterialTheme.colors.primary + ) + } + } + SectionBottomSpacer() + } + } +} diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/UserAddressView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/UserAddressView.kt index c55eaf6c10..9d0efad152 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/UserAddressView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/UserAddressView.kt @@ -1,6 +1,7 @@ package chat.simplex.common.views.usersettings import SectionBottomSpacer +import SectionCardShape import SectionDividerSpaced import SectionItemView import SectionTextFooter @@ -33,6 +34,8 @@ import chat.simplex.common.views.chat.* import chat.simplex.common.views.newchat.* import chat.simplex.common.BuildConfigCommon import chat.simplex.res.MR +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext @Composable fun UserAddressView( @@ -359,6 +362,37 @@ private fun UserAddressLayout( SectionTextFooter(stringResource(MR.strings.add_your_team_members_to_conversations)) } + SectionDividerSpaced() + SectionView { + SettingsActionItem( + painterResource(MR.images.ic_at), + stringResource(MR.strings.your_simplex_name), + click = { + ModalManager.start.showCustomModal { close -> + val domain = user?.profile?.contactDomain?.shortName + SetSimplexDomainView( + title = generalGetString(MR.strings.set_simplex_name), + footer = generalGetString(MR.strings.set_user_simplex_name_footer), + placeholder = "@yourname.testing", + simplexName = if (domain == null) "" else "@$domain", + save = { simplexDomain -> + try { + val u = chatModel.controller.apiSetUserDomain(user?.remoteHostId, simplexDomain) + withContext(Dispatchers.Main) { chatModel.updateUser(u) } + true + } catch (e: Exception) { + Log.e(TAG, "apiSetUserDomain: ${e.message}") + false + } + }, + close = close + ) + } + }, + iconColor = MaterialTheme.colors.secondary + ) + } + SectionDividerSpaced() SectionView(generalGetString(MR.strings.or_to_share_privately)) { CreateOneTimeLinkButton() @@ -699,7 +733,13 @@ private fun AcceptIncognitoToggle(addressSettingsState: MutableState) { val autoReply = rememberSaveable { mutableStateOf(addressSettingsState.value.autoReply) } - TextEditor(autoReply, Modifier.height(100.dp), placeholder = stringResource(MR.strings.enter_welcome_message_optional)) + TextEditor( + autoReply, + Modifier.height(100.dp), + placeholder = stringResource(MR.strings.enter_welcome_message_optional), + contentPadding = PaddingValues(), + shape = SectionCardShape + ) LaunchedEffect(autoReply.value) { if (autoReply.value != addressSettingsState.value.autoReply) { addressSettingsState.value = AddressSettingsState( diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/networkAndServers/ChatRelayView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/networkAndServers/ChatRelayView.kt index ab63067226..9a2d7f8e61 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/networkAndServers/ChatRelayView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/networkAndServers/ChatRelayView.kt @@ -1,6 +1,7 @@ package chat.simplex.common.views.usersettings.networkAndServers import SectionBottomSpacer +import SectionCardShape import SectionDividerSpaced import SectionItemView import SectionItemViewSpaceBetween @@ -10,9 +11,7 @@ import androidx.compose.foundation.layout.* import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.material.* import androidx.compose.runtime.* -import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.sp import androidx.compose.ui.graphics.Color import dev.icerock.moko.resources.compose.painterResource @@ -230,43 +229,35 @@ private fun CustomRelay( } SectionView( - stringResource(MR.strings.your_relay_address).uppercase(), + stringResource(MR.strings.your_relay_address), icon = painterResource(MR.images.ic_error), iconTint = if (!validAddress.value) MaterialTheme.colors.error else Color.Transparent, ) { TextEditor( relayAddress, - Modifier.height(144.dp) + Modifier.height(144.dp), + contentPadding = PaddingValues(), + shape = SectionCardShape ) } SectionDividerSpaced(maxTopPadding = true) - Column { - val iconSize = with(LocalDensity.current) { 21.sp.toDp() } - Row(Modifier.padding(start = DEFAULT_PADDING, bottom = 5.dp), verticalAlignment = Alignment.CenterVertically) { - Text( - stringResource(MR.strings.your_relay_name).uppercase(), - color = MaterialTheme.colors.secondary, style = MaterialTheme.typography.body2, fontSize = 12.sp - ) - IconButton( - onClick = { if (!validName.value) showInvalidRelayNameAlert(relayName) }, - enabled = !validName.value, - modifier = Modifier.padding(start = DEFAULT_PADDING_HALF).size(iconSize) - ) { - Icon( - painterResource(MR.images.ic_error), null, - tint = if (!validName.value) MaterialTheme.colors.error else Color.Transparent - ) - } - } - Column(Modifier.fillMaxWidth()) { - TextEditor( - relayName, - Modifier, - placeholder = generalGetString(MR.strings.enter_relay_name), - enabled = relay.value.tested != true - ) - } + SectionView( + stringResource(MR.strings.your_relay_name), + icon = painterResource(MR.images.ic_error), + iconTint = if (!validName.value) MaterialTheme.colors.error else Color.Transparent, + onIconClick = if (!validName.value) { + { showInvalidRelayNameAlert(relayName) } + } else null + ) { + TextEditor( + relayName, + Modifier, + placeholder = generalGetString(MR.strings.enter_relay_name), + contentPadding = PaddingValues(), + shape = SectionCardShape, + enabled = relay.value.tested != true + ) } if (relay.value.tested != true) { SectionTextFooter(annotatedStringResource(MR.strings.test_relay_to_retrieve_name)) diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/networkAndServers/NetworkAndServers.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/networkAndServers/NetworkAndServers.kt index 892a252a9d..556c7270cc 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/networkAndServers/NetworkAndServers.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/networkAndServers/NetworkAndServers.kt @@ -268,28 +268,32 @@ fun ModalData.NetworkAndServersView(closeNetworkAndServers: () -> Unit) { if (currentRemoteHost == null && networkUseSocksProxy.value) { SectionTextFooter(annotatedStringResource(MR.strings.socks_proxy_setting_limitations)) } - val saveDisabled = !serversCanBeSaved(currUserServers.value, userServers.value, serverErrors.value) - SectionItemView( - { scope.launch { saveServers(rhId = currentRemoteHost?.remoteHostId, currUserServers, userServers) } }, - disabled = saveDisabled, - ) { - Text(stringResource(MR.strings.smp_servers_save), color = if (!saveDisabled) MaterialTheme.colors.onBackground else MaterialTheme.colors.secondary) + SectionDividerSpaced() + SectionView { + val saveDisabled = !serversCanBeSaved(currUserServers.value, userServers.value, serverErrors.value) + SectionItemView( + { scope.launch { saveServers(rhId = currentRemoteHost?.remoteHostId, currUserServers, userServers) } }, + disabled = saveDisabled, + ) { + Text(stringResource(MR.strings.smp_servers_save), color = if (!saveDisabled) MaterialTheme.colors.onBackground else MaterialTheme.colors.secondary) + } } - val serversErr = globalServersError(serverErrors.value) - if (serversErr != null) { - SectionCustomFooter { - ServersErrorFooter(serversErr) + val serversErrs = globalServersErrors(serverErrors.value) + if (serversErrs.isNotEmpty()) { + serversErrs.forEach { err -> + SectionCustomFooter { + ServersErrorFooter(err) + } } } else if (serverErrors.value.isNotEmpty()) { SectionCustomFooter { ServersErrorFooter(generalGetString(MR.strings.errors_in_servers_configuration)) } } - val serversWarn = globalServersWarning(serverWarnings.value) - if (serversWarn != null) { + globalServersWarnings(serverWarnings.value).forEach { warn -> SectionCustomFooter { - ServersWarningFooter(serversWarn) + ServersWarningFooter(warn) } } @@ -951,23 +955,11 @@ fun serversCanBeSaved( return userServers != currUserServers && serverErrors.isEmpty() } -fun globalServersError(serverErrors: List): String? { - for (err in serverErrors) { - if (err.globalError != null) { - return err.globalError - } - } - return null -} +fun globalServersErrors(serverErrors: List): List = + serverErrors.mapNotNull { it.globalError } -fun globalServersWarning(serverWarnings: List): String? { - for (warn in serverWarnings) { - if (warn.globalWarning != null) { - return warn.globalWarning - } - } - return null -} +fun globalServersWarnings(serverWarnings: List): List = + serverWarnings.mapNotNull { it.globalWarning } fun globalSMPServersError(serverErrors: List): String? { for (err in serverErrors) { diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/networkAndServers/OperatorView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/networkAndServers/OperatorView.kt index f5bceabbf1..53277c9ccd 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/networkAndServers/OperatorView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/networkAndServers/OperatorView.kt @@ -211,15 +211,19 @@ fun OperatorViewLayout( rhId = rhId ) } - val serversErr = globalServersError(serverErrors.value) - val serversWarn = globalServersWarning(serverWarnings.value) - if (serversErr != null) { - SectionCustomFooter { - ServersErrorFooter(serversErr) + val serversErrs = globalServersErrors(serverErrors.value) + val serversWarns = globalServersWarnings(serverWarnings.value) + if (serversErrs.isNotEmpty()) { + serversErrs.forEach { err -> + SectionCustomFooter { + ServersErrorFooter(err) + } } - } else if (serversWarn != null) { - SectionCustomFooter { - ServersWarningFooter(serversWarn) + } else if (serversWarns.isNotEmpty()) { + serversWarns.forEach { warn -> + SectionCustomFooter { + ServersWarningFooter(warn) + } } } else { val footerText = when (val c = operator.conditionsAcceptance) { @@ -267,7 +271,7 @@ fun OperatorViewLayout( userServers.value = userServers.value.toMutableList().apply { this[operatorIndex] = this[operatorIndex].copy( operator = this[operatorIndex].operator?.copy( - smpRoles = this[operatorIndex].operator?.smpRoles?.copy(storage = enabled) ?: ServerRoles(storage = enabled, proxy = false) + smpRoles = this[operatorIndex].operator?.smpRoles?.copy(storage = enabled) ?: ServerRoles(storage = enabled, proxy = false, names = false) ) ) } @@ -287,7 +291,27 @@ fun OperatorViewLayout( userServers.value = userServers.value.toMutableList().apply { this[operatorIndex] = this[operatorIndex].copy( operator = this[operatorIndex].operator?.copy( - smpRoles = this[operatorIndex].operator?.smpRoles?.copy(proxy = enabled) ?: ServerRoles(storage = false, proxy = enabled) + smpRoles = this[operatorIndex].operator?.smpRoles?.copy(proxy = enabled) ?: ServerRoles(storage = false, proxy = enabled, names = false) + ) + ) + } + } + ) + } + SectionItemView(padding = PaddingValues(horizontal = DEFAULT_PADDING)) { + Text( + stringResource(MR.strings.operator_use_for_names), + Modifier.padding(end = 24.dp), + color = Color.Unspecified + ) + Spacer(Modifier.fillMaxWidth().weight(1f)) + DefaultSwitch( + checked = userServers.value[operatorIndex].operator_.smpRoles.names, + onCheckedChange = { enabled -> + userServers.value = userServers.value.toMutableList().apply { + this[operatorIndex] = this[operatorIndex].copy( + operator = this[operatorIndex].operator?.copy( + smpRoles = this[operatorIndex].operator?.smpRoles?.copy(names = enabled) ?: ServerRoles(storage = false, proxy = false, names = enabled) ) ) } @@ -371,7 +395,7 @@ fun OperatorViewLayout( userServers.value = userServers.value.toMutableList().apply { this[operatorIndex] = this[operatorIndex].copy( operator = this[operatorIndex].operator?.copy( - xftpRoles = this[operatorIndex].operator?.xftpRoles?.copy(storage = enabled) ?: ServerRoles(storage = enabled, proxy = false) + xftpRoles = this[operatorIndex].operator?.xftpRoles?.copy(storage = enabled) ?: ServerRoles(storage = enabled, proxy = false, names = false) ) ) } diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/networkAndServers/ProtocolServersView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/networkAndServers/ProtocolServersView.kt index 280cd7bedb..63365bd080 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/networkAndServers/ProtocolServersView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/networkAndServers/ProtocolServersView.kt @@ -185,16 +185,14 @@ fun YourServersViewLayout( iconColor = if (testing.value) MaterialTheme.colors.secondary else MaterialTheme.colors.primary ) } - val serversErr = globalServersError(serverErrors.value) - if (serversErr != null) { + globalServersErrors(serverErrors.value).forEach { err -> SectionCustomFooter { - ServersErrorFooter(serversErr) + ServersErrorFooter(err) } } - val serversWarn = globalServersWarning(serverWarnings.value) - if (serversWarn != null) { + globalServersWarnings(serverWarnings.value).forEach { warn -> SectionCustomFooter { - ServersWarningFooter(serversWarn) + ServersWarningFooter(warn) } } SectionDividerSpaced() diff --git a/apps/multiplatform/common/src/commonMain/resources/MR/base/strings.xml b/apps/multiplatform/common/src/commonMain/resources/MR/base/strings.xml index 9262bd9dac..6befeecb3b 100644 --- a/apps/multiplatform/common/src/commonMain/resources/MR/base/strings.xml +++ b/apps/multiplatform/common/src/commonMain/resources/MR/base/strings.xml @@ -15,6 +15,8 @@ Connect Connect incognito Open chat + Join channel %s + Connect to %s Open new chat Open group Open new group @@ -146,6 +148,7 @@ For chat profile %s: Errors in servers configuration. No chat relays enabled. + No servers to resolve names. Server warning Error accepting conditions Spam @@ -199,6 +202,16 @@ Connecting via channel name requires a newer app version. Connecting via contact name requires a newer app version. Please upgrade the app. + SimpleX name error + None of your servers are set to resolve SimpleX names. Configure servers, or use a connection link. + Server %1$s does not support name resolution. Configure servers, or use a connection link. + Name not found + This SimpleX name is not registered. Please check the name. + Resolver error: %1$s + No valid link + The SimpleX name %1$s is registered, but it has no valid link. + Unconfirmed name + The SimpleX name %1$s is registered, but not added to profile. Please add it to your address or channel profile, if you are the owner. Channel temporarily unavailable Channel has no active relays. Please try to join later. App update required @@ -930,6 +943,17 @@ One-time invitation link 1-time link SimpleX address + Verify name + Verify SimpleX names + SimpleX name not verified + SimpleX name + Your SimpleX name + Set SimpleX name + Error saving name + The SimpleX name %1$s is registered without channel link. Add channel link to the name via the registration page. + The SimpleX name %1$s is registered without SimpleX address. Add your SimpleX address to the name via the registration page. + Let people connect to you via name registered with your SimpleX address. + Let people join via name registered with this channel link. Or show this code Full link Short link @@ -2153,6 +2177,7 @@ Use for messages To receive For private routing + To resolve names Added message servers Use for files To send diff --git a/apps/multiplatform/common/src/desktopMain/kotlin/chat/simplex/common/platform/RecAndPlay.desktop.kt b/apps/multiplatform/common/src/desktopMain/kotlin/chat/simplex/common/platform/RecAndPlay.desktop.kt index 8d26f2f085..d59677b726 100644 --- a/apps/multiplatform/common/src/desktopMain/kotlin/chat/simplex/common/platform/RecAndPlay.desktop.kt +++ b/apps/multiplatform/common/src/desktopMain/kotlin/chat/simplex/common/platform/RecAndPlay.desktop.kt @@ -13,9 +13,14 @@ import java.io.File import java.util.* import kotlin.math.max -internal val vlcFactory: MediaPlayerFactory by lazy { MediaPlayerFactory() } +// Serialize the two factory constructions: each MediaPlayerFactory() runs VLC native discovery via +// a JDK ServiceLoader, which is not thread-safe. Building both factories concurrently (e.g. vlcFactory +// on the render thread while vlcPreviewFactory is built on the preview thread) corrupts the ServiceLoader +// enumeration and throws NoSuchElementException from CompoundEnumeration.nextElement. +private val vlcFactoryLock = Any() +internal val vlcFactory: MediaPlayerFactory by lazy { synchronized(vlcFactoryLock) { MediaPlayerFactory() } } // No hardware acceleration - more secure for previews -internal val vlcPreviewFactory: MediaPlayerFactory by lazy { MediaPlayerFactory("--avcodec-hw=none") } +internal val vlcPreviewFactory: MediaPlayerFactory by lazy { synchronized(vlcFactoryLock) { MediaPlayerFactory("--avcodec-hw=none") } } actual class RecorderNative: RecorderInterface { private var player: MediaPlayer? = null diff --git a/apps/simplex-directory-service/src/Directory/Events.hs b/apps/simplex-directory-service/src/Directory/Events.hs index bfbc025a49..3bff611a28 100644 --- a/apps/simplex-directory-service/src/Directory/Events.hs +++ b/apps/simplex-directory-service/src/Directory/Events.hs @@ -27,7 +27,7 @@ import qualified Data.Attoparsec.Text as A import Data.Char (isSpace) import Data.Either (fromRight) import Data.Functor (($>)) -import Data.Maybe (fromMaybe) +import Data.Maybe (fromMaybe, isNothing) import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) @@ -38,6 +38,7 @@ import Simplex.Chat.Messages import Simplex.Chat.Messages.CIContent import Simplex.Chat.Protocol (LinkOwnerSig, MsgChatLink, MsgContent (..)) import Simplex.Chat.Types +import Simplex.Chat.Types.Preferences (GroupFeature) import Simplex.Chat.Types.Shared import Simplex.Messaging.Agent.Protocol (AgentErrorType (..)) import Simplex.Messaging.Encoding.String @@ -52,6 +53,7 @@ data DirectoryEvent | DEGroupLinkCheck GroupInfo | DEPendingMember GroupInfo GroupMember | DEPendingMemberMsg GroupInfo GroupMember ChatItemId Text + | DEGroupItemProhibited GroupInfo GroupMember ChatItemId GroupFeature -- a member posted content prohibited by the group's settings | DEContactRoleChanged GroupInfo ContactId GroupMemberRole -- contactId here is the contact whose role changed | DEServiceRoleChanged GroupInfo GroupMemberRole | DEContactRemovedFromGroup ContactId GroupInfo @@ -84,8 +86,10 @@ crDirectoryEvent_ = \case CEvtJoinedGroupMember {groupInfo, member = m} | pending m -> Just $ DEPendingMember groupInfo m | otherwise -> Nothing - CEvtNewChatItems {chatItems = AChatItem _ _ (GroupChat g _scopeInfo) ci : _} -> case ci of + CEvtNewChatItems {chatItems = AChatItem _ _ (GroupChat g scopeInfo) ci : _} -> case ci of ChatItem {chatDir = CIGroupRcv m, content = CIRcvMsgContent (MCText t)} | pending m -> Just $ DEPendingMemberMsg g m (chatItemId' ci) t + -- only moderate prohibited content in the main group, not in member-support/onboarding scope + ChatItem {chatDir = CIGroupRcv m, content = CIRcvGroupFeatureRejected gf} | isNothing scopeInfo -> Just $ DEGroupItemProhibited g m (chatItemId' ci) gf _ -> Nothing CEvtMemberRole {groupInfo, member, toRole} | groupMemberId' member == groupMemberId' (membership groupInfo) -> Just $ DEServiceRoleChanged groupInfo toRole diff --git a/apps/simplex-directory-service/src/Directory/Options.hs b/apps/simplex-directory-service/src/Directory/Options.hs index 5d51023781..23115ec7c7 100644 --- a/apps/simplex-directory-service/src/Directory/Options.hs +++ b/apps/simplex-directory-service/src/Directory/Options.hs @@ -44,6 +44,9 @@ data DirectoryOpts = DirectoryOpts searchResults :: Int, webFolder :: Maybe FilePath, linkCheckInterval :: Int, + prohibitedToObserver :: Bool, + alwaysCaptcha :: Bool, + knocking :: Bool, testing :: Bool } @@ -177,6 +180,21 @@ directoryOpts appDir defaultDbName = do <> help "Interval in seconds to check public group link data (default: 1800)" <> value 1800 ) + prohibitedToObserver <- + switch + ( long "prohibited-to-observer" + <> help "Set a member to observer (and delete the message) when they post content prohibited by the group's settings" + ) + alwaysCaptcha <- + switch + ( long "always-captcha" + <> help "Require a captcha from joining members in all groups, regardless of per-group filter settings" + ) + knocking <- + switch + ( long "knocking" + <> help "Require admin review (knocking) before joining members are admitted in all groups, regardless of group preference" + ) pure DirectoryOpts { coreOptions, @@ -199,6 +217,9 @@ directoryOpts appDir defaultDbName = do searchResults = 10, webFolder, linkCheckInterval, + prohibitedToObserver, + alwaysCaptcha, + knocking, testing = False } diff --git a/apps/simplex-directory-service/src/Directory/Service.hs b/apps/simplex-directory-service/src/Directory/Service.hs index 63e1a0ff69..318fc210ee 100644 --- a/apps/simplex-directory-service/src/Directory/Service.hs +++ b/apps/simplex-directory-service/src/Directory/Service.hs @@ -271,7 +271,7 @@ directoryService st opts cfg = do acceptMemberHook :: DirectoryOpts -> ServiceState -> GroupInfo -> GroupLinkInfo -> Profile -> IO (Either GroupRejectionReason (GroupAcceptance, GroupMemberRole)) acceptMemberHook - DirectoryOpts {profileNameLimit} + DirectoryOpts {profileNameLimit, alwaysCaptcha, knocking} ServiceState {blockedWordsCfg} g GroupLinkInfo {memberRole} @@ -280,7 +280,8 @@ acceptMemberHook when (useMemberFilter img $ rejectNames a) checkName pure $ if - | useMemberFilter img (passCaptcha a) -> (GAPendingApproval, GRMember) + | knocking -> (GAPendingReview, memberRole) + | alwaysCaptcha || useMemberFilter img (passCaptcha a) -> (GAPendingApproval, GRMember) | useMemberFilter img (makeObserver a) -> (GAAccepted, GRObserver) | otherwise -> (GAAccepted, memberRole) where @@ -294,6 +295,11 @@ acceptMemberHook groupMemberAcceptance :: GroupInfo -> DirectoryMemberAcceptance groupMemberAcceptance GroupInfo {customData} = (\DirectoryGroupData {memberAcceptance = ma} -> ma) $ fromCustomData customData +recommendedSettingsNotice :: UserGroupRegId -> Text +recommendedSettingsNotice userGroupId = + "We recommend allowing direct messages, media, voice, and SimpleX links only for group moderators and admins. Use group preferences to set them.\n\ + \Captcha verification is enabled. Use /'filter " <> tshow userGroupId <> "' to change it." + useMemberFilter :: Maybe ImageData -> Maybe ProfileCondition -> Bool useMemberFilter img_ = \case Just PCAll -> True @@ -311,7 +317,7 @@ readBlockedWordsConfig DirectoryOpts {blockedFragmentsFile, blockedWordsFile, na pure BlockedWordsConfig {blockedFragments, blockedWords, extensionRules, spelling} directoryServiceEvent :: DirectoryLog -> DirectoryOpts -> ServiceState -> User -> ChatController -> DirectoryEvent -> IO () -directoryServiceEvent st opts@DirectoryOpts {adminUsers, superUsers, serviceName, ownersGroup, searchResults} env@ServiceState {searchRequests} user@User {userId} cc = \case +directoryServiceEvent st opts@DirectoryOpts {adminUsers, superUsers, serviceName, ownersGroup, searchResults, prohibitedToObserver, alwaysCaptcha} env@ServiceState {searchRequests} user@User {userId} cc = \case DEContactConnected ct -> deContactConnected ct DEGroupInvitation {contact = ct, groupInfo = g, fromMemberRole, memberRole} -> deGroupInvitation ct g fromMemberRole memberRole DEServiceJoinedGroup ctId g owner -> deServiceJoinedGroup ctId g owner @@ -319,6 +325,7 @@ directoryServiceEvent st opts@DirectoryOpts {adminUsers, superUsers, serviceName DEGroupLinkCheck g -> deGroupLinkCheck g DEPendingMember g m -> dePendingMember g m DEPendingMemberMsg g m ciId t -> dePendingMemberMsg g m ciId t + DEGroupItemProhibited g m ciId gf -> when prohibitedToObserver $ deGroupItemProhibited g m ciId gf DEContactRoleChanged g ctId role -> deContactRoleChanged g ctId role DEServiceRoleChanged g role -> deServiceRoleChanged g role DEContactRemovedFromGroup ctId g -> deContactRemovedFromGroup ctId g @@ -404,7 +411,7 @@ directoryServiceEvent st opts@DirectoryOpts {adminUsers, superUsers, serviceName processInvitation :: Contact -> GroupInfo -> Maybe GroupReg -> IO () processInvitation ct g@GroupInfo {groupId, groupProfile = GroupProfile {displayName}} = \case - Nothing -> addGroupReg notifyAdminUsers st cc ct g GRSProposed joinGroup + Nothing -> addGroupReg notifyAdminUsers st cc user ct g GRSProposed joinGroup Just _gr -> setGroupStatus notifyAdminUsers st env cc groupId GRSProposed joinGroup where joinGroup _ = do @@ -436,7 +443,7 @@ directoryServiceEvent st opts@DirectoryOpts {adminUsers, superUsers, serviceName Left e -> sendMessage cc ct $ "Error: getDuplicateGroup. Please notify the developers.\n" <> T.pack e where askConfirmation = - addGroupReg notifyAdminUsers st cc ct g GRSPendingConfirmation $ \GroupReg {userGroupRegId} -> do + addGroupReg notifyAdminUsers st cc user ct g GRSPendingConfirmation $ \GroupReg {userGroupRegId} -> do sendMessage cc ct $ "The group " <> groupNameDescr p <> " is already submitted to the directory.\nTo confirm the registration, please send:" sendMessage cc ct $ "/confirm " <> tshow userGroupRegId <> ":" <> viewName displayName @@ -488,6 +495,7 @@ directoryServiceEvent st opts@DirectoryOpts {adminUsers, superUsers, serviceName \Please add it to the group welcome message.\n\ \For example, add:" notifyOwner gr' $ "Link to join the group " <> displayName <> ": " <> groupLinkText gLink + notifyOwner gr' $ recommendedSettingsNotice (userGroupRegId gr') Left (ChatError e) -> case e of CEGroupUserRole {} -> notifyOwner gr "Failed creating group link, as service is no longer an admin." CEGroupMemberUserRemoved -> notifyOwner gr "Failed creating group link, as service is removed from the group." @@ -552,8 +560,8 @@ directoryServiceEvent st opts@DirectoryOpts {adminUsers, superUsers, serviceName <> ".\nIt is hidden from the directory until approved." notifyAdminUsers $ "The " <> gt <> " " <> groupRef <> " is updated" <> byMember <> "." sendToApprove g' gr' n' - sendChatCmd cc (APIConnectPlan userId (Just link) True Nothing) >>= \case - Right (CRConnectionPlan _ _ (CPGroupLink (GLPKnown {groupInfo = g'}))) -> + sendChatCmd cc (APIConnectPlan userId (Just (aConnectTarget link)) PRMAllGroups Nothing) >>= \case + Right (CRConnectionPlan _ _ _ _ (CPGroupLink (GLPKnown {groupInfo = g'}))) -> case dbOwnerMemberId gr of Just ownerGMId -> withDB "getGroupMember" cc (\db -> withExceptT show $ getGroupMember db (storeCxt cc) user groupId ownerGMId) >>= \case @@ -650,6 +658,19 @@ directoryServiceEvent st opts@DirectoryOpts {adminUsers, superUsers, serviceName "Captcha is generated by SimpleX Directory service.\n\n*Send captcha text* to join the group " <> displayName <> "." <> if canSendVoiceCaptcha g m then "\nSend /audio to receive a voice captcha." else "" + -- gated by --prohibited-to-observer at the dispatch above + deGroupItemProhibited :: GroupInfo -> GroupMember -> ChatItemId -> GroupFeature -> IO () + deGroupItemProhibited GroupInfo {groupId} m@GroupMember {memberRole} ciId gf = + when (memberRole == GRMember) $ do + let gmId = groupMemberId' m + logInfo $ "Member " <> tshow gmId <> " posted prohibited content (" <> tshow gf <> ") in group " <> tshow groupId <> "; deleting and setting to observer" + sendChatCmd cc (APIDeleteMemberChatItem groupId [ciId]) >>= \case + Right CRChatItemsDeleted {} -> pure () + r -> logError $ "deGroupItemProhibited: unexpected delete response: " <> tshow r + sendChatCmd cc (APIMembersRole groupId [gmId] GRObserver) >>= \case + Right CRMembersRoleUser {} -> pure () -- empty members = already observer (idempotent), still success + r -> logError $ "deGroupItemProhibited: unexpected set observer response: " <> tshow r + sendMemberCaptcha :: GroupInfo -> GroupMember -> Maybe ChatItemId -> Text -> Int -> CaptchaMode -> IO () sendMemberCaptcha GroupInfo {groupId} m quotedId noticeText prevAttempts mode = do s <- getCaptchaStr captchaLength "" @@ -776,7 +797,7 @@ directoryServiceEvent st opts@DirectoryOpts {adminUsers, superUsers, serviceName memberRequiresCaptcha :: DirectoryMemberAcceptance -> GroupMember -> Bool memberRequiresCaptcha a GroupMember {memberProfile = LocalProfile {image}} = - useMemberFilter image $ passCaptcha a + alwaysCaptcha || useMemberFilter image (passCaptcha a) sendToApprove :: GroupInfo -> GroupReg -> GroupApprovalId -> IO () sendToApprove GroupInfo {groupId, groupProfile = p@GroupProfile {displayName, image = image', publicGroup = pg_}, groupSummary} GroupReg {dbContactId, promoted} gaId = do @@ -797,11 +818,11 @@ directoryServiceEvent st opts@DirectoryOpts {adminUsers, superUsers, serviceName forM_ pg_ $ \pg@PublicGroupProfile {groupLink} -> when (groupRegStatus == GRSActive || pendingApproval groupRegStatus) $ do let link = ACL SCMContact $ CLShort groupLink - sendChatCmd cc (APIConnectPlan userId (Just link) True Nothing) >>= \case - Right (CRConnectionPlan _ _ (CPGroupLink (GLPKnown {groupInfo = g', groupUpdated = BoolDef updated, linkOwners = ListDef owners}))) -> + sendChatCmd cc (APIConnectPlan userId (Just (aConnectTarget link)) PRMAllGroups Nothing) >>= \case + Right (CRConnectionPlan _ _ _ _ (CPGroupLink (GLPKnown {groupInfo = g', groupUpdated, linkOwners = ListDef owners}))) -> checkValidOwner dbOwnerMemberId owners $ do - when updated $ reapprove pg gr groupRegStatus g' - when (updated || summary /= groupSummary g') $ listingsUpdated env + when groupUpdated $ reapprove pg gr groupRegStatus g' + when (groupUpdated || summary /= groupSummary g') $ listingsUpdated env Left (ChatErrorAgent {agentError = SMP _ err}) | linkDeleted err -> setGroupStatus logError st env cc groupId GRSRemoved $ \gr' -> notifyOwner gr' "The channel link is no longer valid.\nThe channel is removed from the directory." @@ -933,8 +954,8 @@ directoryServiceEvent st opts@DirectoryOpts {adminUsers, superUsers, serviceName let link = ACL SCMContact $ CLShort connLink mId = MemberId oIdBytes gt' = groupTypeStr gt - sendChatCmd cc (APIConnectPlan userId (Just link) True (Just ownerSig)) >>= \case - Right (CRConnectionPlan _ (ACCL SCMContact ccLink) plan) -> + sendChatCmd cc (APIConnectPlan userId (Just (aConnectTarget link)) PRMAllGroups (Just ownerSig)) >>= \case + Right (CRConnectionPlan _ (ACCL SCMContact ccLink) _ _ plan) -> handleGroupLinkPlan ct ccLink mId ownerSig gt' plan _ -> sendMessage cc ct "Error: could not connect. Please report it to directory admins." deChatLinkReceived ct (MCLGroup {groupProfile = GroupProfile {publicGroup = Just pg}}) _ = @@ -963,8 +984,8 @@ directoryServiceEvent st opts@DirectoryOpts {adminUsers, superUsers, serviceName (_, Just (OVFailed reason)) -> sendMessage cc ct $ "Link signature verification failed: " <> reason <> ".\nYou must be the " <> gt <> " owner to register it." (Nothing, _) -> sendMessage cc ct $ "Error: no " <> gt <> " information available via the link." _ -> sendMessage cc ct $ "Error: could not verify " <> gt <> " ownership. Please report it to directory admins." - GLPKnown {groupInfo = g, groupUpdated = BoolDef updated, ownerVerification} -> case ownerVerification of - Just OVVerified -> deReregistration ct g updated ownerSig + GLPKnown {groupInfo = g, groupUpdated, ownerVerification} -> case ownerVerification of + Just OVVerified -> deReregistration ct g groupUpdated ownerSig Just (OVFailed reason) -> sendMessage cc ct $ "Link signature verification failed: " <> reason <> ".\nYou must be the " <> gt <> " owner to register it." Nothing -> sendMessage cc ct $ "Error: could not verify " <> gt <> " ownership." GLPConnectingProhibit _ -> sendMessage cc ct $ "Already connecting to this " <> gt <> "." @@ -979,10 +1000,10 @@ directoryServiceEvent st opts@DirectoryOpts {adminUsers, superUsers, serviceName let GroupShortLinkData {groupProfile = GroupProfile {displayName}} = groupSLinkData ownerContact = GroupOwnerContact {contactId = contactId' ct, memberId = mId} sendMessage cc ct $ "Joining the " <> gt <> " " <> displayName <> "…" - sendChatCmd cc (APIPrepareGroup userId ccLink False groupSLinkData) >>= \case + sendChatCmd cc (APIPrepareGroup userId ccLink False Nothing groupSLinkData) >>= \case Right (CRNewPreparedChat _ (AChat SCTGroup (Chat (GroupChat gInfo _) _ _))) -> do let gId = groupId' gInfo - addGroupReg notifyAdminUsers st cc ct gInfo GRSProposed $ \_ -> pure () + addGroupReg notifyAdminUsers st cc user ct gInfo GRSProposed $ \_ -> pure () sendChatCmd cc (APIConnectPreparedGroup gId False (Just ownerContact) Nothing) >>= \case Right CRStartedConnectionToGroup {groupInfo = gInfo'} -> withDB "getGroupMember" cc (\db -> withExceptT show $ getGroupMemberByMemberId db (storeCxt cc) user gInfo' mId) >>= \case @@ -1007,7 +1028,7 @@ directoryServiceEvent st opts@DirectoryOpts {adminUsers, superUsers, serviceName | contactId' ct `isOwner` gr -> sameOwnerReregistration gr gt | otherwise -> sendMessage cc ct $ "This " <> gt <> " is registered by another owner." Left _ -> - addGroupReg notifyAdminUsers st cc ct g (GRSPendingApproval 1) $ \gr -> do + addGroupReg notifyAdminUsers st cc user ct g (GRSPendingApproval 1) $ \gr -> do void $ setGroupRegOwner cc groupId ownerMember sendToApprove g gr 1 | role < GROwner -> sendMessage cc ct $ "You must be the " <> gt <> " owner to register it." @@ -1045,6 +1066,7 @@ directoryServiceEvent st opts@DirectoryOpts {adminUsers, superUsers, serviceName in if role >= GROwner then setGroupStatus notifyAdminUsers st env cc groupId (GRSPendingApproval 1) $ \gr' -> do notifyOwner gr' $ "Joined the " <> gt <> " " <> displayName <> ". Registration is pending approval — it may take up to 48 hours." + notifyOwner gr' $ recommendedSettingsNotice (userGroupRegId gr') sendToApprove g gr' 1 else do setGroupStatus notifyAdminUsers st env cc groupId GRSRemoved $ \_ -> pure () @@ -1484,12 +1506,16 @@ setGroupStatusPromo sendReply st env cc GroupReg {dbGroupId = gId} grStatus' grP logGUpdatePromotion st gId grPromoted' continue -addGroupReg :: (Text -> IO ()) -> DirectoryLog -> ChatController -> Contact -> GroupInfo -> GroupRegStatus -> (GroupReg -> IO ()) -> IO () -addGroupReg sendMsg st cc ct g@GroupInfo {groupId} grStatus continue = +addGroupReg :: (Text -> IO ()) -> DirectoryLog -> ChatController -> User -> Contact -> GroupInfo -> GroupRegStatus -> (GroupReg -> IO ()) -> IO () +addGroupReg sendMsg st cc user ct g@GroupInfo {groupId} grStatus continue = addGroupRegStore cc ct g grStatus >>= \case Left e -> sendMsg $ "Error creating group registation for group " <> tshow groupId <> ": " <> T.pack e Right gr -> do logGCreate st gr + let d = toCustomData $ DirectoryGroupData newGroupJoinFilter + withDB' "setGroupCustomData" cc (\db -> setGroupCustomData db user g $ Just d) >>= \case + Right () -> pure () + Left e -> sendMsg $ "Error setting default captcha for group " <> tshow groupId <> ": " <> T.pack e continue gr setGroupStatus :: (Text -> IO ()) -> DirectoryLog -> ServiceState -> ChatController -> GroupId -> GroupRegStatus -> (GroupReg -> IO ()) -> IO () diff --git a/apps/simplex-directory-service/src/Directory/Store.hs b/apps/simplex-directory-service/src/Directory/Store.hs index 89c5178f7d..a9a9788e0f 100644 --- a/apps/simplex-directory-service/src/Directory/Store.hs +++ b/apps/simplex-directory-service/src/Directory/Store.hs @@ -52,6 +52,7 @@ module Directory.Store basicJoinFilter, moderateJoinFilter, strongJoinFilter, + newGroupJoinFilter, groupDBError, logGCreate, logGDelete, @@ -164,6 +165,16 @@ strongJoinFilter = makeObserver = Nothing } +-- Default applied to newly registered groups: a captcha challenge is required +-- from every joining member unless the owner changes it with /filter. +newGroupJoinFilter :: DirectoryMemberAcceptance +newGroupJoinFilter = + DirectoryMemberAcceptance + { rejectNames = Nothing, + passCaptcha = Just PCAll, + makeObserver = Nothing + } + type UserGroupRegId = Int64 type GroupApprovalId = Int64 diff --git a/bots/api/COMMANDS.md b/bots/api/COMMANDS.md index d14435cabd..28ece08908 100644 --- a/bots/api/COMMANDS.md +++ b/bots/api/COMMANDS.md @@ -1363,28 +1363,28 @@ ChatCmdError: Command error (only used in WebSockets API). ### APIConnectPlan -Determine SimpleX link type and if the bot is already connected via this link. +Determine SimpleX link type and if the bot is already connected via this link or name. *Network usage*: interactive. **Parameters**: - userId: int64 -- connectionLink: string? -- resolveKnown: bool +- connectTarget: string? +- resolveMode: [PlanResolveMode](./TYPES.md#planresolvemode) - linkOwnerSig: [LinkOwnerSig](./TYPES.md#linkownersig)? **Syntax**: ``` -/_connect plan +/_connect plan ``` ```javascript -'/_connect plan ' + userId + ' ' + connectionLink // JavaScript +'/_connect plan ' + userId + ' ' + connectTarget // JavaScript ``` ```python -'/_connect plan ' + str(userId) + ' ' + connectionLink # Python +'/_connect plan ' + str(userId) + ' ' + connectTarget # Python ``` **Responses**: @@ -1393,6 +1393,8 @@ ConnectionPlan: Connection link information. - type: "connectionPlan" - user: [User](./TYPES.md#user) - connLink: [CreatedConnLink](./TYPES.md#createdconnlink) +- planSimplexName: [SimplexNameInfo](./TYPES.md#simplexnameinfo)? +- otherSimplexName: [SimplexNameInfo](./TYPES.md#simplexnameinfo)? - connectionPlan: [ConnectionPlan](./TYPES.md#connectionplan) ChatCmdError: Command error (only used in WebSockets API). @@ -1455,26 +1457,26 @@ ChatCmdError: Command error (only used in WebSockets API). ### Connect -Connect via SimpleX link as string in the active user profile. +Connect via SimpleX link or name as string in the active user profile. *Network usage*: interactive. **Parameters**: - incognito: bool -- connLink_: string? +- connTarget_: string? **Syntax**: ``` -/connect[ ] +/connect[ ] ``` ```javascript -'/connect' + (connLink_ ? ' ' + connLink_ : '') // JavaScript +'/connect' + (connTarget_ ? ' ' + connTarget_ : '') // JavaScript ``` ```python -'/connect' + ((' ' + connLink_) if connLink_ is not None else '') # Python +'/connect' + ((' ' + connTarget_) if connTarget_ is not None else '') # Python ``` **Responses**: diff --git a/bots/api/TYPES.md b/bots/api/TYPES.md index b38e3f6c6e..ce5c834001 100644 --- a/bots/api/TYPES.md +++ b/bots/api/TYPES.md @@ -139,12 +139,14 @@ This file is generated automatically. - [MsgReaction](#msgreaction) - [MsgReceiptStatus](#msgreceiptstatus) - [MsgSigStatus](#msgsigstatus) +- [NameErrorType](#nameerrortype) - [NetworkError](#networkerror) - [NewUser](#newuser) - [NoteFolder](#notefolder) - [OwnerVerification](#ownerverification) - [PaginationByTime](#paginationbytime) - [PendingContactConnection](#pendingcontactconnection) +- [PlanResolveMode](#planresolvemode) - [PrefEnabled](#prefenabled) - [Preferences](#preferences) - [PreparedContact](#preparedcontact) @@ -172,8 +174,11 @@ This file is generated automatically. - [SMPAgentError](#smpagenterror) - [SecurityCode](#securitycode) - [SimplePreference](#simplepreference) +- [SimplexDomain](#simplexdomain) +- [SimplexDomainClaim](#simplexdomainclaim) +- [SimplexDomainError](#simplexdomainerror) +- [SimplexDomainProof](#simplexdomainproof) - [SimplexLinkType](#simplexlinktype) -- [SimplexNameDomain](#simplexnamedomain) - [SimplexNameInfo](#simplexnameinfo) - [SimplexNameType](#simplexnametype) - [SimplexTLD](#simplextld) @@ -313,6 +318,9 @@ FILE: - type: "FILE" - fileErr: [FileErrorType](#fileerrortype) +NO_NAME_SERVERS: +- type: "NO_NAME_SERVERS" + PROXY: - type: "PROXY" - proxyServer: string @@ -1104,6 +1112,14 @@ ChatStoreChanged: InvalidConnReq: - type: "invalidConnReq" +SimplexDomainNotReady: +- type: "simplexDomainNotReady" +- simplexDomain: [SimplexDomain](#simplexdomain) +- simplexDomainError: [SimplexDomainError](#simplexdomainerror) + +NotResolvedLocally: +- type: "notResolvedLocally" + UnsupportedConnReq: - type: "unsupportedConnReq" @@ -1976,6 +1992,10 @@ EXPIRED: INTERNAL: - type: "INTERNAL" +NAME: +- type: "NAME" +- nameErr: [NameErrorType](#nameerrortype) + DUPLICATE_: - type: "DUPLICATE_" @@ -2330,6 +2350,7 @@ MemberSupport: - membersRequireAttention: int - viaGroupLinkUri: string? - groupKeys: [GroupKeys](#groupkeys)? +- groupDomainVerified: bool? --- @@ -2753,6 +2774,8 @@ Unknown: - peerType: [ChatPeerType](#chatpeertype)? - localBadge: [LocalBadge](#localbadge)? - localAlias: string +- contactDomain: [SimplexDomainClaim](#simplexdomainclaim)? +- contactDomainVerified: bool? --- @@ -2928,6 +2951,23 @@ Unknown: - "signedNoKey" +--- + +## NameErrorType + +**Discriminated union type**: + +NO_RESOLVER: +- type: "NO_RESOLVER" + +NOT_FOUND: +- type: "NOT_FOUND" + +RESOLVER: +- type: "RESOLVER" +- resolverErr: string + + --- ## NetworkError @@ -3038,6 +3078,16 @@ count= - updatedAt: UTCTime +--- + +## PlanResolveMode + +**Enum type**: +- "allGroups" +- "unknown" +- "never" + + --- ## PrefEnabled @@ -3098,6 +3148,7 @@ count= - preferences: [Preferences](#preferences)? - peerType: [ChatPeerType](#chatpeertype)? - badge: [BadgeProof](#badgeproof)? +- contactDomain: [SimplexDomainClaim](#simplexdomainclaim)? --- @@ -3146,7 +3197,7 @@ NO_SESSION: **Record type**: - groupWebPage: string? -- groupDomain: string? +- groupDomainClaim: [SimplexDomainClaim](#simplexdomainclaim)? - domainWebPage: bool - allowEmbedding: bool @@ -3530,6 +3581,48 @@ A_QUEUE: - allow: [FeatureAllowed](#featureallowed) +--- + +## SimplexDomain + +**Record type**: +- nameTLD: [SimplexTLD](#simplextld) +- domain: string +- subDomain: [string] + + +--- + +## SimplexDomainClaim + +**Record type**: +- domain: string +- proof: [SimplexDomainProof](#simplexdomainproof)? + + +--- + +## SimplexDomainError + +**Discriminated union type**: + +NoValidLink: +- type: "noValidLink" + +UnknownDomain: +- type: "unknownDomain" + + +--- + +## SimplexDomainProof + +**Record type**: +- linkOwnerId: string? +- presHeader: string +- signature: string + + --- ## SimplexLinkType @@ -3542,23 +3635,13 @@ A_QUEUE: - "relay" ---- - -## SimplexNameDomain - -**Record type**: -- nameTLD: [SimplexTLD](#simplextld) -- domain: string -- subDomain: [string] - - --- ## SimplexNameInfo **Record type**: - nameType: [SimplexNameType](#simplexnametype) -- nameDomain: [SimplexNameDomain](#simplexnamedomain) +- nameDomain: [SimplexDomain](#simplexdomain) --- diff --git a/bots/src/API/Docs/Commands.hs b/bots/src/API/Docs/Commands.hs index 8ebd510a55..ddfc817fa2 100644 --- a/bots/src/API/Docs/Commands.hs +++ b/bots/src/API/Docs/Commands.hs @@ -135,10 +135,10 @@ chatCommandsDocsData = ( "Connection commands", "These commands may be used to create connections. Most bots do not need to use them - bot users will connect via bot address with auto-accept enabled.", [ ("APIAddContact", [], "Create 1-time invitation link.", ["CRInvitation", "CRChatCmdError"], [], Just UNInteractive, "/_connect " <> Param "userId" <> OnOffParam "incognito" "incognito" (Just False)), - -- `Maybe` in `connectionLink :: Maybe AConnectionLink` is used to signal link parsing error to the runtime (the handler returns CEInvalidConnReq on Nothing); it is NOT API-level optionality. The parameter is required from callers. - ("APIConnectPlan", [], "Determine SimpleX link type and if the bot is already connected via this link.", ["CRConnectionPlan", "CRChatCmdError"], [], Just UNInteractive, "/_connect plan " <> Param "userId" <> " " <> Param "connectionLink"), + -- `Maybe` in `connectTarget :: Maybe ConnectTarget` is used to signal parse failure to the runtime (the handler returns CEInvalidConnReq on Nothing); it is NOT API-level optionality. The parameter is required from callers. + ("APIConnectPlan", [], "Determine SimpleX link type and if the bot is already connected via this link or name.", ["CRConnectionPlan", "CRChatCmdError"], [], Just UNInteractive, "/_connect plan " <> Param "userId" <> " " <> Param "connectTarget"), ("APIConnect", [], "Connect via prepared SimpleX link. The link can be 1-time invitation link, contact address or group link.", ["CRSentConfirmation", "CRContactAlreadyExists", "CRSentInvitation", "CRChatCmdError"], [], Just UNInteractive, "/_connect " <> Param "userId" <> Optional "" (" " <> Param "$0") "preparedLink_"), - ("Connect", [], "Connect via SimpleX link as string in the active user profile.", ["CRSentConfirmation", "CRContactAlreadyExists", "CRSentInvitation", "CRChatCmdError"], [], Just UNInteractive, "/connect" <> Optional "" (" " <> Param "$0") "connLink_"), + ("Connect", [], "Connect via SimpleX link or name as string in the active user profile.", ["CRSentConfirmation", "CRContactAlreadyExists", "CRSentInvitation", "CRChatCmdError"], [], Just UNInteractive, "/connect" <> Optional "" (" " <> Param "$0") "connTarget_"), ("APIAcceptContact", ["incognito"], "Accept contact request.", ["CRAcceptingContactRequest", "CRChatCmdError"], [], Just UNInteractive, "/_accept " <> Param "contactReqId"), ("APIRejectContact", [], "Reject contact request. The user who sent the request is **not notified**.", ["CRContactRequestRejected", "CRChatCmdError"], [], Nothing, "/_reject " <> Param "contactReqId") ] @@ -410,9 +410,11 @@ undocumentedCommands = "APISetMemberSettings", "APISetNetworkConfig", "APISetNetworkInfo", + "APISetPublicGroupAccess", "APISetServerOperators", "APISetUserContactReceipts", "APISetUserGroupReceipts", + "APISetUserDomain", "APISetUserServers", "APISetUserUIThemes", "APIShareChatMsgContent", @@ -432,7 +434,9 @@ undocumentedCommands = "APIUserRead", "APIValidateServers", "APIVerifyContact", + "APIVerifyContactDomain", "APIVerifyGroupMember", + "APIVerifyGroupDomain", "APIVerifyToken", "CheckChatRunning", "ConfirmRemoteCtrl", diff --git a/bots/src/API/Docs/Responses.hs b/bots/src/API/Docs/Responses.hs index ddd127241b..f897fc3908 100644 --- a/bots/src/API/Docs/Responses.hs +++ b/bots/src/API/Docs/Responses.hs @@ -148,6 +148,7 @@ undocumentedResponses = "CRContactAliasUpdated", "CRContactCode", "CRContactInfo", + "CRContactDomainVerified", "CRContactRatchetSyncStarted", "CRContactSwitchAborted", "CRContactSwitchStarted", @@ -167,6 +168,7 @@ undocumentedResponses = "CRGroupMemberRatchetSyncStarted", "CRGroupMemberSwitchAborted", "CRGroupMemberSwitchStarted", + "CRGroupDomainVerified", "CRGroupProfile", "CRGroupUserChanged", "CRItemsReadForChat", diff --git a/bots/src/API/Docs/Types.hs b/bots/src/API/Docs/Types.hs index 6313c68838..35ea9fe261 100644 --- a/bots/src/API/Docs/Types.hs +++ b/bots/src/API/Docs/Types.hs @@ -34,7 +34,8 @@ import Simplex.Chat.Store.Profiles import Simplex.Chat.Store.Shared import Simplex.Chat.Operators import Simplex.Messaging.Agent.Store.Entity (DBStored (..)) -import Simplex.Chat.Badges (BadgeInfo (..), BadgeProof (..), BadgeStatus (..), BadgeType (..), JSONBadge (..)) +import Simplex.Chat.Badges +import Simplex.Chat.Names import Simplex.Chat.Types import Simplex.Chat.Types.Preferences import Simplex.Chat.Types.Shared @@ -45,7 +46,7 @@ import Simplex.Messaging.Agent.Protocol import Simplex.Messaging.Client import Simplex.Messaging.Crypto.File import Simplex.Messaging.Parsers (dropPrefix, fstToLower) -import Simplex.Messaging.Protocol (BlockingInfo (..), BlockingReason (..), CommandError (..), ErrorType (..), NetworkError (..), ProxyError (..)) +import Simplex.Messaging.Protocol (BlockingInfo (..), BlockingReason (..), CommandError (..), ErrorType (..), NameErrorType (..), NetworkError (..), ProxyError (..)) import Simplex.Messaging.Protocol.Types (ClientNotice (..)) import Simplex.Messaging.Transport import Simplex.RemoteControl.Types @@ -321,11 +322,13 @@ chatTypesDocsData = (sti @MsgReaction, STUnion, "MR", [], "", ""), (sti @MsgReceiptStatus, STEnum, "MR", [], "", ""), (sti @MsgSigStatus, STEnum, "MSS", [], "", ""), + (sti @NameErrorType, STUnion, "", [], "", ""), (sti @NetworkError, STUnion, "NE", [], "", ""), (sti @NewUser, STRecord, "", [], "", ""), (sti @NoteFolder, STRecord, "", [], "", ""), (sti @OwnerVerification, STUnion, "OV", [], "", ""), (sti @PendingContactConnection, STRecord, "", [], "", ""), + (sti @PlanResolveMode, STEnum, "PRM", [], "", ""), (sti @PrefEnabled, STRecord, "", [], "", ""), (sti @Preferences, STRecord, "", [], "", ""), (sti @PreparedContact, STRecord, "", [], "", ""), @@ -353,8 +356,11 @@ chatTypesDocsData = (sti @RoleGroupPreference, STRecord, "", [], "", ""), (sti @SecurityCode, STRecord, "", [], "", ""), (sti @SimplePreference, STRecord, "", [], "", ""), + (sti @SimplexDomain, STRecord, "", [], "", ""), + (sti @SimplexDomainClaim, STRecord, "", [], "", ""), + (sti @SimplexDomainError, STUnion, "SDE", [], "", ""), + (sti @SimplexDomainProof, STRecord, "", [], "", ""), (sti @SimplexLinkType, STEnum, "XL", [], "", ""), - (sti @SimplexNameDomain, STRecord, "", [], "", ""), (sti @SimplexNameInfo, STRecord, "", [], "", ""), (sti @SimplexNameType, STEnum, "NT", [], "", ""), (sti @SimplexTLD, STEnum, "TLD", [], "", ""), @@ -548,11 +554,13 @@ deriving instance Generic MsgFilter deriving instance Generic MsgReaction deriving instance Generic MsgReceiptStatus deriving instance Generic MsgSigStatus +deriving instance Generic NameErrorType deriving instance Generic NetworkError deriving instance Generic NewUser deriving instance Generic NoteFolder deriving instance Generic OwnerVerification deriving instance Generic PendingContactConnection +deriving instance Generic PlanResolveMode deriving instance Generic PrefEnabled deriving instance Generic Preferences deriving instance Generic PreparedContact @@ -578,8 +586,11 @@ deriving instance Generic RelayProfile deriving instance Generic RelayStatus deriving instance Generic ReportReason deriving instance Generic SecurityCode +deriving instance Generic SimplexDomain +deriving instance Generic SimplexDomainClaim +deriving instance Generic SimplexDomainError +deriving instance Generic SimplexDomainProof deriving instance Generic SimplexLinkType -deriving instance Generic SimplexNameDomain deriving instance Generic SimplexNameInfo deriving instance Generic SimplexNameType deriving instance Generic SimplexTLD diff --git a/bots/src/API/TypeInfo.hs b/bots/src/API/TypeInfo.hs index c5a3b11953..f949a2f92f 100644 --- a/bots/src/API/TypeInfo.hs +++ b/bots/src/API/TypeInfo.hs @@ -194,6 +194,7 @@ toTypeInfo tr = primitiveToLower st@(ST t ps) = let t' = fstToLower t in if t' `elem` primitiveTypes then ST t' ps else st stringTypes = [ "AConnectionLink", + "AConnectTarget", "AProtocolType", "AgentConnId", "AgentInvId", @@ -215,11 +216,13 @@ toTypeInfo tr = "Text", "MREmojiChar", "PrivateKey", + "ProofPresHeader", "PublicKey", "ProtocolServer", "SbKey", "SharedMsgId", "Signature", + "StrJSON", "TransportHost", "UIColor", "UserPwd", diff --git a/cabal.project b/cabal.project index 516d029b11..c66e079518 100644 --- a/cabal.project +++ b/cabal.project @@ -21,7 +21,7 @@ constraints: zip +disable-bzip2 +disable-zstd source-repository-package type: git location: https://github.com/simplex-chat/simplexmq.git - tag: 98391fd677f547f610a17c48cc96d8c4b2d5e96e + tag: 551de8039fbfcbc75d8e2685a4c631a55ae28fb2 source-repository-package type: git diff --git a/docs/guide/README.md b/docs/guide/README.md index ad3849d1d3..fe1546af0a 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -12,6 +12,7 @@ The first messaging platform that has no user identifiers of any kind — 100% p - [Secret groups](./secret-groups.md) - [Channel webpage](./channel-webpage.md) - [Chat profiles](./chat-profiles.md) +- [Registering a SimpleX name](./register-simplex-name.md) - [Managing data](./managing-data.md) - [Audio & video calls](./audio-video-calls.md) - [Privacy & security](./privacy-security.md) diff --git a/docs/guide/diagrams/simplex-name-steps.mmd b/docs/guide/diagrams/simplex-name-steps.mmd new file mode 100644 index 0000000000..ca19d3c6f3 --- /dev/null +++ b/docs/guide/diagrams/simplex-name-steps.mmd @@ -0,0 +1,19 @@ +flowchart TD + S([Start]) --> A["Step 1: Create a wallet
save your recovery phrase"] + A --> B["Step 2: Register the name
connect wallet, search, choose years"] + B --> C["On Create your profile, paste your link into
SimpleX contact (@name) or SimpleX channel (#name)"] + C --> H["Confirm: two transactions,
60 seconds apart"] + H --> I["Step 3: search or type your name
shows 'Unconfirmed name'"] + I --> D{"A contact or a channel?"} + D -->|"@name (contact)"| J1["Step 4: set Your SimpleX name
in your SimpleX address"] + D -->|"#name (channel)"| J2["Step 4: set SimpleX name
in the channel"] + J1 --> K["Step 5: from another device,
search or type the name"] + J2 --> K + K --> Z([Connected. Name verified.]) + + classDef start fill:#f4ecf7,stroke:#8e44ad,color:#4a235a; + classDef step fill:#eaf2fb,stroke:#2e86de,color:#1b3a5b; + classDef ok fill:#d5f5e3,stroke:#27ae60,color:#145a32; + class S start; + class Z ok; + class A,B,C,H,I,J1,J2,K step; diff --git a/docs/guide/diagrams/simplex-name-steps.svg b/docs/guide/diagrams/simplex-name-steps.svg new file mode 100644 index 0000000000..4d062ec1c2 --- /dev/null +++ b/docs/guide/diagrams/simplex-name-steps.svg @@ -0,0 +1 @@ +

@name (contact)

#name (channel)

Start

Step 1: Create a wallet
save your recovery phrase

Step 2: Register the name
connect wallet, search, choose years

On Create your profile, paste your link into
SimpleX contact (@name) or SimpleX channel (#name)

Confirm: two transactions,
60 seconds apart

Step 3: search or type your name
shows 'Unconfirmed name'

A contact or a channel?

Step 4: set Your SimpleX name
in your SimpleX address

Step 4: set SimpleX name
in the channel

Step 5: from another device,
search or type the name

Connected. Name verified.

\ No newline at end of file diff --git a/docs/guide/images/before-we-start.png b/docs/guide/images/before-we-start.png new file mode 100644 index 0000000000..eb853fcd96 Binary files /dev/null and b/docs/guide/images/before-we-start.png differ diff --git a/docs/guide/images/create-your-profile.png b/docs/guide/images/create-your-profile.png new file mode 100644 index 0000000000..2d5e96d9ee Binary files /dev/null and b/docs/guide/images/create-your-profile.png differ diff --git a/docs/guide/images/register-name.png b/docs/guide/images/register-name.png new file mode 100644 index 0000000000..94584f54df Binary files /dev/null and b/docs/guide/images/register-name.png differ diff --git a/docs/guide/register-simplex-name.md b/docs/guide/register-simplex-name.md new file mode 100644 index 0000000000..df78b19844 --- /dev/null +++ b/docs/guide/register-simplex-name.md @@ -0,0 +1,123 @@ +--- +title: Registering a SimpleX name +--- + +# Registering a SimpleX name + +A SimpleX name lets people reach you by typing a short `@name` instead of pasting +a long link. You register the name on a website and add your SimpleX link to it, +then claim the name in the app, to connect it with your SimpleX address or +channel name. + +> Names currently run on a testing network. The registration page is +> [testing-names.simplex.chat](https://testing-names.simplex.chat) and names end +> in `.testing`. The steps stay the same when the main names launch. + +## What you need + +- A crypto wallet such as MetaMask. +- The SimpleX app. +- A link for the name to open: your **contact address** (for one-to-one chats), + your **channel link** (to join a channel), or both. + +## How it works + +Setting up a name takes two parts. On the website you register the name and add +your link, so people can find your link by name. In the app you set the same name +on your profile - to prevent any other names from opening your profile or channel. + +![Steps to register a SimpleX name](./diagrams/simplex-name-steps.svg) + +## Step 1. Create a wallet + +Install MetaMask (browser extension or mobile app) and create a wallet. Write +down your recovery phrase somewhere safe and offline, as anyone with that phrase +controls your names. + +On the testing network you need a small amount of test ETH to pay network fees. + +## Step 2. Register the name and add your link + +Open the registration page and tap **Connect** to link your wallet. Type the +name you want in **Search for a name** and open it. Choose how many years to +register for, then tap **Next**. Names are currently 6 characters or more, and +some names are reserved. + +![Register your name and choose the registration period](./images/register-name.png) + +On **Create your profile**, paste your SimpleX link into the matching field: + +![Create your profile](./images/create-your-profile.png) + +- **SimpleX contact** for one-to-one chats. Copy your address from the app + (**Create SimpleX address**) and paste it here. People reach it with `@name`. +- **SimpleX channel** for a channel. Copy your **Channel link** and paste it here. + People join it with `#name`. +- **Advanced usage:** fill both to use one name for your chat (`@name`) and your + channel (`#name`). + +Then tap **Next**. + +Finally, tap **Begin** and complete the three steps the site shows: + +> Before we start. Registering your name takes three steps: +> 1. Complete a transaction to begin the timer. +> 2. Wait 60 seconds for the timer to complete. +> 3. Complete a second transaction to secure your name. + +These two transactions protect the name you are registering. The first records +only a secret code for the name, not the name itself, so nobody watching the +blockchain can see which name you want. The wait lets that first transaction +settle, and the second transaction then reveals and claims the name. Without this +two-step process, someone could see your registration in progress and grab the +name before you. + +![The three steps to secure your name](./images/before-we-start.png) + +## Step 3. Check what the app sees + +Copy your `#name.testing` (or `@name.testing`). Paste the name into the search bar, or simply type it. + +The app reports that the name is registered but not yet added to your profile: + +> Unconfirmed name. The SimpleX name is registered, but not added to profile. +> Please add it to your address or channel profile, if you are the owner. + +This is expected, and confirms the name points at your link. The next step +finishes the setup. + +## Step 4. Claim the name in the app + +Set the name on the same profile the record points at. + +- For your **contact address**, open your SimpleX address, tap **Your SimpleX + name**, enter the name, and save. +- For your **channel**, open the channel information, tap **SimpleX name** (below + **Channel link**), enter the name, and save. + +This proves to people who connect to you that `#name.testing` (or `@name.testing`) is your name. + +## Step 5. Connect by name + +On another device, copy `#name.testing` (or `@name.testing`). Paste the name into the search bar, or simply type it. This time the app connects, and the name +shows a check mark next to it. + +You can paste the name in your own device too - the app will warn you that it is your own name. + +Anyone can now reach you by name, and their app confirms it is really you. + +## If something doesn't work + +| Message | Meaning | Fix | +|---|---|---| +| Unconfirmed name | The name points at a link, but the link's profile does not claim the name yet. | Do step 4: set the name on the profile it points at. | +| Name not found | No name is registered. | Check the spelling, or register it (step 2). | +| No valid link | The name has no contact or channel link. | Add a link to the name on the website, on its **Records** tab. | +| Error saving name | You tried to claim a name that has no matching link on the website. | Add your contact address or channel link to the name, then set the name again. | +| None of your servers are set to resolve SimpleX names | No server in the app is set to resolve names. | In server settings, turn on **To resolve names** for a server. | + +## See also + +- [Making connections](./making-connections.md) +- [Chat profiles](./chat-profiles.md) +- [Channel webpage](./channel-webpage.md) diff --git a/images/github-banner.jpg b/images/github-banner.jpg new file mode 100644 index 0000000000..f7a0d730b8 Binary files /dev/null and b/images/github-banner.jpg differ diff --git a/packages/simplex-chat-client/types/typescript/src/commands.ts b/packages/simplex-chat-client/types/typescript/src/commands.ts index d1b89ffe27..31d6597b3f 100644 --- a/packages/simplex-chat-client/types/typescript/src/commands.ts +++ b/packages/simplex-chat-client/types/typescript/src/commands.ts @@ -495,12 +495,12 @@ export namespace APIAddContact { } } -// Determine SimpleX link type and if the bot is already connected via this link. +// Determine SimpleX link type and if the bot is already connected via this link or name. // Network usage: interactive. export interface APIConnectPlan { userId: number // int64 - connectionLink?: string - resolveKnown: boolean + connectTarget?: string + resolveMode: T.PlanResolveMode linkOwnerSig?: T.LinkOwnerSig } @@ -508,7 +508,7 @@ export namespace APIConnectPlan { export type Response = CR.ConnectionPlan | CR.ChatCmdError export function cmdString(self: APIConnectPlan): string { - return '/_connect plan ' + self.userId + ' ' + self.connectionLink + return '/_connect plan ' + self.userId + ' ' + self.connectTarget } } @@ -528,18 +528,18 @@ export namespace APIConnect { } } -// Connect via SimpleX link as string in the active user profile. +// Connect via SimpleX link or name as string in the active user profile. // Network usage: interactive. export interface Connect { incognito: boolean - connLink_?: string + connTarget_?: string } export namespace Connect { export type Response = CR.SentConfirmation | CR.ContactAlreadyExists | CR.SentInvitation | CR.ChatCmdError export function cmdString(self: Connect): string { - return '/connect' + (self.connLink_ ? ' ' + self.connLink_ : '') + return '/connect' + (self.connTarget_ ? ' ' + self.connTarget_ : '') } } diff --git a/packages/simplex-chat-client/types/typescript/src/responses.ts b/packages/simplex-chat-client/types/typescript/src/responses.ts index 0fcf0e6eca..f54acfbeb1 100644 --- a/packages/simplex-chat-client/types/typescript/src/responses.ts +++ b/packages/simplex-chat-client/types/typescript/src/responses.ts @@ -186,6 +186,8 @@ export namespace CR { type: "connectionPlan" user: T.User connLink: T.CreatedConnLink + planSimplexName?: T.SimplexNameInfo + otherSimplexName?: T.SimplexNameInfo connectionPlan: T.ConnectionPlan } diff --git a/packages/simplex-chat-client/types/typescript/src/types.ts b/packages/simplex-chat-client/types/typescript/src/types.ts index 323f174f91..dcd9a5581f 100644 --- a/packages/simplex-chat-client/types/typescript/src/types.ts +++ b/packages/simplex-chat-client/types/typescript/src/types.ts @@ -66,6 +66,7 @@ export type AgentErrorType = | AgentErrorType.NTF | AgentErrorType.XFTP | AgentErrorType.FILE + | AgentErrorType.NO_NAME_SERVERS | AgentErrorType.PROXY | AgentErrorType.RCP | AgentErrorType.BROKER @@ -84,6 +85,7 @@ export namespace AgentErrorType { | "NTF" | "XFTP" | "FILE" + | "NO_NAME_SERVERS" | "PROXY" | "RCP" | "BROKER" @@ -136,6 +138,10 @@ export namespace AgentErrorType { fileErr: FileErrorType } + export interface NO_NAME_SERVERS extends Interface { + type: "NO_NAME_SERVERS" + } + export interface PROXY extends Interface { type: "PROXY" proxyServer: string @@ -1036,6 +1042,8 @@ export type ChatErrorType = | ChatErrorType.ChatNotStopped | ChatErrorType.ChatStoreChanged | ChatErrorType.InvalidConnReq + | ChatErrorType.SimplexDomainNotReady + | ChatErrorType.NotResolvedLocally | ChatErrorType.UnsupportedConnReq | ChatErrorType.ConnReqMessageProhibited | ChatErrorType.ContactNotReady @@ -1113,6 +1121,8 @@ export namespace ChatErrorType { | "chatNotStopped" | "chatStoreChanged" | "invalidConnReq" + | "simplexDomainNotReady" + | "notResolvedLocally" | "unsupportedConnReq" | "connReqMessageProhibited" | "contactNotReady" @@ -1267,6 +1277,16 @@ export namespace ChatErrorType { type: "invalidConnReq" } + export interface SimplexDomainNotReady extends Interface { + type: "simplexDomainNotReady" + simplexDomain: SimplexDomain + simplexDomainError: SimplexDomainError + } + + export interface NotResolvedLocally extends Interface { + type: "notResolvedLocally" + } + export interface UnsupportedConnReq extends Interface { type: "unsupportedConnReq" } @@ -2157,6 +2177,7 @@ export type ErrorType = | ErrorType.LARGE_MSG | ErrorType.EXPIRED | ErrorType.INTERNAL + | ErrorType.NAME | ErrorType.DUPLICATE_ export namespace ErrorType { @@ -2175,6 +2196,7 @@ export namespace ErrorType { | "LARGE_MSG" | "EXPIRED" | "INTERNAL" + | "NAME" | "DUPLICATE_" interface Interface { @@ -2241,6 +2263,11 @@ export namespace ErrorType { type: "INTERNAL" } + export interface NAME extends Interface { + type: "NAME" + nameErr: NameErrorType + } + export interface DUPLICATE_ extends Interface { type: "DUPLICATE_" } @@ -2608,6 +2635,7 @@ export interface GroupInfo { membersRequireAttention: number // int viaGroupLinkUri?: string groupKeys?: GroupKeys + groupDomainVerified?: boolean } export interface GroupKeys { @@ -2984,6 +3012,8 @@ export interface LocalProfile { peerType?: ChatPeerType localBadge?: LocalBadge localAlias: string + contactDomain?: SimplexDomainClaim + contactDomainVerified?: boolean } export enum MemberCriteria { @@ -3177,6 +3207,29 @@ export enum MsgSigStatus { SignedNoKey = "signedNoKey", } +export type NameErrorType = NameErrorType.NO_RESOLVER | NameErrorType.NOT_FOUND | NameErrorType.RESOLVER + +export namespace NameErrorType { + export type Tag = "NO_RESOLVER" | "NOT_FOUND" | "RESOLVER" + + interface Interface { + type: Tag + } + + export interface NO_RESOLVER extends Interface { + type: "NO_RESOLVER" + } + + export interface NOT_FOUND extends Interface { + type: "NOT_FOUND" + } + + export interface RESOLVER extends Interface { + type: "RESOLVER" + resolverErr: string + } +} + export type NetworkError = | NetworkError.ConnectError | NetworkError.TLSError @@ -3295,6 +3348,12 @@ export interface PendingContactConnection { updatedAt: string // ISO-8601 timestamp } +export enum PlanResolveMode { + AllGroups = "allGroups", + Unknown = "unknown", + Never = "never", +} + export interface PrefEnabled { forUser: boolean forContact: boolean @@ -3335,6 +3394,7 @@ export interface Profile { preferences?: Preferences peerType?: ChatPeerType badge?: BadgeProof + contactDomain?: SimplexDomainClaim } export type ProxyClientError = @@ -3395,7 +3455,7 @@ export namespace ProxyError { export interface PublicGroupAccess { groupWebPage?: string - groupDomain?: string + groupDomainClaim?: SimplexDomainClaim domainWebPage: boolean allowEmbedding: boolean } @@ -3898,6 +3958,41 @@ export interface SimplePreference { allow: FeatureAllowed } +export interface SimplexDomain { + nameTLD: SimplexTLD + domain: string + subDomain: string[] +} + +export interface SimplexDomainClaim { + domain: string + proof?: SimplexDomainProof +} + +export type SimplexDomainError = SimplexDomainError.NoValidLink | SimplexDomainError.UnknownDomain + +export namespace SimplexDomainError { + export type Tag = "noValidLink" | "unknownDomain" + + interface Interface { + type: Tag + } + + export interface NoValidLink extends Interface { + type: "noValidLink" + } + + export interface UnknownDomain extends Interface { + type: "unknownDomain" + } +} + +export interface SimplexDomainProof { + linkOwnerId?: string + presHeader: string + signature: string +} + export enum SimplexLinkType { Contact = "contact", Invitation = "invitation", @@ -3906,15 +4001,9 @@ export enum SimplexLinkType { Relay = "relay", } -export interface SimplexNameDomain { - nameTLD: SimplexTLD - domain: string - subDomain: string[] -} - export interface SimplexNameInfo { nameType: SimplexNameType - nameDomain: SimplexNameDomain + nameDomain: SimplexDomain } export enum SimplexNameType { diff --git a/packages/simplex-chat-python/src/simplex_chat/types/_commands.py b/packages/simplex-chat-python/src/simplex_chat/types/_commands.py index 3847f44811..9fb1a6c916 100644 --- a/packages/simplex-chat-python/src/simplex_chat/types/_commands.py +++ b/packages/simplex-chat-python/src/simplex_chat/types/_commands.py @@ -434,17 +434,17 @@ def APIAddContact_cmd_string(self: APIAddContact) -> str: APIAddContact_Response = CR.Invitation | CR.ChatCmdError -# Determine SimpleX link type and if the bot is already connected via this link. +# Determine SimpleX link type and if the bot is already connected via this link or name. # Network usage: interactive. class APIConnectPlan(TypedDict): userId: int # int64 - connectionLink: NotRequired[str] - resolveKnown: bool + connectTarget: NotRequired[str] + resolveMode: "T.PlanResolveMode" linkOwnerSig: NotRequired["T.LinkOwnerSig"] def APIConnectPlan_cmd_string(self: APIConnectPlan) -> str: - return '/_connect plan ' + str(self['userId']) + ' ' + self.get('connectionLink') + return '/_connect plan ' + str(self['userId']) + ' ' + self.get('connectTarget') APIConnectPlan_Response = CR.ConnectionPlan | CR.ChatCmdError @@ -463,15 +463,15 @@ def APIConnect_cmd_string(self: APIConnect) -> str: APIConnect_Response = CR.SentConfirmation | CR.ContactAlreadyExists | CR.SentInvitation | CR.ChatCmdError -# Connect via SimpleX link as string in the active user profile. +# Connect via SimpleX link or name as string in the active user profile. # Network usage: interactive. class Connect(TypedDict): incognito: bool - connLink_: NotRequired[str] + connTarget_: NotRequired[str] def Connect_cmd_string(self: Connect) -> str: - return '/connect' + ((' ' + self.get('connLink_')) if self.get('connLink_') is not None else '') + return '/connect' + ((' ' + self.get('connTarget_')) if self.get('connTarget_') is not None else '') Connect_Response = CR.SentConfirmation | CR.ContactAlreadyExists | CR.SentInvitation | CR.ChatCmdError diff --git a/packages/simplex-chat-python/src/simplex_chat/types/_responses.py b/packages/simplex-chat-python/src/simplex_chat/types/_responses.py index e85de02c78..bd61e6dae1 100644 --- a/packages/simplex-chat-python/src/simplex_chat/types/_responses.py +++ b/packages/simplex-chat-python/src/simplex_chat/types/_responses.py @@ -57,6 +57,8 @@ class ConnectionPlan(TypedDict): type: Literal["connectionPlan"] user: "T.User" connLink: "T.CreatedConnLink" + planSimplexName: NotRequired["T.SimplexNameInfo"] + otherSimplexName: NotRequired["T.SimplexNameInfo"] connectionPlan: "T.ConnectionPlan" class ContactAlreadyExists(TypedDict): diff --git a/packages/simplex-chat-python/src/simplex_chat/types/_types.py b/packages/simplex-chat-python/src/simplex_chat/types/_types.py index 25825d8f98..0856aaf772 100644 --- a/packages/simplex-chat-python/src/simplex_chat/types/_types.py +++ b/packages/simplex-chat-python/src/simplex_chat/types/_types.py @@ -78,6 +78,9 @@ class AgentErrorType_FILE(TypedDict): type: Literal["FILE"] fileErr: "FileErrorType" +class AgentErrorType_NO_NAME_SERVERS(TypedDict): + type: Literal["NO_NAME_SERVERS"] + class AgentErrorType_PROXY(TypedDict): type: Literal["PROXY"] proxyServer: str @@ -123,6 +126,7 @@ AgentErrorType = ( | AgentErrorType_NTF | AgentErrorType_XFTP | AgentErrorType_FILE + | AgentErrorType_NO_NAME_SERVERS | AgentErrorType_PROXY | AgentErrorType_RCP | AgentErrorType_BROKER @@ -133,7 +137,7 @@ AgentErrorType = ( | AgentErrorType_INACTIVE ) -AgentErrorType_Tag = Literal["CMD", "CONN", "NO_USER", "SMP", "NTF", "XFTP", "FILE", "PROXY", "RCP", "BROKER", "AGENT", "NOTICE", "INTERNAL", "CRITICAL", "INACTIVE"] +AgentErrorType_Tag = Literal["CMD", "CONN", "NO_USER", "SMP", "NTF", "XFTP", "FILE", "NO_NAME_SERVERS", "PROXY", "RCP", "BROKER", "AGENT", "NOTICE", "INTERNAL", "CRITICAL", "INACTIVE"] class AutoAccept(TypedDict): acceptIncognito: bool @@ -784,6 +788,14 @@ class ChatErrorType_chatStoreChanged(TypedDict): class ChatErrorType_invalidConnReq(TypedDict): type: Literal["invalidConnReq"] +class ChatErrorType_simplexDomainNotReady(TypedDict): + type: Literal["simplexDomainNotReady"] + simplexDomain: "SimplexDomain" + simplexDomainError: "SimplexDomainError" + +class ChatErrorType_notResolvedLocally(TypedDict): + type: Literal["notResolvedLocally"] + class ChatErrorType_unsupportedConnReq(TypedDict): type: Literal["unsupportedConnReq"] @@ -1014,6 +1026,8 @@ ChatErrorType = ( | ChatErrorType_chatNotStopped | ChatErrorType_chatStoreChanged | ChatErrorType_invalidConnReq + | ChatErrorType_simplexDomainNotReady + | ChatErrorType_notResolvedLocally | ChatErrorType_unsupportedConnReq | ChatErrorType_connReqMessageProhibited | ChatErrorType_contactNotReady @@ -1070,7 +1084,7 @@ ChatErrorType = ( | ChatErrorType_exception ) -ChatErrorType_Tag = Literal["noActiveUser", "noConnectionUser", "noSndFileUser", "noRcvFileUser", "userUnknown", "userExists", "chatRelayExists", "differentActiveUser", "cantDeleteActiveUser", "cantDeleteLastUser", "cantHideLastUser", "hiddenUserAlwaysMuted", "emptyUserPassword", "userAlreadyHidden", "userNotHidden", "invalidDisplayName", "chatNotStarted", "chatNotStopped", "chatStoreChanged", "invalidConnReq", "unsupportedConnReq", "connReqMessageProhibited", "contactNotReady", "contactNotActive", "contactDisabled", "connectionDisabled", "groupUserRole", "groupMemberInitialRole", "contactIncognitoCantInvite", "groupIncognitoCantInvite", "groupContactRole", "groupDuplicateMember", "groupDuplicateMemberId", "groupNotJoined", "groupMemberNotActive", "cantBlockMemberForSelf", "groupMemberUserRemoved", "groupMemberNotFound", "groupCantResendInvitation", "groupInternal", "fileNotFound", "fileSize", "fileAlreadyReceiving", "fileCancelled", "fileCancel", "fileAlreadyExists", "fileWrite", "fileSend", "fileRcvChunk", "fileInternal", "fileImageType", "fileImageSize", "fileNotReceived", "fileNotApproved", "fallbackToSMPProhibited", "inlineFileProhibited", "invalidForward", "invalidChatItemUpdate", "invalidChatItemDelete", "hasCurrentCall", "noCurrentCall", "callContact", "directMessagesProhibited", "agentVersion", "agentNoSubResult", "commandError", "agentCommandError", "invalidFileDescription", "connectionIncognitoChangeProhibited", "connectionUserChangeProhibited", "peerChatVRangeIncompatible", "relayTestError", "internalError", "exception"] +ChatErrorType_Tag = Literal["noActiveUser", "noConnectionUser", "noSndFileUser", "noRcvFileUser", "userUnknown", "userExists", "chatRelayExists", "differentActiveUser", "cantDeleteActiveUser", "cantDeleteLastUser", "cantHideLastUser", "hiddenUserAlwaysMuted", "emptyUserPassword", "userAlreadyHidden", "userNotHidden", "invalidDisplayName", "chatNotStarted", "chatNotStopped", "chatStoreChanged", "invalidConnReq", "simplexDomainNotReady", "notResolvedLocally", "unsupportedConnReq", "connReqMessageProhibited", "contactNotReady", "contactNotActive", "contactDisabled", "connectionDisabled", "groupUserRole", "groupMemberInitialRole", "contactIncognitoCantInvite", "groupIncognitoCantInvite", "groupContactRole", "groupDuplicateMember", "groupDuplicateMemberId", "groupNotJoined", "groupMemberNotActive", "cantBlockMemberForSelf", "groupMemberUserRemoved", "groupMemberNotFound", "groupCantResendInvitation", "groupInternal", "fileNotFound", "fileSize", "fileAlreadyReceiving", "fileCancelled", "fileCancel", "fileAlreadyExists", "fileWrite", "fileSend", "fileRcvChunk", "fileInternal", "fileImageType", "fileImageSize", "fileNotReceived", "fileNotApproved", "fallbackToSMPProhibited", "inlineFileProhibited", "invalidForward", "invalidChatItemUpdate", "invalidChatItemDelete", "hasCurrentCall", "noCurrentCall", "callContact", "directMessagesProhibited", "agentVersion", "agentNoSubResult", "commandError", "agentCommandError", "invalidFileDescription", "connectionIncognitoChangeProhibited", "connectionUserChangeProhibited", "peerChatVRangeIncompatible", "relayTestError", "internalError", "exception"] ChatFeature = Literal["timedMessages", "fullDelete", "reactions", "voice", "files", "calls", "sessions"] @@ -1553,6 +1567,10 @@ class ErrorType_EXPIRED(TypedDict): class ErrorType_INTERNAL(TypedDict): type: Literal["INTERNAL"] +class ErrorType_NAME(TypedDict): + type: Literal["NAME"] + nameErr: "NameErrorType" + class ErrorType_DUPLICATE_(TypedDict): type: Literal["DUPLICATE_"] @@ -1571,10 +1589,11 @@ ErrorType = ( | ErrorType_LARGE_MSG | ErrorType_EXPIRED | ErrorType_INTERNAL + | ErrorType_NAME | ErrorType_DUPLICATE_ ) -ErrorType_Tag = Literal["BLOCK", "SESSION", "CMD", "PROXY", "AUTH", "BLOCKED", "SERVICE", "CRYPTO", "QUOTA", "STORE", "NO_MSG", "LARGE_MSG", "EXPIRED", "INTERNAL", "DUPLICATE_"] +ErrorType_Tag = Literal["BLOCK", "SESSION", "CMD", "PROXY", "AUTH", "BLOCKED", "SERVICE", "CRYPTO", "QUOTA", "STORE", "NO_MSG", "LARGE_MSG", "EXPIRED", "INTERNAL", "NAME", "DUPLICATE_"] FeatureAllowed = Literal["always", "yes", "no"] @@ -1828,6 +1847,7 @@ class GroupInfo(TypedDict): membersRequireAttention: int # int viaGroupLinkUri: NotRequired[str] groupKeys: NotRequired["GroupKeys"] + groupDomainVerified: NotRequired[bool] class GroupKeys(TypedDict): publicGroupId: str @@ -2089,6 +2109,8 @@ class LocalProfile(TypedDict): peerType: NotRequired["ChatPeerType"] localBadge: NotRequired["LocalBadge"] localAlias: str + contactDomain: NotRequired["SimplexDomainClaim"] + contactDomainVerified: NotRequired[bool] MemberCriteria = Literal["all"] @@ -2221,6 +2243,20 @@ MsgReceiptStatus = Literal["ok", "badMsgHash"] MsgSigStatus = Literal["verified", "signedNoKey"] +class NameErrorType_NO_RESOLVER(TypedDict): + type: Literal["NO_RESOLVER"] + +class NameErrorType_NOT_FOUND(TypedDict): + type: Literal["NOT_FOUND"] + +class NameErrorType_RESOLVER(TypedDict): + type: Literal["RESOLVER"] + resolverErr: str + +NameErrorType = NameErrorType_NO_RESOLVER | NameErrorType_NOT_FOUND | NameErrorType_RESOLVER + +NameErrorType_Tag = Literal["NO_RESOLVER", "NOT_FOUND", "RESOLVER"] + class NetworkError_connectError(TypedDict): type: Literal["connectError"] connectError: str @@ -2304,6 +2340,8 @@ class PendingContactConnection(TypedDict): createdAt: str # ISO-8601 timestamp updatedAt: str # ISO-8601 timestamp +PlanResolveMode = Literal["allGroups", "unknown", "never"] + class PrefEnabled(TypedDict): forUser: bool forContact: bool @@ -2340,6 +2378,7 @@ class Profile(TypedDict): preferences: NotRequired["Preferences"] peerType: NotRequired["ChatPeerType"] badge: NotRequired["BadgeProof"] + contactDomain: NotRequired["SimplexDomainClaim"] class ProxyClientError_protocolError(TypedDict): type: Literal["protocolError"] @@ -2381,7 +2420,7 @@ ProxyError_Tag = Literal["PROTOCOL", "BROKER", "BASIC_AUTH", "NO_SESSION"] class PublicGroupAccess(TypedDict): groupWebPage: NotRequired[str] - groupDomain: NotRequired[str] + groupDomainClaim: NotRequired["SimplexDomainClaim"] domainWebPage: bool allowEmbedding: bool @@ -2724,16 +2763,35 @@ class SecurityCode(TypedDict): class SimplePreference(TypedDict): allow: "FeatureAllowed" -SimplexLinkType = Literal["contact", "invitation", "group", "channel", "relay"] - -class SimplexNameDomain(TypedDict): +class SimplexDomain(TypedDict): nameTLD: "SimplexTLD" domain: str subDomain: list[str] +class SimplexDomainClaim(TypedDict): + domain: str + proof: NotRequired["SimplexDomainProof"] + +class SimplexDomainError_noValidLink(TypedDict): + type: Literal["noValidLink"] + +class SimplexDomainError_unknownDomain(TypedDict): + type: Literal["unknownDomain"] + +SimplexDomainError = SimplexDomainError_noValidLink | SimplexDomainError_unknownDomain + +SimplexDomainError_Tag = Literal["noValidLink", "unknownDomain"] + +class SimplexDomainProof(TypedDict): + linkOwnerId: NotRequired[str] + presHeader: str + signature: str + +SimplexLinkType = Literal["contact", "invitation", "group", "channel", "relay"] + class SimplexNameInfo(TypedDict): nameType: "SimplexNameType" - nameDomain: "SimplexNameDomain" + nameDomain: "SimplexDomain" SimplexNameType = Literal["publicGroup", "contact"] diff --git a/plans/2026-06-20-channel-received-no-avatar-left-padding.md b/plans/2026-06-20-channel-received-no-avatar-left-padding.md new file mode 100644 index 0000000000..13ee4ebc4f --- /dev/null +++ b/plans/2026-06-20-channel-received-no-avatar-left-padding.md @@ -0,0 +1,103 @@ +# Remove left padding on consecutive (no-avatar) received messages in channels + +## Problem + +In a channel, received messages show the sender avatar on the first message of a +run and hide it on consecutive messages, but those consecutive messages still +reserve the avatar-sized **left padding** so they line up under the first. For a +channel's feed-style layout this indentation wastes horizontal space — +consecutive received messages should sit flush-left where the avatar would be. +This applies to **both** the channel owner's broadcasts and contributors' posts. + +Desired behaviour: in channels, any received message that does **not** show an +avatar (a consecutive post from the same sender) drops the avatar-sized left +padding. The first message of a run still shows the avatar and keeps its layout; +when the run is broken (a different sender, or a time gap), the next message +shows the avatar again — this run logic is unchanged, only the no-avatar left +padding is reduced. + +## The two received directions in a channel + +Received items in a channel arrive as one of two directions +(`Subscriber.hs`, `saveRcvCI`): + +- **`ChannelRcv`** (no member) — the **owner's** broadcast, sent "as the channel". + The backend permits sending-as-group only to the owner, and a channel owner's + main-scope messages are always sent as group (`ChatInfo.sendAsGroup` is true + for `useRelays && memberRole >= Owner` in the main scope), so received owner + posts arrive as `ChannelRcv`. Shows the channel avatar. +- **`GroupRcv(member)`** (attributed) — a **contributor's** post, carrying the + member. Shows the member avatar. + +Both are received messages, and the change now applies to **both** when they hide +the avatar. (An earlier revision scoped this to `ChannelRcv`/owner only; it now +covers contributors too, per request.) + +## Change + +In channels — gated on `ChatInfo.isChannel` (the `useRelays` flag, which is +reliably present, unlike the optional group-type predicate) — the no-avatar +branches for **both** `ChannelRcv` and `GroupRcv` drop the avatar-sized left +padding down to the base inset where the avatar itself starts. In non-channel +groups the `GroupRcv` no-avatar layout is unchanged (`isChannel` is false). The +avatar-shown layouts, sent messages, and all other chats are unchanged. + +The same Row's `end` padding is already gated on `chatInfo.isChannel` (the merged +right-gap change #7106), so gating `start` on `isChannel` keeps each Row +internally consistent and the change precisely "in channels". + +### Android / desktop (`apps/multiplatform`, `ChatView.kt`, `ChatItemsList`) + +Both the `CIDirection.GroupRcv` and `CIDirection.ChannelRcv` `showAvatar == false` +rows: + +```kotlin +// before +.padding(start = 8.dp + (MEMBER_IMAGE_SIZE * fontSizeSqrtMultiplier) + 4.dp, end = …) +// after +.padding(start = if (chatInfo.isChannel) 8.dp else 8.dp + (MEMBER_IMAGE_SIZE * fontSizeSqrtMultiplier) + 4.dp, end = …) +``` + +### iOS (`apps/ios`, `ChatView.swift`, `chatItemListView`) + +Both the `.groupRcv` and `.channelRcv` no-avatar branches: + +```swift +// before +.padding(.leading, 10 + memberImageSize + 12) +// after +.padding(.leading, chat.chatInfo.isChannel ? 12 : 10 + memberImageSize + 12) +``` + +## Run behaviour (unchanged) + +`shouldShowAvatar(current, older)` shows the avatar on the first message of a +same-sender run and hides it on consecutive ones; a different sender or a gap +resets the run. For `GroupRcv` "same sender" is the same `memberId`; for +`ChannelRcv` consecutive channel broadcasts count as the same sender. Only the +no-avatar left padding is changed. + +## Scope + +- Affects: all received consecutive (no-avatar) messages **in channels** — owner + broadcasts (`ChannelRcv`) and contributor posts (`GroupRcv`). This includes a + channel's member-support sub-scope, which renders through the same + `ChatItemsList` with the channel's `isChannel`; treating it the same way is + consistent with the merged right-gap change (#7106), which also gates that + Row's `end` padding on `isChannel` without a scope filter. +- Unchanged: the first message of each run (avatar shown), sent messages, regular + groups, business chats and direct chats (`isChannel` false — the `else` branch + preserves the original avatar-inset value exactly), and any non-channel + `ChannelRcv` welcome item. + +## Verification + +- Android/desktop: `:common:compileKotlinDesktop` compiles clean. +- iOS: small, type-safe constant change; build/verify on macOS (Xcode) — not + compilable on the Linux build host used here. +- Visual (both platforms), in a channel: + - First message of a run (owner or contributor): avatar shown, layout unchanged. + - Following messages from the same sender (no avatar): now flush-left. + - A different sender / time gap resets the run — the next message shows the + avatar again. + - Regular groups, business and direct chats keep their existing indentation. diff --git a/plans/2026-06-22-roster-catchup-subscribers.md b/plans/2026-06-22-roster-catchup-subscribers.md new file mode 100644 index 0000000000..fd1979cda0 --- /dev/null +++ b/plans/2026-06-22-roster-catchup-subscribers.md @@ -0,0 +1,83 @@ +# Roster catch-up for channel subscribers + +Continues the public-groups roster work (privileged roster, member keys, `VersionRoster` monotonic gate, task-047's `Maybe VersionRoster` on `XGrpMemRole`/`XGrpMemDel`). + +## Problem + +A channel subscriber learns the full roster only on join and on resume (`serveRoster`, Subscriber.hs:1174/1269), then tracks it via forwarded `XGrpMemRole`/`XGrpMemDel` deltas, each carrying an incrementing `VersionRoster`. The gate (`applyAtRosterVersion`, Subscriber.hs:3248) accepts any delta at `v >= cur` and advances to `v`. + +If the subscriber misses intermediate deltas and then receives one at a version more than one above its known version, it advances to `v` and applies that one change — but the roster changes carried by the skipped versions (other members' roles, removals, keys) are lost until the next resume. The subscriber can then reject a freshly-promoted member's signed action (`RGEMsgBadSignature`) for a key it never learned. + +Catch-up: on detecting a gap, the subscriber asks the relay that forwarded the delta to re-serve the full roster, which carries the complete set and keys. + +## Design + +Four pieces. No schema change, no new store function. + +### 1. Owner sends the roster before the delta (the enabler) + +Today the owner sends `XGrpMemRole`/`XGrpMemDel` first, then `broadcastRoster` (Commands.hs:2754/2885). The relay forwards the delta to subscribers *before* its own roster-blob transfer completes, so for the whole transfer its stored `roster_blob` lags its `roster_version`. A catch-up request in that window serves a stale blob the subscriber rejects (`notBelowRoster`) — which is the common case, not an edge. + +Fix: in `APIMembersRole` / `APIRemoveMembers`, reorder to **apply the change to the owner's members → `broadcastRoster v` → send the delta**. This restructures `changeRoleCurrentMems` / `deleteMemsSend` to separate "apply to owner DB" from "send delta to relays" (the roster is still built after the change, so it reflects the new roles / excludes the removed member). + +Effect, relying on FIFO order of the owner→relay connection (a guarantee the roster design already assumes): the relay applies and stores the blob at `v` (`setGroupLiveRoster`) before it processes and forwards the delta at `v`. So a relay's `roster_version` always reflects its stored blob, and any request triggered by a forwarded delta finds a current blob. The now-redundant delta hits the existing no-op suppression (`fromRole == memRole`, Subscriber.hs:3298, added in task-047) and is still forwarded to subscribers — no new relay logic, subscribers still see the delta. + +Behavioral change to core delivery (all relays/subscribers) → its own commit. Implementation must confirm FIFO holds owner→relay (the test will expose a violation). Residual: a failed roster send (rare; already `catchAllErrors`) leaves that relay's gate briefly above its blob until the next change — heals on resume. + +### 2. New event `XGrpRosterRequest VersionRoster` (Protocol.hs) + +A directed subscriber→relay control message carrying the subscriber's pre-gap version, so the relay can skip serving when it holds nothing newer. + +```haskell +XGrpRosterRequest :: VersionRoster -> ChatMsgEvent 'Json +``` + +Wire plumbing (standard single-`VersionRoster` `'Json` event): GADT constructor; `CMEventTag` `XGrpRosterRequest_`; `strEncode` `"x.grp.roster.request"`; `strP` case; `toCMEventTag`; `appJsonToCM` (`XGrpRosterRequest <$> p "version"`); `chatToAppMessage` (`o ["version" .= v]`). NOT in `isForwardedGroupMsg` (point-to-point). NOT in `requiresSignature` (subscribers/observers have no key). + +### 3. Subscriber detects the gap and requests (Subscriber.hs, `applyAtRosterVersion`) + +`applyAtRosterVersion` already reads `cur`, compares `v >= cur`, advances the gate — the one path shared by `xGrpMemRole` and `xGrpMemDel`. In its accepting branch, when the receiver is a subscriber (`not (isUserGrpFwdRelay gInfo)`) and `cur = Just c` with `v > c + 1`, send `XGrpRosterRequest c` to the relay that forwarded the delta, then run the action unchanged (the delta is still applied; the roster heals `c+1 .. v-1`). + +To target the forwarding relay, thread it as `Maybe GroupMember` through `xGrpMemRole` / `xGrpMemDel` / `applyAtRosterVersion`: `Just m` on the forwarded path (`m` in scope in `processForwardedMsg`, Subscriber.hs:3804/3806), `Nothing` on the direct path (1092/1096; the receiver there is a relay and never requests). Send via `sendGroupMessage' user gInfo [relay] (XGrpRosterRequest c)`. + +One forwarding relay only, not all relays: avoids N² requests under concurrent multi-relay gaps, and the owner-signed roster needs no cross-relay verification. The gate advances to `v` on the first gap in a batch, so later `+1` deltas aren't gaps — normally one request per batch. + +### 4. Relay serves on request (Subscriber.hs, `processEvent` + new `xGrpRosterRequest`) + +The request arrives on the direct member connection, dispatched in `processEvent` (alongside other direct group events, ~Subscriber.hs:1103): + +```haskell +XGrpRosterRequest reqVer -> Nothing <$ xGrpRosterRequest gInfo' m'' reqVer +``` + +```haskell +xGrpRosterRequest :: GroupInfo -> GroupMember -> VersionRoster -> CM () +xGrpRosterRequest gInfo m reqVer = + when (isUserGrpFwdRelay gInfo) $ do + cur <- withStore' $ \db -> getGroupRosterVersion db gInfo + when (maybe True (> reqVer) cur) $ serveRoster user gInfo m +``` + +Reuses `serveRoster` unchanged (signed header + inline blob chunks to the one requester — the join/resume path). The version check serves only when the relay holds something newer than the requester, rate-limiting same-version spam. With piece 1, the served blob is current, so the subscriber accepts it (`notBelowRoster`) and `rosterCompletion` heals the skipped set and keys. `serveRoster` is a no-op without a stored roster. + +## Files touched + +- `src/Simplex/Chat/Library/Commands.hs` — reorder owner sends in `APIMembersRole`/`APIRemoveMembers` (restructure `changeRoleCurrentMems`/`deleteMemsSend`). +- `src/Simplex/Chat/Protocol.hs` — new event, end to end. +- `src/Simplex/Chat/Library/Subscriber.hs` — gap detection + request in `applyAtRosterVersion`; thread forwarding relay through `xGrpMemRole`/`xGrpMemDel`; new `xGrpRosterRequest`; one `processEvent` dispatch line. +- No schema change, no new store fn (reuses `getGroupRosterVersion`, `getGroupRelayMembers`, `getGroupRoster`, `serveRoster`). +- `tests/ChatTests/` — one channel catch-up test. + +## Tests + +A `channels` test asserting a subscriber that observes a version gap recovers the skipped set. The hard part is staging a deterministic gap (FIFO forwarding doesn't drop deltas). Candidate: two relays where an intermediate delta reaches only one path, so the subscriber receives a later delta at a jumped version; assert it emits exactly one `XGrpRosterRequest`, the relay re-serves, and a member promoted in the skipped interval is afterwards known (its signed action accepted, no `RGEMsgBadSignature`). Confirm the gap is reliably reproducible before finalizing; fall back to asserting "a forwarded delta at a jumped version triggers one request + re-serve" if the two-relay setup is flaky. Iterate with `-m "channels"`. + +## Commits + +1. Reorder owner sends (roster before delta) — relay blob is current before it forwards deltas. +2. Protocol: add `XGrpRosterRequest`. +3. Relay: `xGrpRosterRequest` + `processEvent` dispatch. +4. Subscriber: gap detection + request to the forwarding relay. +5. Test + schema/plan regen. + +Build and run `-m "channels"` after each. diff --git a/plans/2026-06-23-wide-image-crash.md b/plans/2026-06-23-wide-image-crash.md index effe8695b6..b409befda2 100644 --- a/plans/2026-06-23-wide-image-crash.md +++ b/plans/2026-06-23-wide-image-crash.md @@ -47,52 +47,62 @@ and reaches the unbounded `aspectRatio`. ## Fix -Add the symmetric **upper** bound to the clamp, mirroring the existing lower -bound and the tall-image height cap already enforced in `PriorityLayout` -(`FramedItemView.kt`: `maxImageHeight = constraints.maxWidth * 2.33f`): +An initial fix (already merged) added a symmetric upper bound to the ratio, +`coerceIn(1f / 2.33f, 2.33f)`. That stops the crash but reshapes every image +wider than 2.33:1 — including legitimate panoramas — to 2.33:1. This change +**supersedes** it: stop routing the box height through `aspectRatio` and compute +it **directly**, so the dangerous `width = height × ratio` derivation never +happens. The wide side is then left at its **natural ratio** (no upper clamp); +only the tall side is capped at `2.33`, exactly as before. This mirrors what the +iOS app already does (`height = w × heightRatio`, `heightRatio = min(h / w, 2.33)`): ```kotlin -// after +// before (merged interim fix) Modifier.width(w).aspectRatio((previewBitmap.width.toFloat() / previewBitmap.height.toFloat()).coerceIn(1f / 2.33f, 2.33f)) +// after +Modifier.width(w).height(w * (previewBitmap.height.toFloat() / previewBitmap.width.toFloat()).coerceAtMost(2.33f)) ``` -This is the minimal one-line change. With the cap, the box width is pinned -(`≤ DEFAULT_MAX_IMAGE_WIDTH = 500.dp`) and the height-driven width becomes -`height × 2.33 ≈ 2714 px` — three orders of magnitude inside the 262142 limit — -so the measurement can never overflow at any screen density. `2.33` is the -project's single "most-extreme allowed image proportion" constant: an image is -now clamped to at most 2.33:1 in **either** direction, the same rule already -applied to tall images. +With this form the box width is pinned (`≤ DEFAULT_MAX_IMAGE_WIDTH = 500.dp`) and +the height is `w × min(h / w, 2.33)`, which is always in `(0, w × 2.33]` — at most +`≈ 1165.dp`. Both dimensions are therefore always far inside the 262142 px +`Constraints` limit **at any aspect ratio and any screen density**, so the crash +is structurally impossible rather than merely bounded. A very wide image renders +at its true proportions (a thin strip) instead of being reshaped to 2.33:1. -## Why 2.33 (and not a larger cap) +This does not disturb the framed item's text-width adaptation: that uses +`.width(IntrinsicSize.Max)` (`FramedItemView.kt`), which reads the image box's +intrinsic **width** — still pinned to `w` — so only the wide side's height +derivation changes. -`2.33` is provably safe by construction because it ties the wide bound to the -same proportion the layout already guarantees for height, independent of density. -A larger cap (e.g. 50–200) would preserve the natural shape of genuine panoramas -but relies on an assumption about the maximum measured height and loses the -symmetry with the tall-image rule. The trade-off accepted here is that wide -images between 2.33:1 and the crash threshold now display at 2.33:1 (the very -wide remainder shown as a thin strip with `ContentScale.FillWidth`) rather than -at their natural ratio — a cosmetic change in exchange for a guaranteed-safe, -consistent fix. +## Why compute height directly (vs clamping the ratio) + +The earlier candidate fix clamped the ratio (`coerceIn(1f / 2.33f, 2.33f)`). That +is safe, but it reshapes every image wider than 2.33:1 — including legitimate +panoramas — to 2.33:1, because `ContentScale.FillWidth` cannot fill the +over-tall box and the image letterboxes. Computing the height directly removes +the overflow-prone code path entirely *and* preserves the natural shape of wide +images, so there is no display trade-off to accept. It also makes the Compose and +iOS image-sizing logic parallel. ## Scope / non-goals -- Only the `!smallView` framed Box uses a media-derived `aspectRatio`; it is now - clamped. The chat-list `smallView` preview is locked to a fixed `36.sp` square, - and all other image/video/link paths size with `.width(...)` + `ContentScale` - (no `aspectRatio`), so none of them can hit this overflow. -- Two follow-ups were identified but intentionally left out to keep the diff - minimal: (1) a **symmetric wide guard** in the bitmap decoders - (`outWidth > outHeight * 256`) for defense-in-depth across all consumers, and - (2) extracting the duplicated `2.33` literal (now in `CIImageView.kt` and - `FramedItemView.kt`) into a shared `MAX_IMAGE_ASPECT_RATIO` constant. +- Only the `!smallView` framed Box derived its size from the image ratio; it now + computes height directly. The chat-list `smallView` preview is locked to a fixed + `36.sp` square, and all other image/video/link paths size with `.width(...)` + + `ContentScale` (no `aspectRatio`), so none of them can hit this overflow. +- One follow-up was identified but intentionally left out to keep the diff + minimal: a **symmetric wide guard** in the bitmap decoders + (`outWidth > outHeight * 256`, mirroring the existing tall guard in + `Images.android.kt` / `Images.desktop.kt`) for defense-in-depth, so any future + consumer rendering a decoded bitmap is protected at the source. ## iOS -iOS is **not** affected by the crash. It carries the same lopsided logic — -`heightRatio` (`apps/ios/SimpleXChat/ImageUtils.swift`) caps only the tall side -(`min(size.height / size.width, 2.33)`) — but SwiftUI lays out with `CGFloat` -frames and has no `Constraints` packing limit, so a 4000×1 image yields a valid -(sub-pixel height) frame instead of throwing. No iOS change is required for the -crash; bounding the wide side there would only be a cosmetic parity tweak. +iOS is **not** affected by the crash, and the fix above brings the two platforms +into alignment. iOS already sizes the preview by computing the height directly — +`height = w × heightRatio`, `heightRatio = min(size.height / size.width, 2.33)` +(`apps/ios/SimpleXChat/ImageUtils.swift`) — which is exactly the form now used on +Android/desktop. (Even before, SwiftUI lays out with `CGFloat` frames and has no +`Constraints` packing limit, so a 4000×1 image yielded a valid sub-pixel-height +frame rather than throwing.) No iOS change is required. diff --git a/plans/2026-06-25-name-resolution.md b/plans/2026-06-25-name-resolution.md new file mode 100644 index 0000000000..737de7fe99 --- /dev/null +++ b/plans/2026-06-25-name-resolution.md @@ -0,0 +1,506 @@ +# SimpleX names — simplification plan + +Status: design agreed while reviewing branch `sh/namespace`. This supersedes the +name handling currently on that branch. Line refs are to the working tree at +review time; re-check before editing. + +## 1. Goal + +Reduce the feature to the minimum coherent, secure shape: + +- **One** name per entity, on the **profile** (the entity's claimed identity), + typed `Maybe SimplexNameInfo`. No second "locally-known" copy on the entity row. +- A local **verification status** as a 3-state `Maybe Bool` (not a timestamp): + not-attempted / failed / verified. A failed check never blocks connecting. +- Connect-by-name requires the entity to claim the name, and the result is created as verified. +- The **proof** (address-key signature, context-bound) is **in scope for link + contexts** — connect-by-name, 1-time invitations, contact addresses, channel + join links — so those names are verifiable in this release. Only a name with + **no link context** (a group member, or a name on an `XInfo` profile over an + established connection) is deferred: stored, but not shown until that gap closes. + +Removed from the current branch: the `*.simplex_name` entity columns (the +"locally-known/ct" copy), the `connections.simplex_name` carrier, the four +partial UNIQUE indexes + "newer-claim-wins" clearing, and the `_verified_at` +timestamps. + +## 2. Why (trust model) + +A name resolves to a link via the agent (`resolveSimplexName`); a `NameRecord` +has **lists** of links (`nrSimplexContact`, `nrSimplexChannel`), so +verification matches against **any** of them. "Match any" is safe **only because +the namespace is an on-chain, ENS-style registry**: `nrOwner`/`nrResolver` are +Ethereum addresses (`Names/Record.hs:22-23,36`), so each name has a **single +owner** who sets all its links. An attacker can register *their* name → your +address (the offensive-name case, handled by the claim check below) but **cannot +add a link to your name** — on-chain ownership blocks impersonation. Everything +here depends on that; if names were not single-owner, "match any" would be exploitable. + +The registrant of a name controls what it points to, with no proof that the +target address agreed to it — anyone can publish `@offensive → your address` or +`#offensive → your channel`. Therefore: + +- One-directional verification ("does `resolve(name)` equal a stored link") is + insufficient: it confirms the registrant's assertion, not the address owner's. +- A profile **claiming** a name (and even a link) proves nothing — anyone can + copy a link into a profile. **Control of a link is proven only by an actual + connection/join through it.** +- Sound verification is the intersection: `resolve(name) → link`, **and** the + entity advertises that name in its profile (it claims the name), **and** that link is one + we connected/joined through (control-proven). +- Verifying a name without having connected through its link needs a **signature + by the address key over the name, bound to the presentation context** (§4.8). + This is **in scope** for link contexts: a 1-time invitation includes such a proof + bound to the invite, so resolving the name → address → address key verifies it. + +Consequence: names are verifiable in this release for **channels** (join link), +**contacts connected via their address/name** (the link connected through), and +**1-time-invite contacts** (the in-scope address-key proof). The only case still +deferred is a name with **no link context at all** — a group member, or a name on +an `XInfo` profile over an established connection — which stays stored-but-not-shown. + +## 3. Current branch state (to be changed) + +Migration `M20260603_simplex_name` currently adds, on both SQLite and Postgres: + +- `contacts.simplex_name`, `contacts.simplex_name_verified_at` +- `groups.simplex_name`, `groups.simplex_name_verified_at` +- `connections.simplex_name` +- `contact_profiles.simplex_name`, `group_profiles.simplex_name` +- UNIQUE indexes `idx_contacts_simplex_name`, `idx_groups_simplex_name`, + `idx_contact_profiles_simplex_name`, `idx_group_profiles_simplex_name` +- `server_operators.smp_role_names` (= 1 for `'simplex'`) + +…and threads two names per entity through the types: `Contact.simplexName` / +`GroupInfo.simplexName` (from `*.simplex_name`, "locally known"), and +`LocalProfile.simplexName` (from `*_profiles.simplex_name`, "peer claim"), plus +a `verified_at` timestamp on the entity. `apiVerifySimplexName` verifies the +entity (ct) name against the **profile's self-asserted `contactLink`** for +contacts (wrong link), and against `preparedGroup.connLinkToConnect` for groups +(correct). The `connections.simplex_name` carrier is plumbed through +`createConnection_` but **never written** (all callers pass `Nothing`). + +## 4. Target design + +### 4.1 Name type and JSON encoding + +The name type is **`SimplexNameInfo`** (simplexmq `Simplex/Messaging/SimplexName.hs:37`), +which has: + +- `StrEncoding` (`SimplexName.hs:89`) — canonical `simplex:/name@…` / `#…` string, +- a text `ToField` (`SimplexName.hs:146`) — stores as TEXT, +- a JSON **object** instance: `$(J.deriveJSON defaultJSON ''SimplexNameInfo)` + (`SimplexName.hs:154`) → `{nameType, nameDomain}`. + +**Keep the object JSON** — the UI/API needs the structured form (it reads the name +off `LocalProfile`, `CRSimplexNameVerified`, …). The conflict is only on the +**wire**: `PublicGroupAccess.groupDomain` is a **released** field typed +`Maybe Text` (a JSON string), so the wire form of the name must stay a string. + +Resolve by wrapping **only the wire fields** with simplexmq's generic newtype +`StrJSON` (`Simplex/Messaging/Encoding/String.hs:265`), whose `ToJSON`/`FromJSON` +go through `StrEncoding` → a JSON string (`String.hs:267–272`; idiom +`deriving (ToJSON, FromJSON) via (StrJSON "X" T)`): + +- wire (`Profile`, `GroupProfile`/`PublicGroupAccess`): + `Maybe (StrJSON "SimplexName" SimplexNameInfo)` → JSON **string**, byte-identical + on the wire to the released `Maybe Text`. +- local/UI (`LocalProfile`): `Maybe SimplexNameInfo`, **unwrapped** → JSON **object**. + +Wrap/unwrap at the `Profile` ⇄ `LocalProfile` boundary (`toLocalProfile` / +`fromLocalProfile`). `SimplexNameInfo`'s own JSON instance is untouched, so +`CRSimplexNameVerified` and any other UI-facing use stay object. + +Inherent asymmetry: there is no `LocalGroupProfile`, so the channel name reaches +the UI as a **string** (via `GroupProfile`, which is `StrJSON`), while the contact +name reaches it as an **object** (via `LocalProfile`). If the UI needs the channel +name as an object too, add a decoded field on `GroupInfo` (follow-up). The bot-API +binding generator must render `StrJSON`-wrapped fields as `string`. + +DB stays TEXT: `ToField` (`SimplexName.hs:146`) on write; on read a **hard** +`FromField SimplexNameInfo` (add it — `SimplexName.hs:141-145` says to define it +"when a consumer requires the row-fail behaviour"), so an invalid stored name fails the +row — matching the wire, where a name that won't `strDecode` fails the profile. **No +soft-decode** (`decodeSimplexName` dropped for the name columns). + +### 4.2 Types (field changes) + +- `Profile.contactDomain :: Maybe (StrJSON "SimplexName" SimplexNameInfo)` — NEW; + JSON string (§4.1). The entity's advertised contact name. (Replaces the branch's + `Profile.simplexName`.) +- `Profile.contactDomainProof :: Maybe ClaimProof` — NEW; a flat sibling of + `contactDomain`/`contactLink`, a **wire profile field like `Profile.badge`**. The + **stored** own profile (`contact_profiles`) has the name but **no proof**; the + proof is generated and **added to the outgoing profile at send/save** (§4.8), exactly + as the badge is. `PHSimplexLink` (verifiable) when the profile is saved to a contact + address / 1-time invite; `PHTest` over an established connection (the gap). +- `LocalProfile.contactDomain :: Maybe SimplexNameInfo` (unwrapped → object JSON) + and `LocalProfile.contactDomainVerification :: Maybe Bool` — local status, **not** + on wire `Profile`. `toLocalProfile` unwraps the `StrJSON`; `fromLocalProfile` + re-wraps `contactDomain` and drops the status (mirrors how `localBadge`'s status + is dropped). +- `PublicGroupAccess.groupDomain :: Maybe (StrJSON "SimplexName" SimplexNameInfo)` + — RETYPE from `Maybe Text` (`Types.hs:857`); JSON string, wire-identical to the + released text (§4.1). Owner-set, broadcast in `XGrpInfo`. **Only public, relay-backed + groups** (`groups.use_relays`) can have a name — they have a channel join link to + resolve to and an owner key (`groups.member_priv_key`, `chat_schema.sql:193`) to sign + with; p2p groups have neither. (`contactDomain` on a member is a contact attribute, unaffected.) +- `GroupInfo.groupDomainVerification :: Maybe Bool` — local status, read from the + `groups` table (there is no `LocalGroupProfile`, and `GroupProfile` is the wire + type, so the status cannot be sent with the profile). +- DROP `Contact.simplexName`, `GroupInfo.simplexName`, `Connection.simplexName`, + and both `*VerifiedAt` timestamps. + +Asymmetry, intentional: contact name + status both live on `contact_profiles` +(exposed via `LocalProfile`); the group name lives on `group_profiles` +(exposed via `GroupProfile`/`PublicGroupAccess`) but its status lives on +`groups` (exposed via `GroupInfo`). This is forced — `group_profiles` is the +shared wire profile with no local columns, while `contact_profiles` already +holds local state (`local_alias`). + +### 4.3 Schema — rewrite `M20260603_simplex_name` (branch unreleased) + +Add: +- `contact_profiles`: `contact_domain TEXT`, `contact_domain_verification` + (nullable `INTEGER` SQLite / `SMALLINT` Postgres). +- `groups`: `group_domain_verification` (nullable `INTEGER`/`SMALLINT`). +- `server_operators.smp_role_names` (= 1 for `'simplex'`) — keep. +- `user_contact_links`: the contact-address **root signing key** (BLOB, mirroring + `groups.root_priv_key`) — captured from the 2-step short-link creation — so the + contact-address / 1-time-invite proof can be signed chat-side. (Not present today.) + +No DB change for `group_profiles.group_domain` — it already exists (from +`M20260515_public_group_access`); only the Haskell type and JSON change. + +Remove (vs the current branch migration): `contacts.simplex_name`, +`contacts.simplex_name_verified_at`, `groups.simplex_name`, +`groups.simplex_name_verified_at`, `connections.simplex_name`, +`contact_profiles.simplex_name`, `group_profiles.simplex_name`, and all four +UNIQUE indexes. No name uniqueness is enforced at the DB level — identity comes +from verification, not a constraint. + +Verification column decode: `Maybe BoolInt → Maybe Bool` (`NULL` = not attempted, +`0` = failed, `1` = verified). + +### 4.4 Storage functions (`Store/Shared.hs`, `Store/Direct.hs`, `Store/Groups.hs`) + +- Read the name columns as `Maybe SimplexNameInfo` via the **hard** `FromField` + (§4.1) — an invalid name fails the row; no soft `decodeSimplexName`. +- `toContact` / `toGroupInfo`: read `contact_domain` → `LocalProfile.contactDomain` + and `contact_domain_verification` → `LocalProfile.contactDomainVerification`; + `group_profiles.group_domain` → `PublicGroupAccess.groupDomain` and + `groups.group_domain_verification` → `GroupInfo.groupDomainVerification`. Delete + the ct/cp split and the entity-`simplex_name` reads. +- `createContact_` / `createGroup_` / `createPreparedContact` / `createPreparedGroup`: + set the name on the **profile** columns only; drop the entity-`simplex_name` + argument and the `connections.simplex_name` carrier param on `createConnection_`. +- `updateContactProfile` / `updateGroupProfile`: write `contact_domain` / + `group_domain` from the received profile. Reset the verification to `NULL` + (not-attempted) **only when the name changes**; an XInfo/XGrpInfo with the + **same** name keeps the existing status (a verified name stays verified), exactly as + a badge does. No conflict clearing (no UNIQUE index). +- `getContactBySimplexName` / `getGroupIdBySimplexName`: look up by the **verified** + profile name (the name column joined with verification = `Just True`); on a miss + or unverified, fall through to resolve-and-connect. Consistent with the existing + by-address lookup `getContactViaShortLinkToConnect` (`Direct.hs:963`), which + matches the link with no verification check — a link is the identity, a name is a + claim that only becomes a usable pointer once verified. + +### 4.5 Redaction (`Library/Internal.hs:1246`) + +```haskell +redactedMemberProfile :: GroupInfo -> GroupMember -> Profile -> Profile +redactedMemberProfile g m Profile {…, contactLink, contactDomain} = + let allowDirect = groupFeatureMemberAllowed SGFDirectMessages m g + allowSimplexLinks = groupFeatureMemberAllowed SGFSimplexLinks m g && allowDirect + in Profile { … + , shortDescr = removeSimplexLink =<< shortDescr -- via allowSimplexLinks + , contactLink = if allowSimplexLinks then contactLink else Nothing + , contactDomain = if allowDirect then contactDomain else Nothing + , contactDomainProof = Nothing } -- member profiles are contextless; never include a proof +``` + +- `allowDirect` is the single primitive (the `DirectMessages` permission); it + controls the name and is reused inside `allowSimplexLinks`. No `allowName` flag, + no second lookup. +- **Behavior changes vs current:** `contactLink` flips from unconditionally + dropped to controlled by `allowSimplexLinks` (a member's contact address becomes + visible whenever links+DMs are allowed — the meaning of "links allowed"); the + name follows the looser `allowDirect`. Rationale: a link is one-tap-to-connect + (low friction), a name only resolves if the recipient deliberately looks it up + (higher friction), so a group can forbid links yet allow name discovery, with + "DMs allowed" the floor for both. +- Signature takes `(GroupInfo, GroupMember)` and derives both flags inside, so + the rule lives in one place. Callers pass `(g, m)`; the own-profile path passes + `(g, membership g)` — behavior-preserving because + `groupFeatureUserAllowed f g ≡ groupFeatureMemberAllowed f (membership g) g` + (both reduce to `groupFeatureMemberAllowed' f (memberRole (membership g)) + (fullGroupPreferences g)`, `Types.hs:646–652`). +- Collapses `groupUserAllowSimplexLinks` (`Types.hs:656`) and the pre-computed + `allowSimplexLinks` wiring at the call sites (`Internal.hs:1244`, + `Subscriber.hs:842,2817,3239`, `Commands.hs:3748,4057`). `Commands.hs:3748` + has `Maybe GroupInfo` → "no group ⇒ no redaction" at the call site. + +### 4.6 Resolution + verification (`Library/Commands.hs`) + +Two cases that differ in whether verification can *fail*: + +**Connect-by-name** (`connectPlanName` / `dispatchResolvedRecord`) — verification is +a **precondition** of connecting. After decoding the resolved short link's embedded +profile, **add the claim check**: require that profile's `contactDomain` / +`groupDomain` to equal the resolved name, else fail with `CESimplexNameNotFound` +("name unknown") and **do not connect**. (The current branch decodes the profile but +never compares the name — this is the missing check.) On success the prepared +contact/group is created with the name on the profile, `connLinkToConnect` = the +resolved link, verification = `Just True` (**created as verified**). There is no "failed" +outcome here — failing to resolve or to claim the name just means no connection. + +**Connected NOT by name** (via an address link or a 1-time link) — the peer's profile +may *claim* a name; it starts **unverified** (`Nothing`). Verification is **post-hoc +and non-blocking**: keep `apiVerifySimplexName` (`/_verify simplex name`). + - **Contacts** verify by a **single path** — check `contactDomainProof` (§4.8): + resolve the claimed name → its link, validate the owner chain and **select the key by + the proof's `linkOwnerId`** (that owner's `ownerKey`, or the root key if `Nothing` — + the usual contact-address case), check the `ClaimProof` signature over + `name <> presHeader`, and check the proof's `presHeader` link == + `preparedContact.connLinkToConnect` (**not** `profile.contactLink` — the branch bug). + Contact addresses and 1-time invites both include the proof. + - **Channels** verify by **presence / link-match**: `resolve(#name)` includes + `preparedGroup.connLinkToConnect` (the join link), whose owner-signed data already + has `groupDomain` (no `ClaimProof` — §4.8). + Result is `Just True` (holds) or `Just False` (fails) — and **`Just False` must NOT + prevent the connection**, exactly as a failed *badge* verification doesn't. **This is + why the status must be 3-state** (`Nothing` not attempted / `Just False` failed / + `Just True` verified). Names that stay `Nothing` have **no proof/link context** — + group members, and names on an `XInfo` profile over an established connection. + +Open option: **auto-verify on connect** (run the same non-blocking check +automatically when connecting via address/1-time link), instead of only on demand. +Either way the status stays 3-state — auto-verification can fail without blocking. + +Keep the pure helpers `firstNameLink` (per-type link pick, cross-type rejection) and +`linksMatch` (scheme-normalized compare). + +### 4.7 Display (`View.hs`) + +A name is shown **when there is a proof to verify**, together with its status — +verified, failed, or not-yet-verified. All three states are shown (a failed or +pending check still shows the name, flagged), so the user sees the name and its +trust level rather than a silent omission. Rendering those three states is **out of +scope for this PR** (UI work), but the core stores the data — the 3-state status and +the proof — to drive it. A name with **no proof to verify** — a group member, or a +name on an `XInfo` profile over an established connection — is **not shown**. + +### 4.8 Proof — a flat profile field, signed by the address key, context-bound + +A name resolves to a **contact address** (the persistent identity link). The proof +asserts "the owner of that address asserts this name", so it is **signed by the +address's key** (the resolved address's own key) — **not** by the +per-connection or 1-time-link key. Every proof is **tied to the link it's shown +through**, so a proof made for one link can't be reused on another; these are +distinct proofs. Store the link in a presentation header: +**rename `BadgePresHeader` (`Badges.hs:212`) → `ProofPresHeader`** (now shared by +badge and name proofs) and add a **`PHSimplexLink AConnShortLink`** constructor. +`AConnShortLink` (`Agent.Protocol.hs:1536`, +`forall m. ConnectionModeI m => ACSL (SConnectionMode m) (ConnShortLink m)`) is the +existing existential, so the context is either a 1-time invitation or a contact +address. The signed payload includes this header, and the **verifier compares the +header's link against the link the proof is presented through** (the current +invite/address) — that comparison is what makes a proof non-replayable across +links. The tag enum (`Badges.hs:200`), the `StrEncoding` (`:216`), and +`badgePresHeaderAccepted` (`:226`, → `proofPresHeaderAccepted`) each gain the new +variant. + +**Type & wire** — a JSON object like `BadgeProof` (`Badges.hs:393`): + + data ClaimProof = ClaimProof + { linkOwnerId :: Maybe OwnerId, -- which owner signed; Nothing = root key (see below) + presHeader :: ProofPresHeader, -- context: PHSimplexLink | PHTest + signature :: C.Signature 'C.Ed25519 -- by that owner's key, over: smpEncode name <> smpEncode presHeader + } + +The signature is by the key of the signer's **owner identity** in the link's owner +chain (`OwnerAuth`, `Agent/Protocol.hs:1829`); `ClaimProof` has +**`linkOwnerId :: Maybe OwnerId`** (`OwnerId`, `:1827`) to name it, so the verifier +checks exactly that key (no iterating the owner list): + +- **Channels** (which can have owners other than the address) sign with the user's **owner key**, + `linkOwnerId = Just oid` — **not** the root key — `groups.member_priv_key` + (`chat_schema.sql:193`). +- A **contact address** has a single owner = its creator, so it signs with the **root + key**, `linkOwnerId = Nothing`. + +The root key (`ShortLinkCreds.linkPrivSigKey`/`linkRootSigKey`, `:1482-83`) otherwise +only *authorizes* owners (`validateOwners`/`validateLinkOwners`, `:1846–1859`); +`Nothing` (root) is **allowed at validation**. Both keys live **chat-side** so signing +is in the chat layer — **but only channels store theirs today** (`groups`); a contact +address (`user_contact_links`, `:386`) has **no key column**, so we must add one +(mirroring `groups.root_priv_key`), captured from the 2-step short-link creation, to +sign the contact-address / 1-time-invite proofs. Signed payload = +`smpEncode name <> smpEncode presHeader` (`name` from the profile's `contactDomain`). +`presHeader` serialises as its `StrEncoding` string, `signature` base64url. + +Per presentation context: + +- **Contact address** (the name's own resolved link): presence in the address link's + owner-signed data already proves the name — but we **include the explicit `ClaimProof` + here too** (bound to the address) so contact verification is + one uniform path (always check the proof) rather than presence-for-addresses / + proof-for-invites. The address can also serve as the **badge** proof's context. +- **1-time invitation**: include a proof **signed by the address key, bound to the + 1-time link** as context. Feasible **now** — the 1-time link is a unique, + single-use context; no general mechanism required. This is what makes + a 1-time-invite contact verifiable. +- **`XInfo` over an established connection**: no link context → the step that adds the proof sets + `PHTest` (unbound) → unverifiable → not shown. Left for later, same as the badge's + `PHTest`. (For **group members** the proof is dropped entirely by redaction, §4.5.) + +Home: **inside the profile** — `Profile.contactDomainProof :: Maybe ClaimProof`, a flat +sibling of `contactDomain`/`contactLink`, exactly like `Profile.badge`. It is **not** +stored on the own profile; like the badge, it is **generated fresh and added to the +outgoing profile at send/save** — when the profile is sent to a peer (`XInfo`) or saved +to a link — by signing `name <> presHeader` with the address root key and setting the +**destination as the `presHeader` context**. Because `presentUserBadge` +(`Internal.hs:2037`) already adds the badge proof to the outgoing profile at *both* +peer-sends and link-data writes, the name-proof step belongs in the **same +function**. The context decides whether a proof is useful: saving to a contact address / +1-time invite sets `PHSimplexLink(that link)` (verifiable — the in-scope cases); an +established-connection peer-send sets `PHTest` (unbound — left for later, same as the +badge). The receiver verifies and stores the 3-state status on +`LocalProfile.contactDomainVerification`, as `localBadge` holds the badge status. +Connect-by-name is **created as verified**. + +**Scope:** the **useful** (`PHSimplexLink`) proofs — set when the profile is saved to +a contact address or 1-time invite — are in this change; the verifier resolves the name → +address → address key → checks the signature and the `presHeader` link. Channels use +presence (below). The contextless established-connection case (a `PHTest` name proof) and +group members are left for later. + +Badges stay **in the profile** — person-scoped, presented per connection +(`presentUserBadge`, `Internal.hs:2037`), including over established connections via +`XInfo`. They share the presentation-header context type with name proofs but sign +with the **badge credential key**, not the address key. Two scopes, two homes. + +The shared step sets **both** proof kinds the same way: `PHSimplexLink(link)` +when the destination is a link (contact address, 1-time invite — verifiable), `PHTest` +over an established connection (unbound — the gap). So name proofs and badges both use +`PHTest` only for the contextless established-connection case. + +No group proof field: a channel is always joined via its **join link** (its own +address), whose owner-signed data already has `groupDomain`, and there is no +"advertised link ≠ resolved address" case for channels — so channels verify by +presence/link-match and need no `ClaimProof`. (If full symmetry is wanted later, add +`GroupProfile.groupDomainProof` the same way.) + +### 4.9 Set-name API (in scope — currently missing) + +Names are **pre-registered out of band** — the app does **not** call RNAME. The API +only **verifies** the name and **adds it to the profile**. The user must be able to +add/change/remove their own name from the UI; the branch has no command for the +**contact** name. + +- **Contact name** — add `APISetUserName :: Maybe SimplexNameInfo -> ChatCommand` + (`Nothing` clears). On set: + 1. Require an **address** — fail if none (the UI won't offer the action without one). + 2. Require it to be a **short link** — if only a long link exists, create the short + link (the name resolves to a short link, and the check below is short-link-based). + 3. Ensure that short link is **in the profile** (`contactLink`) — add it if missing. + 4. **Verify**: resolve the name and compare the short link it points to against the + profile's `contactLink`; fail if they don't match (name not preregistered to this + address). + 5. Set `LocalProfile.contactDomain` and **re-publish the contact-address link data**. + The `ClaimProof` is added when the profile is saved to that link (the send/save + proof-adding step, §4.8) — **not** produced by the API itself. (Steps 1–4 are the verify; + this step is set + re-publish.) + Needs a `ChatCommand` constructor + parser + handler. +- **Channel name** (public, relay-backed groups only) — a **separate** + `APISetPublicGroupName`, parallel to the contact one (not folded into + `SetPublicGroupAccess`): same require-address / require-short-link + / link-in-profile / verify / set-`groupDomain` flow against the channel's **join + link**. Rationale: it mirrors the contact API, and the name's fail-able verify + + preconditions don't mix cleanly with the plain `web=`/`embed=`/`domain_page=` writes. + **Drop `domain=` from `SetPublicGroupAccess`** (`Commands.hs:5461`) so there's a single + verified path; factor out the shared `GroupProfile`-update + `XGrpInfo` broadcast so + both commands reuse it. Verify is **TLD-dependent**: resolve+compare for `TLDSimplex`, + a different/no check for `TLDWeb` (web domains don't resolve through the namespace). +- The own name has **no stored verification status** — the verify step checks it at + add time; the 3-state status is only for peers' names. No RNAME wiring (out of scope). + +## 5. Removal checklist (from the current branch) + +- `Contact.simplexName`, `GroupInfo.simplexName`, `Connection.simplexName`. +- `*VerifiedAt` timestamps (→ `Maybe Bool` status fields). +- `connections.simplex_name` column + the `createConnection_` carrier param + the + `XInfo` carrier consumption in `Subscriber.hs`. +- `contacts.simplex_name`, `groups.simplex_name` columns. +- The four partial UNIQUE indexes + `clearConflictingContactProfileSimplexName_` + / `clearConflictingGroupProfileSimplexName_` + their call sites. +- `getContactBySimplexName` / `getGroupIdBySimplexName` against entity columns + (re-point or remove per 6.b). + +## 6. Resolved decisions + +a. **Wire-string encoding (§4.1):** `SimplexNameInfo` keeps object JSON; wire + fields are wrapped in `StrJSON` (string), `LocalProfile` stays unwrapped + (object). Channel name reaches the UI as a **string** (via `GroupProfile`) and + that is fine — no decoded-object field on `GroupInfo` (no reason to re-connect + to a channel you're in; channel names are only shown verified). The object form + matters for **contacts** (connect-from-groups, sharing), which `LocalProfile` + provides. Residual chore: teach the bot-API binding generator to emit `string` + for `StrJSON` fields and pick the `StrJSON` `name` Symbol. +b. **Lookup (§4.4):** re-point `getContactBySimplexName` (its one caller is + connect-by-name, `Commands.hs:4241`) to the **verified** `contact_profiles. + contact_domain`; miss/unverified ⇒ resolve-and-connect. Keeps the no-network + shortcut for already-known contacts. (`getGroupIdBySimplexName` has no external + caller — drop it.) +c. **Proof (§4.8):** a flat **`Profile.contactDomainProof :: Maybe ClaimProof`**, a wire + profile field like `Profile.badge`. Not stored on the own profile; **generated fresh and + added to the outgoing profile at send/save** (peer `XInfo` or save-to-link) by the + **same function** as the badge (`presentUserBadge`, which already runs at + peer-sends *and* link-data writes). Signed by the signer's **owner-identity key** — a + channel's **owner key** (`groups.member_priv_key`, `linkOwnerId = Just oid`) + or a contact address's **root key** (sole owner, `linkOwnerId = Nothing`) — over + `name <> presHeader`; `linkOwnerId` selects the verification key (`Nothing` = root, + allowed at validation). `PHSimplexLink` for address/invite saves, `PHTest` over + established connections (the gap). Verify checks the signature **and `presHeader`'s link + == the link actually used** (`connLinkToConnect`). Channels use presence (owner-signed + link data). **Gap:** the contact-address key isn't stored chat-side today + (`user_contact_links` has no key column) — add one to sign chat-side. Receiver status + on `LocalProfile.contactDomainVerification`. +d. **`redactedMemberProfile` contactLink exposure (§4.5):** intended — a member's + contact address becomes group-visible when links + DMs are allowed. +e. **Verify command + status (§4.6):** keep `apiVerifySimplexName` — required to + verify a claimed name for entities connected **not** by name (address / 1-time + link). Status is **3-state** because a failed name (or badge) verification must + **not** block the connection; connect-by-name is the only created-as-verified path + (and there a failure to resolve or to claim the name means no connection, not a failed state). + **Auto-verify on connect** (vs. on-demand only) is left open; it doesn't change + the 3-state requirement. + +## 7. Rollout & scope + +The **claim check** (§4.6) — a name resolves only if the **resolved link's own +data claims it** — is the anti-stray-names protection and **must ship regardless**: +a name someone registers against a real address must not "work" without that +address owner's agreement. It needs no signature (the address-case presence suffices), +so it lands with the core change. + +The signed proof (§4.8) can ship in the **same** release (add + verify together) or +be **staged** — implemented at the core level with the user-facing name-addition +hidden in the UI until ready. Either way it stays a *core* change. + +The `ProofPresHeader` rename + `PHSimplexLink` + letting badges opt into the link +context ripples through the badge code — accepted, and bounded: + +- `Badges.hs`: `BadgePresHeader` → `ProofPresHeader`, `BadgePresHeaderTag` → + `ProofPresHeaderTag`, `badgePresHeaderAccepted` → `proofPresHeaderAccepted` + (`:200, :212, :216, :226`); add the `PHSimplexLink AConnShortLink` + tag/constructor/`StrEncoding`/accepted-case; `badgeProof` (`:314`) takes the + renamed type. +- `presentUserBadge` (`Internal.hs:2037`) + its ~15 call sites — the **shared point that adds + proofs to the outgoing profile** (already runs at peer-sends *and* link-data writes): generalize it + to set **both** the badge proof and the name `ClaimProof` onto the outgoing profile, + using `PHSimplexLink link` where the destination is a link, `PHTest` otherwise. + +The pure rename can land as a **standalone prep commit** ahead of the proof; the +`PHSimplexLink` wiring + name proof land with the proof work. diff --git a/plans/2026-06-27-namespace-ui-display-set.md b/plans/2026-06-27-namespace-ui-display-set.md new file mode 100644 index 0000000000..1f01cc4311 --- /dev/null +++ b/plans/2026-06-27-namespace-ui-display-set.md @@ -0,0 +1,243 @@ +# SimpleX name UI: display + verify + set (iOS + Android/desktop) + +Branch: `sh/namespace-ui` (rebased onto core `fc0582cf0` — the finalized verify API). This pass adds +displaying a contact's / channel's SimpleX name with verification state, verifying names (manual + auto), +and two screens for setting the user's own name and a channel's name. + +**Upstream sync (2026-06-27):** core `sh/namespace` is at `5008b4e62` ("refactor setting user name" + +test/comment cleanup, on top of the verify-API split `fc0582cf0`). UI branch rebased onto it (backup tag +`backup-namespace-ui-pre-rebase5`); pure-frontend, rebase clean. All dep-touching changes across these +syncs were **wire-neutral**: cosmetic StrJSON label on `Profile.contactDomain`; `APISetUserName` handler +refactor (constructor `{userId, simplexName}`, `/_set_name` parser, `CRUserProfileUpdated`/`NoChange` +response unchanged); `Internal.hs` record-field reordering in bot profiles; store/view/test cleanup. +`Types.hs` model fields/JSON, verify/set commands, responses, `NameVerifyOutcome`, `NameClaimProof`, and +`SimplexNameInfo` are unchanged. **No UI code change required.** + +## Scope + +Ships (both iOS and Android/desktop): +- Models: decode name / proof / verification fields, add `NameClaimProof` + `SimplexNameInfo` helpers. +- Name display + 3-state verification indicator on contact info and channel info. +- Verify API calls + new response handling. +- "Verify SimpleX names" privacy toggle (default ON). +- Two "Set SimpleX name" screens (own name; channel name). + +Out: no change to the core verify algorithm — the UI only triggers it and renders the result. + +## Decisions + +Single source of truth. The UX walkthrough shows the visuals; the implementation sections give file:line. + +### Product / UX (confirmed) +- **A. Title** — rename to "SimpleX address and name". +- **B. Screen body copy** — placeholders for now (final copy TBD): + - Own: *"Set a SimpleX name so people can connect to you using @yourname instead of a link. The name + must already be registered to your address."* + - Channel: *"Set a SimpleX name so people can find this channel as #name. The name must be registered + to this channel's address."* +- **C. Own name read-only** — No; the current own name appears only inside the set screen. +- **D. Rename scope** — rename the shared string everywhere (settings-menu row + screen title). +- **E. Auto-verify trigger** — with the toggle ON, auto-verify on open only if stored state is `null`; + verified/failed shows the stored result, and tapping the indicator re-verifies. +- **F. Failure reason** — shown on tap of the red cross (alert); an inconclusive result shows a brief + alert on completion. Not shown inline. + +### Technical approach +- **T1. Show the name only when a proof exists** (`contactDomainProof` / `groupDomainProof` != nil). +- **T2. One formatter + one parser.** `SimplexNameInfo.shortName` (display, mirrors `shortNameInfoStr`), + `editDomain` (prefix-less, prefills set fields), `SimplexNameInfo(parsing:)` (decode the encoded + `groupDomain` string). Contact display uses the decoded object; channel display parses `groupDomain`. +- **T3. Set screens send a name string; UI fixes only the type prefix.** `strP` reads `@`->contact / + `#`->group first, so the UI prepends `@` (own) / `#` (channel); the backend canonicalises the domain. + Empty input clears. +- **T4. Channel uses a raw `APIUpdateGroupProfile`** (documented at the call site): core has + `APISetUserName` but no `APISetGroupName`, so the channel name is set by re-sending the cloned + `GroupProfile` with `publicGroup.publicGroupAccess.groupDomain` updated. +- **T5. Gating.** Channel "Set SimpleX name" only when `useRelays && isOwner && publicGroup?.publicGroupAccess != nil`; + own "Set SimpleX name" lives in the existing-address branch (inherently requires an address). + +Minor defaults (flag if wrong): iOS toggle in the first "Chats" Section (PrivacySettings.swift:85); +spinner delay ~300ms; channel name cleared via empty input; set-name fields rely on backend rejection +for validation (+ helper text). + +## UX walkthrough + +Same on both platforms. Nothing existing moves. + +### Name + verification indicator (contact info / channel info) + +A new line under the name, above the description, shown per T1. + +``` + Contact info Channel info + +------------------+ +------------------+ + | [ photo ] | | [ photo ] | + | Alice | | My Team | + | @alice.simplex v| <- new | #myteam Verify | <- new + | "description..."| | "description..."| + +------------------+ +------------------+ + (v = check) (Verify = action) +``` + +Name on the left, indicator on the right; the indicator depends on state: + +| State (`*Verification`) | Name style | Indicator | +|---|---|---| +| Verified (`true`) | accent color | check mark in regular color | +| Failed (`false`) | code style | cross mark in red (tap -> failure reason, per F) | +| Not verified (`null`), toggle OFF | code style | "Verify name" action (accent) | +| Not verified (`null`), toggle ON | code style | auto-verify on open (per E) -> spinner -> result | +| Verifying (in-flight) | code style | delayed spinner (~300ms, so a fast result doesn't flash) | + +### Set screens (2 new buttons -> 2 new screens) + +1. **Own name** — on the "SimpleX address and name" screen, a new "Set SimpleX name" button just above + the "Or to share privately" section: + ``` + [ QR code ] + Share address + Business address (toggle) + Address settings + ------------------ + Set SimpleX name -> <- new + ------------------ + Or to share privately + Create 1-time link + ``` +2. **Channel name** — on channel info, in the existing "Advanced options" section (owners only): + ``` + Advanced options + Web access + Set SimpleX name -> <- new + ``` + +Each opens the same view (parameterised by prefix / body text / save action): explanation + a text field +with a fixed prefix adornment (`@` own -> user types `alice.simplex`; `#` channel -> user types `myteam`) ++ Save. Empty + Save clears the name. + +### Settings toggle +"Verify SimpleX names" toggle, default ON, in the privacy settings "Chats" section (iOS: +PrivacySettings.swift:85, no `MorePrivacyView`; Kotlin: `MorePrivacyView` Chats section, PrivacySettings.kt:118). + +## Backend reference (core @ fc0582cf0) + +Single source for wire/JSON facts. + +- Display: `shortNameInfoStr` (simplexmq Protocol.hs:1594) — public group on default `.simplex` TLD with + empty subdomain -> `#myteam`; else prefix (`@`/`#`) + full domain (`@alice.simplex`, `#myteam.testing`). +- Encoded form: `strEncode SimplexNameInfo = "simplex:/name" <> ("@"|"#") <> fullDomain` (Protocol.hs:1565). +- JSON shapes: `LocalProfile.contactDomain :: Maybe SimplexNameInfo` -> JSON **object**; + `PublicGroupAccess.groupDomain :: Maybe (StrJSON SimplexNameInfo)` -> JSON **string** (encoded form). +- Verification: `LocalProfile.contactDomainVerification` / `GroupInfo.groupDomainVerification :: Maybe Bool` + -> JSON `true`/`false`/absent (decodes as Swift `Bool?` / Kotlin `Boolean?`); null=not attempted, + false=failed, true=verified. +- Proof: `LocalProfile.contactDomainProof` / `PublicGroupAccess.groupDomainProof :: Maybe NameClaimProof` + -> JSON object `{linkOwnerId?: string, presHeader: string, signature: string}` (all strings). +- Verify commands (manual; network/resolver errors are retryable `ChatErrorAgent`): + - `APIVerifyContactName {contactId}` -> `/_verify name @`. + - `APIVerifyPublicGroupName {groupId}` -> `/_verify name #`. + - Outcome `NVOVerified | NVOFailed Text | NVOInconclusive Text` -> persists `Just True` / `Just False` / + leaves unchanged. Responses `CRContactNameVerified {user, contact, verificationResult :: Maybe Text}` / + `CRGroupNameVerified {user, groupInfo, verificationResult :: Maybe Text}` return the **updated** entity + plus `Nothing`=verified / `Just reason`=failure-or-inconclusive text. +- Set own name: `APISetUserName userId (Maybe SimplexNameInfo)` -> `/_set_name []` (parsed by + `strP`, NOT json; Commands.hs:5438). Rejects `name is not registered to your address`. Response + `CRUserProfileUpdated` / `CRUserProfileNoChange`. +- Set channel name: `APIUpdateGroupProfile` (`/_group_profile # `, Commands.hs:5571) with + `groupDomain` set. Rejects `name is not registered to this channel`. Response `CRGroupUpdated`. + +## Gotchas + +1. **iOS Codable (compile-blocking).** `SimplexNameInfo`/`SimplexNameDomain`/`SimplexTLD`/`SimplexNameType` + are `Decodable`-only (ChatTypes.swift:5261-5281); adding `contactDomain` to the `Codable` `LocalProfile` + breaks `Encodable` synthesis -> make all four `Codable`. (Kotlin already `@Serializable`.) +2. **`groupDomain` string carries the `simplex:/name` prefix** -> strip it in `parsing`. +3. **`NameClaimProof` decoded for presence only.** UI just checks `!= nil`; if any field's JSON shape is + uncertain at implementation, decode permissively. +4. **Delayed spinner — no existing helper.** iOS: `@State var verifying` set true after `Task.sleep(~300ms)`, + guarded by an `inFlight` flag. Android: a small `LaunchedEffect(inFlight){ delay(300); show=true }` composable. +5. **Enum JSON parity** — backend `enumJSON (dropPrefix "TLD"/"NT")` lowercases -> matches the Swift/Kotlin + enum raw values. +6. **Navigation.** iOS `NavigationLink`; Android `ModalManager.start.showModalCloseable { ... }` + (template: PrivacySettings.kt:162). + +--- + +## iOS implementation + +### Models — `apps/ios/SimpleXChat/ChatTypes.swift` +- Make `SimplexNameInfo`/`SimplexNameDomain`/`SimplexTLD`/`SimplexNameType` (5261-5281) `Codable`. +- Add `NameClaimProof: Codable, Hashable { presHeader: String; signature: String; linkOwnerId: String? }`. +- `SimplexNameInfo` (5261): add `init?(parsing: String)`, `var shortName: String`, `var editDomain: String`. +- `LocalProfile` (153): add `contactDomain: SimplexNameInfo?`, `contactDomainProof: NameClaimProof?`, + `contactDomainVerification: Bool?`. +- `GroupInfo` (2506): add `groupDomainVerification: Bool?`. +- `PublicGroupAccess` (2616): keep `groupDomain: String?`; add `groupDomainProof: NameClaimProof?`. + +### API — `apps/ios/Shared/Model/{AppAPITypes,SimpleXAPI}.swift` +- `ChatCommand`: `apiSetUserName(userId: Int64, name: String?)` -> `"/_set_name \(userId)" + (name.map{" "+$0} ?? "")`; + `apiVerifyContactName(contactId: Int64)` -> `"/_verify name @\(contactId)"`; + `apiVerifyPublicGroupName(groupId: Int64)` -> `"/_verify name #\(groupId)"`. +- `ChatResponse1`: add `contactNameVerified(user:contact:verificationResult:)` / + `groupNameVerified(user:groupInfo:verificationResult:)` cases (+ `responseType`/`details` entries). + Templates: `contactUpdated` AppAPITypes.swift:1114 / responseType:1193 / details:1267; `groupUpdated`:1140. +- Wrappers: `apiSetUserName(_:)`; `apiVerifyContactName(_:)` (updated `Contact` + reason); + `apiVerifyPublicGroupName(_:)` (updated `GroupInfo` + reason). Channel set reuses `apiUpdateGroup(_:_:)`. + +### Views +- Reusable `SimplexNameView` subview rendering the 5-row state table (incl. delayed spinner + verify action). +- Contact: `ChatInfoView.swift` `contactInfoHeader()` — before the `shortDescr` block (~395), per T1 render + `SimplexNameView` from `contactDomain`/`contactDomainProof`/`contactDomainVerification`; onAppear auto-verify (E). +- Channel: `GroupChatInfoView.swift` `groupInfoHeader()` — before webPage (~334), same from parsed + `groupDomain` + `groupDomainProof` + `groupDomainVerification`; "Set SimpleX name" button in Advanced options (~248). +- Address view: `UserAddressView.swift` — "Set SimpleX name" Section above "Or to share privately" (194). +- New `SetSimplexNameView.swift` (own + channel modes). +- Title rename (A/D): the address screen's title is set by the presenter, not `UserAddressView` + (literal also at UserAddressLearnMore.swift:71) — locate the title source and rename everywhere. +- Toggle: `PrivacySettings.swift` main "Chats" Section (~85) `Toggle("Verify SimpleX names", isOn:)` + bound to `@AppStorage(DEFAULT_PRIVACY_VERIFY_SIMPLEX_NAMES)`; declare the constant + default `true` in + the `appDefaults` dict (SettingsView.swift:88-105). + +## Android/desktop implementation (multiplatform Kotlin) + +### Models — `model/ChatModel.kt` +- Add `@Serializable data class NameClaimProof(presHeader: String, signature: String, linkOwnerId: String? = null)`. +- `SimplexNameInfo` (4875): add `companion fun parse(encoded): SimplexNameInfo?`, `val shortName`, `val editDomain`. +- `LocalProfile` (2061): add `contactDomain: SimplexNameInfo? = null`, `contactDomainProof: NameClaimProof? = null`, + `contactDomainVerification: Boolean? = null`. +- `GroupInfo` (2181): add `groupDomainVerification: Boolean? = null`. +- `PublicGroupAccess` (2323): keep `groupDomain: String?`; add `groupDomainProof: NameClaimProof? = null`. + +### API — `model/SimpleXAPI.kt` +- `CC`: `ApiSetUserName(userId, name: String?)`, `ApiVerifyContactName(contactId)` -> `"/_verify name @$contactId"`, + `ApiVerifyPublicGroupName(groupId)` -> `"/_verify name #$groupId"` (+ cmdString entries). +- `CR`: `@SerialName("contactNameVerified") ContactNameVerified(user, contact, verificationResult: String?)`, + `GroupNameVerified(user, groupInfo, verificationResult: String?)` (+ `responseType`). Templates: + `ContactUpdated` SimpleXAPI.kt:6454 / responseType:6646; `GroupUpdated`:6500. +- Wrappers `apiSetUserName`, `apiVerifyContactName`, `apiVerifyPublicGroupName`; channel set reuses `apiUpdateGroupProfile`. +- Pref: `val privacyVerifySimplexNames = mkBoolPreference(SHARED_PREFS_PRIVACY_VERIFY_SIMPLEX_NAMES, true)` (~123). + +### Views +- Reusable `SimplexNameView` composable (the 5-row state table). +- Contact: `views/chat/ChatInfoView.kt` — after `ChatInfoDescription(...)` (~759), per T1; onAppear auto-verify (E). +- Channel: `views/chat/group/GroupChatInfoView.kt` — after `ChatInfoDescription(...)` (~947), per T1; + "Set SimpleX name" button in Advanced options `SectionView` (~805). +- New `views/usersettings/SetSimplexNameView.kt` (own + channel modes). +- `UserAddressView.kt`: "Set SimpleX name" button above the one-time-link section (~347). +- Toggle: `PrivacySettings.kt` `MorePrivacyView` "Chats" Section (~118) `SettingsPreferenceItem(..., appPrefs.privacyVerifySimplexNames)`. +- `strings.xml`: `set_simplex_name`, `verify_simplex_name`, `verify_simplex_names`, screen titles/body; + rename `simplex_address` -> "SimpleX address and name" (D). + +## Build / verify +- iOS: Xcode build of SimpleXChat + app (or swift build of the package targets). +- Android/desktop: `./gradlew` compile of `:common` (desktop target fastest). +- Manual: a peer with a verified name shows accent + check; tampered/failed shows red cross + reason on tap; + toggle OFF shows "Verify name"; toggle ON auto-verifies on open with a delayed spinner. Set own/channel + name; clearing works; core rejection surfaces as an alert. + +## Commit plan (conventional) +1. `feat(names): decode name/proof/verification; add SimplexNameInfo helpers + NameClaimProof` (models, both) +2. `feat(names): verify API (contact/group) + response handling` (CC/CR, wrappers) +3. `feat(names): show name + verification state on contact and channel info` (SimplexNameView + headers) +4. `feat(names): "Verify SimpleX names" privacy toggle + auto-verify on open` +5. `feat(names): set user and channel SimpleX name screens` diff --git a/plans/2026-06-29-fix-desktop-video-vlc-factory-race.md b/plans/2026-06-29-fix-desktop-video-vlc-factory-race.md new file mode 100644 index 0000000000..f75b962a4b --- /dev/null +++ b/plans/2026-06-29-fix-desktop-video-vlc-factory-race.md @@ -0,0 +1,77 @@ +# Fix desktop crash when opening a video (VLC factory init race) + +## Problem (user-facing) + +Opening a video in full screen on desktop can crash the app with: + +``` +java.util.NoSuchElementException + at java.base/java.lang.CompoundEnumeration.nextElement + ... java.util.ServiceLoader ... + at uk.co.caprica.vlcj.factory.discovery.provider.DirectoryProviderDiscoveryStrategy.getSupportedProviders + at uk.co.caprica.vlcj.factory.MediaPlayerFactory. + at chat.simplex.common.platform.RecAndPlay_desktopKt.vlcFactory_delegate$lambda$0(RecAndPlay.desktop.kt:16) +``` + +The crash is intermittent and originates from the lazy initialization of the shared +`MediaPlayerFactory` while a video full-screen view is being composed. + +## Cause + +Each `MediaPlayerFactory()` constructor runs VLC native-library discovery, which iterates a +JDK `ServiceLoader` over `DiscoveryDirectoryProvider`. `ServiceLoader` and the underlying +`CompoundEnumeration` are **not thread-safe**: when two factory constructions run concurrently +on different threads, one enumeration reports `hasNext() == true` and then throws +`NoSuchElementException` from `nextElement()`. + +There are two factories on the desktop: + +- `vlcFactory` — used by the real audio/video players. Its lazy init is triggered on the + AWT/Compose render thread when a video is opened full screen + (`VideoPlayer.initializeMediaPlayerComponent` -> `RecAndPlay.desktop.kt:16`). +- `vlcPreviewFactory` (`--avcodec-hw=none`) — used by preview snapshot helpers, whose lazy init + runs on the dedicated `previewThread` (`VideoPlayer.getOrCreateHelperPlayer`). + +The single-factory invariant established by #6739 ("use shared VLC media-player factory") was +the original protection against concurrent factory construction. #6924 reintroduced a second +factory (`vlcPreviewFactory`) for hardware-acceleration-free previews, reopening the race: the +render thread can construct `vlcFactory` while `previewThread` constructs `vlcPreviewFactory`, +producing two concurrent `ServiceLoader` discoveries and the crash. + +## Fix + +Serialize the two `MediaPlayerFactory()` constructions behind a shared lock so their +native-discovery / `ServiceLoader` runs can never overlap: + +```kotlin +private val vlcFactoryLock = Any() +internal val vlcFactory: MediaPlayerFactory by lazy { synchronized(vlcFactoryLock) { MediaPlayerFactory() } } +internal val vlcPreviewFactory: MediaPlayerFactory by lazy { synchronized(vlcFactoryLock) { MediaPlayerFactory("--avcodec-hw=none") } } +``` + +Both factories are preserved, including the preview factory's `--avcodec-hw=none` option. The +lock guards only the one-time construction of each factory, so there is no steady-state +contention once both are built. + +### Why this approach + +- **Minimal and intent-preserving.** Keeps both factories (preview still needs + `--avcodec-hw=none`) and only adds serialization, restoring the no-concurrent-construction + guarantee that #6739 relied on. +- **Lazy-preserving.** Each factory is still built strictly on demand; the lock only matters in + the rare window where both initialize at the same time. A smaller diff (forcing + `vlcFactory` first inside the preview initializer) was rejected because it would eagerly + construct the main factory whenever a preview is generated and reads as dead code. + +### Known trade-off + +Because `vlcFactory` is initialized on the AWT/render thread, if `previewThread` is mid-construction +of `vlcPreviewFactory` the render thread can briefly block on the lock until native discovery +finishes. This replaces an intermittent crash with a rare, short stall — an acceptable trade. +A more thorough follow-up would either collapse to a single factory (passing `:avcodec-hw=none` +as a per-media option on preview prepare) or eagerly initialize both factories off the render +thread at startup. + +## Scope + +- `apps/multiplatform/common/src/desktopMain/kotlin/chat/simplex/common/platform/RecAndPlay.desktop.kt` diff --git a/scripts/nix/sha256map.nix b/scripts/nix/sha256map.nix index 8dca57a258..15e7bb2b59 100644 --- a/scripts/nix/sha256map.nix +++ b/scripts/nix/sha256map.nix @@ -1,5 +1,5 @@ { - "https://github.com/simplex-chat/simplexmq.git"."98391fd677f547f610a17c48cc96d8c4b2d5e96e" = "1ajgidba08dq8yj7xyr9i47rfrlkzbr75j5nyyjcv0zf778sgv0m"; + "https://github.com/simplex-chat/simplexmq.git"."551de8039fbfcbc75d8e2685a4c631a55ae28fb2" = "1gn0fkxp60cizh2v7vjsd4c2bab2si7fl2bdzikisvg0na8ffnhw"; "https://github.com/simplex-chat/hs-socks.git"."a30cc7a79a08d8108316094f8f2f82a0c5e1ac51" = "0yasvnr7g91k76mjkamvzab2kvlb1g5pspjyjn2fr6v83swjhj38"; "https://github.com/simplex-chat/direct-sqlcipher.git"."f814ee68b16a9447fbb467ccc8f29bdd3546bfd9" = "1ql13f4kfwkbaq7nygkxgw84213i0zm7c1a8hwvramayxl38dq5d"; "https://github.com/simplex-chat/sqlcipher-simple.git"."a46bd361a19376c5211f1058908fc0ae6bf42446" = "1z0r78d8f0812kxbgsm735qf6xx8lvaz27k1a0b4a2m0sshpd5gl"; diff --git a/simplex-chat.cabal b/simplex-chat.cabal index f8c599c80b..14bc3e4075 100644 --- a/simplex-chat.cabal +++ b/simplex-chat.cabal @@ -5,7 +5,7 @@ cabal-version: 1.12 -- see: https://github.com/sol/hpack name: simplex-chat -version: 7.0.0.6 +version: 7.0.0.7 category: Web, System, Services, Cryptography homepage: https://github.com/simplex-chat/simplex-chat#readme author: simplex.chat @@ -40,6 +40,7 @@ library Simplex.Chat.AppSettings Simplex.Chat.Badges Simplex.Chat.Badges.CLI + Simplex.Chat.Names Simplex.Chat.Call Simplex.Chat.Controller Simplex.Chat.Delivery @@ -144,6 +145,8 @@ library Simplex.Chat.Store.Postgres.Migrations.M20260531_member_removed_at Simplex.Chat.Store.Postgres.Migrations.M20260601_relay_sent_web_domain Simplex.Chat.Store.Postgres.Migrations.M20260602_group_roster + Simplex.Chat.Store.Postgres.Migrations.M20260603_simplex_name + Simplex.Chat.Store.Postgres.Migrations.M20260629_roster_catchup else exposed-modules: Simplex.Chat.Archive @@ -306,6 +309,8 @@ library Simplex.Chat.Store.SQLite.Migrations.M20260531_member_removed_at Simplex.Chat.Store.SQLite.Migrations.M20260601_relay_sent_web_domain Simplex.Chat.Store.SQLite.Migrations.M20260602_group_roster + Simplex.Chat.Store.SQLite.Migrations.M20260603_simplex_name + Simplex.Chat.Store.SQLite.Migrations.M20260629_roster_catchup other-modules: Paths_simplex_chat hs-source-dirs: @@ -579,12 +584,14 @@ test-suite simplex-chat-test ChatTests.Forward ChatTests.Groups ChatTests.Local + ChatTests.Names ChatTests.Profiles ChatTests.Utils JSONFixtures JSONTests MarkdownTests MemberRelationsTests + NameResolver MessageBatching OperatorTests ProtocolTests @@ -665,6 +672,8 @@ test-suite simplex-chat-test , unicode-transforms ==0.4.* , unliftio ==0.2.* , uri-bytestring >=0.3.3.1 && <0.4 + , wai ==3.2.* + , warp ==3.3.* default-language: Haskell2010 if flag(client_postgres) other-modules: diff --git a/src/Simplex/Chat/Badges.hs b/src/Simplex/Chat/Badges.hs index e861d27f11..6e35517ed3 100644 --- a/src/Simplex/Chat/Badges.hs +++ b/src/Simplex/Chat/Badges.hs @@ -1,6 +1,7 @@ {-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DerivingStrategies #-} +{-# LANGUAGE DerivingVia #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleInstances #-} @@ -27,8 +28,8 @@ module Simplex.Chat.Badges maxXFTPFileSize, maxFileSizeSupporter, maxFileSizeLegend, - BadgePresHeaderTag (..), - BadgePresHeader (..), + ProofPresHeaderTag (..), + ProofPresHeader (..), BadgePurchase (..), BadgeMasterKey (..), BadgeRequest (..), @@ -197,9 +198,9 @@ maxXFTPFileSize = \case -- presentation, not bound to any context; the 'T' tag marks it so master rejects it. -- PHUnknown is the forward-compat catch-all for tags this version does not interpret. -data BadgePresHeaderTag = PHTestTag | PHUnknownTag Char +data ProofPresHeaderTag = PHTestTag | PHUnknownTag Char -instance StrEncoding BadgePresHeaderTag where +instance StrEncoding ProofPresHeaderTag where strEncode = B.singleton . \case PHTestTag -> 'T' PHUnknownTag c -> c @@ -209,11 +210,13 @@ instance StrEncoding BadgePresHeaderTag where 'T' -> PHTestTag c -> PHUnknownTag c -data BadgePresHeader +data ProofPresHeader = PHTest ByteString | PHUnknown Char ByteString + deriving (Eq, Show) + deriving (ToJSON, FromJSON) via (StrJSON "ProofPresHeader" ProofPresHeader) -instance StrEncoding BadgePresHeader where +instance StrEncoding ProofPresHeader where strEncode = \case PHTest nonce -> strEncode PHTestTag <> nonce PHUnknown c b -> strEncode (PHUnknownTag c) <> b @@ -223,8 +226,8 @@ instance StrEncoding BadgePresHeader where PHUnknownTag c -> PHUnknown c <$> A.takeByteString -- v6.5.x accepts both; v7 will reject PHTest/PHUnknown -badgePresHeaderAccepted :: BadgePresHeader -> Bool -badgePresHeaderAccepted = \case +proofPresHeaderAccepted :: ProofPresHeader -> Bool +proofPresHeaderAccepted = \case PHTest _ -> True PHUnknown _ _ -> True @@ -311,7 +314,7 @@ generateBadgeProof pk (BadgeCredential keyIdx masterKey signature badgeInfo) ph fmap (\p -> BadgeProof keyIdx ph p badgeInfo) <$> bbsProofGen pk signature bbsBadgeHeader ph bbsBadgeDisclosedIndexes (badgeMessages masterKey badgeInfo) -- application-level proof generation with a semantic presentation header -badgeProof :: BBSPublicKey -> BadgeCredential -> BadgePresHeader -> IO (Either String BadgeProof) +badgeProof :: BBSPublicKey -> BadgeCredential -> ProofPresHeader -> IO (Either String BadgeProof) badgeProof pk cred ph = generateBadgeProof pk cred (BBSPresHeader $ strEncode ph) -- Recipient-side: verify a badge proof with the configured key its index points to. @@ -324,7 +327,7 @@ verifyBadge keys b@(BadgeProof keyIdx _ _ _) = case M.lookup keyIdx keys of verifyBadgeWith :: BBSPublicKey -> BadgeProof -> IO Bool verifyBadgeWith pk (BadgeProof _ ph@(BBSPresHeader phBytes) proof badgeInfo) - | either (const False) badgePresHeaderAccepted (strDecode phBytes) = + | either (const False) proofPresHeaderAccepted (strDecode phBytes) = bbsProofVerify pk proof bbsBadgeHeader ph bbsBadgeDisclosedIndexes bbsBadgeMessageCount (badgeInfoMessages badgeInfo) | otherwise = pure False diff --git a/src/Simplex/Chat/Controller.hs b/src/Simplex/Chat/Controller.hs index 48913af9a5..48f4ec9eec 100644 --- a/src/Simplex/Chat/Controller.hs +++ b/src/Simplex/Chat/Controller.hs @@ -417,6 +417,7 @@ data ChatCommand | APIGetCallInvitations | APICallStatus ContactId WebRTCCallStatus | APIUpdateProfile {userId :: UserId, profile :: Profile} + | APISetUserDomain {userId :: UserId, simplexDomain :: Maybe SimplexDomain} | APISetContactPrefs {contactId :: ContactId, preferences :: Preferences} | APISetContactAlias {contactId :: ContactId, localAlias :: LocalAlias} | APISetGroupAlias {groupId :: GroupId, localAlias :: LocalAlias} @@ -442,6 +443,7 @@ data ChatCommand | APILeaveGroup {groupId :: GroupId} | APIListMembers {groupId :: GroupId} | APIUpdateGroupProfile {groupId :: GroupId, groupProfile :: GroupProfile} + | APISetPublicGroupAccess GroupId PublicGroupAccess | APICreateGroupLink {groupId :: GroupId, memberRole :: GroupMemberRole} | APIGroupLinkMemberRole {groupId :: GroupId, memberRole :: GroupMemberRole} | APIDeleteGroupLink {groupId :: GroupId} @@ -527,15 +529,17 @@ data ChatCommand | AddContact IncognitoEnabled | APISetConnectionIncognito Int64 IncognitoEnabled | APIChangeConnectionUser Int64 UserId -- new user id to switch connection to - | APIConnectPlan {userId :: UserId, connectionLink :: Maybe AConnectionLink, resolveKnown :: Bool, linkOwnerSig :: Maybe LinkOwnerSig} -- Maybe AConnectionLink is used to report link parsing failure as special error - | APIPrepareContact UserId ACreatedConnLink ContactShortLinkData - | APIPrepareGroup UserId CreatedLinkContact DirectLink GroupShortLinkData + | APIConnectPlan {userId :: UserId, connectTarget :: Maybe AConnectTarget, resolveMode :: PlanResolveMode, linkOwnerSig :: Maybe LinkOwnerSig} -- Maybe AConnectTarget is used to report parsing failure as special error + | APIPrepareContact UserId ACreatedConnLink (Maybe SimplexDomain) ContactShortLinkData + | APIPrepareGroup UserId CreatedLinkContact DirectLink (Maybe SimplexDomain) GroupShortLinkData | APIChangePreparedContactUser ContactId UserId | APIChangePreparedGroupUser GroupId UserId | APIConnectPreparedContact {contactId :: ContactId, incognito :: IncognitoEnabled, msgContent_ :: Maybe MsgContent} | APIConnectPreparedGroup {groupId :: GroupId, incognito :: IncognitoEnabled, ownerContact :: Maybe GroupOwnerContact, msgContent_ :: Maybe MsgContent} | APIConnect {userId :: UserId, incognito :: IncognitoEnabled, preparedLink_ :: Maybe ACreatedConnLink} -- Maybe is used to report link parsing failure as special error - | Connect {incognito :: IncognitoEnabled, connLink_ :: Maybe AConnectionLink} + | Connect {incognito :: IncognitoEnabled, connTarget_ :: Maybe AConnectTarget} + | APIVerifyContactDomain {contactId :: ContactId} + | APIVerifyGroupDomain {groupId :: GroupId} | APIConnectContactViaAddress UserId IncognitoEnabled ContactId | ConnectSimplex IncognitoEnabled -- UserId (not used in UI) | DeleteContact ContactName ChatDeleteMode @@ -666,6 +670,22 @@ data ChatCommand CustomChatCommand ByteString deriving (Show) +data PlanResolveMode + = PRMAllGroups -- resolve all known groups and all unknown chats + | PRMUnknown -- only resolve if chat is unknown (default) + | PRMNever -- do not resolve links and names, only do local search + deriving (Eq, Show) + +planResolveModeP :: A.Parser PlanResolveMode +planResolveModeP = + A.takeTill (== ' ') >>= \case + "allGroups" -> pure PRMAllGroups + "on" -> pure PRMAllGroups + "unknown" -> pure PRMUnknown + "off" -> pure PRMUnknown + "never" -> pure PRMNever + _ -> fail "bad PlanResolveMode" + allowRemoteCommand :: ChatCommand -> Bool -- XXX: consider using Relay/Block/ForceLocal allowRemoteCommand = \case StartChat {} -> False @@ -774,6 +794,8 @@ data ChatResponse | CRContactCode {user :: User, contact :: Contact, connectionCode :: Text} | CRGroupMemberCode {user :: User, groupInfo :: GroupInfo, member :: GroupMember, connectionCode :: Text} | CRConnectionVerified {user :: User, verified :: Bool, expectedCode :: Text} + | CRContactDomainVerified {user :: User, contact :: Contact, verificationFailure :: Maybe Text} + | CRGroupDomainVerified {user :: User, groupInfo :: GroupInfo, verificationFailure :: Maybe Text} | CRTagsUpdated {user :: User, userTags :: [ChatTag], chatTags :: [ChatTagId]} | CRNewChatItems {user :: User, chatItems :: [AChatItem]} | CRChatItemUpdated {user :: User, chatItem :: AChatItem} @@ -814,7 +836,7 @@ data ChatResponse | CRInvitation {user :: User, connLinkInvitation :: CreatedLinkInvitation, connection :: PendingContactConnection} | CRConnectionIncognitoUpdated {user :: User, toConnection :: PendingContactConnection, customUserProfile :: Maybe Profile} | CRConnectionUserChanged {user :: User, fromConnection :: PendingContactConnection, toConnection :: PendingContactConnection, newUser :: User} - | CRConnectionPlan {user :: User, connLink :: ACreatedConnLink, connectionPlan :: ConnectionPlan} + | CRConnectionPlan {user :: User, connLink :: ACreatedConnLink, planSimplexName :: Maybe SimplexNameInfo, otherSimplexName :: Maybe SimplexNameInfo, connectionPlan :: ConnectionPlan} | CRNewPreparedChat {user :: User, chat :: AChat} | CRContactUserChanged {user :: User, fromContact :: Contact, newUser :: User, toContact :: Contact} | CRGroupUserChanged {user :: User, fromGroup :: GroupInfo, newUser :: User, toGroup :: GroupInfo} @@ -1103,7 +1125,7 @@ data GroupLinkPlan | GLPOwnLink {groupInfo :: GroupInfo} | GLPConnectingConfirmReconnect | GLPConnectingProhibit {groupInfo_ :: Maybe GroupInfo} - | GLPKnown {groupInfo :: GroupInfo, groupUpdated :: BoolDef, ownerVerification :: Maybe OwnerVerification, linkOwners :: ListDef GroupLinkOwner} + | GLPKnown {groupInfo :: GroupInfo, groupUpdated :: Bool, ownerVerification :: Maybe OwnerVerification, linkOwners :: ListDef GroupLinkOwner} | GLPNoRelays {groupSLinkData_ :: Maybe GroupShortLinkData} | GLPUpdateRequired {groupSLinkData_ :: Maybe GroupShortLinkData} deriving (Show) @@ -1399,6 +1421,12 @@ data ChatError | ChatErrorRemoteHost {rhKey :: RHKey, remoteHostError :: RemoteHostError} deriving (Show, Exception) +-- why a resolved SimpleX name could not be used (the name itself resolved; an unregistered name is the agent's NAME NOT_FOUND) +data SimplexDomainError + = SDENoValidLink -- the name's record has no usable contact/channel link + | SDEUnknownDomain -- the resolved link's profile has no name, or a different name + deriving (Eq, Show) + data ChatErrorType = CENoActiveUser | CENoConnectionUser {agentConnId :: AgentConnId} @@ -1420,6 +1448,8 @@ data ChatErrorType | CEChatNotStopped | CEChatStoreChanged | CEInvalidConnReq + | CESimplexDomainNotReady {simplexDomain :: SimplexDomain, simplexDomainError :: SimplexDomainError} + | CENotResolvedLocally -- a name or link is not a known chat in the local store and online resolution is off (PRMNever) | CEUnsupportedConnReq | CEInvalidChatMessage {connection :: Connection, msgMeta :: Maybe MsgMetaJSON, messageData :: Text, message :: String} | CEConnReqMessageProhibited @@ -1751,6 +1781,8 @@ $(JQ.deriveJSON (sumTypeJSON $ dropPrefix "GLP") ''GroupLinkPlan) $(JQ.deriveJSON (sumTypeJSON $ dropPrefix "FC") ''ForwardConfirmation) +$(JQ.deriveJSON (sumTypeJSON $ dropPrefix "SDE") ''SimplexDomainError) + $(JQ.deriveJSON (sumTypeJSON $ dropPrefix "CE") ''ChatErrorType) $(JQ.deriveJSON (sumTypeJSON $ dropPrefix "RHE") ''RemoteHostError) diff --git a/src/Simplex/Chat/Core.hs b/src/Simplex/Chat/Core.hs index ac05550939..cc3e49beb6 100644 --- a/src/Simplex/Chat/Core.hs +++ b/src/Simplex/Chat/Core.hs @@ -140,7 +140,7 @@ createActiveUser cc CoreChatOpts {chatRelay} = \case displayName <- T.pack <$> withPrompt "display name" getLine createUser loop False $ mkProfile displayName where - mkProfile displayName = Profile {displayName, fullName = "", shortDescr = Nothing, image = Nothing, contactLink = Nothing, peerType = Nothing, preferences = Nothing, badge = Nothing} + mkProfile displayName = Profile {displayName, fullName = "", shortDescr = Nothing, image = Nothing, contactLink = Nothing, peerType = Nothing, preferences = Nothing, badge = Nothing, contactDomain = Nothing} createUser onError clientService p = execChatCommand' (CreateActiveUser NewUser {profile = Just p, pastTimestamp = False, userChatRelay = BoolDef chatRelay, clientService = BoolDef clientService}) 0 `runReaderT` cc >>= \case Right (CRActiveUser user) -> pure user diff --git a/src/Simplex/Chat/Library/Commands.hs b/src/Simplex/Chat/Library/Commands.hs index eada7e5a1b..837317176f 100644 --- a/src/Simplex/Chat/Library/Commands.hs +++ b/src/Simplex/Chat/Library/Commands.hs @@ -13,6 +13,7 @@ {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} +{-# LANGUAGE TypeApplications #-} {-# OPTIONS_GHC -fno-warn-ambiguous-fields #-} module Simplex.Chat.Library.Commands where @@ -56,6 +57,7 @@ import qualified Data.UUID as UUID import qualified Data.UUID.V4 as V4 import Simplex.Chat.Library.Subscriber import Simplex.Chat.Badges (BadgeCredential (..), LocalBadge (..), maxXFTPFileSize, mkBadgeStatus, verifyCredential) +import Simplex.Chat.Names (SimplexDomainProof (..), SimplexDomainClaim (..), claimDomain, mkDomainClaim) import Simplex.Chat.Call import Simplex.Chat.Controller import Simplex.Chat.Delivery (DeliveryJobScope (..), DeliveryJobSpec (..), DeliveryWorkerScope (..)) @@ -91,7 +93,7 @@ import Simplex.Chat.Types.Shared import Simplex.Chat.Util (liftIOEither, zipWith3') import qualified Simplex.Chat.Util as U import Simplex.Chat.Web (webPreviewWorker) -import Simplex.FileTransfer.Description (FileDescriptionURI (..), maxFileSize, maxFileSizeHard) +import Simplex.FileTransfer.Description (FileDescriptionURI (..), maxFileSizeHard) import Simplex.Messaging.Agent import Simplex.Messaging.Agent.Env.SQLite (ServerCfg (..), ServerRoles (..), allRoles) import Simplex.Messaging.Agent.Protocol @@ -105,11 +107,11 @@ import qualified Simplex.Messaging.Crypto as C import qualified Simplex.Messaging.Crypto.ShortLink as SL import Simplex.Messaging.Crypto.File (CryptoFile (..), CryptoFileArgs (..)) import qualified Simplex.Messaging.Crypto.File as CF -import Simplex.Messaging.Crypto.Ratchet (PQEncryption (..), PQSupport (..), pattern IKPQOff, pattern IKPQOn, pattern PQEncOff, pattern PQSupportOff, pattern PQSupportOn) +import Simplex.Messaging.Crypto.Ratchet (PQEncryption (..), PQSupport (..), pattern IKPQOff, pattern IKPQOn, pattern PQSupportOff, pattern PQSupportOn) import Simplex.Messaging.Encoding import Simplex.Messaging.Encoding.String import Simplex.Messaging.Parsers (base64P) -import Simplex.Messaging.Protocol (AProtoServerWithAuth (..), AProtocolType (..), MsgFlags (..), NtfServer, ProtoServerWithAuth (..), ProtocolServer, ProtocolType (..), ProtocolTypeI (..), SProtocolType (..), SubscriptionMode (..), UserProtocol, userProtocol) +import Simplex.Messaging.Protocol (AProtoServerWithAuth (..), AProtocolType (..), MsgFlags (..), NameRecord (..), NtfServer, ProtoServerWithAuth (..), ProtocolServer, ProtocolType (..), ProtocolTypeI (..), SProtocolType (..), SubscriptionMode (..), UserProtocol, userProtocol) import Simplex.Messaging.ServiceScheme (ServiceScheme (..)) import qualified Simplex.Messaging.TMap as TM import Simplex.Messaging.Transport.Client (defaultSocksProxyWithAuth) @@ -129,7 +131,7 @@ import qualified UnliftIO.Exception as E import UnliftIO.IO (hClose) import UnliftIO.STM #if defined(dbPostgres) -import Data.Bifunctor (bimap, second) +import Data.Bifunctor (bimap, first, second) import Simplex.Messaging.Agent.Client (SubInfo (..), getAgentQueuesInfo, getAgentWorkersDetails, getAgentWorkersSummary, temporaryOrHostError) #else import Data.Bifunctor (bimap, first, second) @@ -381,14 +383,14 @@ processChatCommand cxt nm = \case user <- withFastStore $ \db -> do user <- createUserRecordAt db (AgentUserId auId) (isTrue userChatRelay) service p True ts mapM_ (setUserServers db user ts) uss - createPresetContactCards db cxt user `catchAllErrors` \_ -> pure () + createPresetContactCards db user `catchAllErrors` \_ -> pure () createNoteFolder db user pure user atomically . writeTVar u $ Just user pure $ CRActiveUser user where - createPresetContactCards :: DB.Connection -> StoreCxt -> User -> ExceptT StoreError IO () - createPresetContactCards db cxt user = do + createPresetContactCards :: DB.Connection -> User -> ExceptT StoreError IO () + createPresetContactCards db user = do createContact db cxt user simplexStatusContactProfile createContact db cxt user simplexTeamContactProfile chooseServers :: Maybe User -> CM ([UpdatedUserOperatorServers], (NonEmpty (ServerCfg 'PSMP), NonEmpty (ServerCfg 'PXFTP))) @@ -1491,6 +1493,24 @@ processChatCommand cxt nm = \case withCurrentCall contactId $ \user ct call -> updateCallItemStatus user ct call receivedStatus Nothing $> Just call APIUpdateProfile userId profile -> withUserId userId (`updateProfile` profile) + APISetUserDomain userId domain_ -> withUserId userId $ \user@User {profile = p@LocalProfile {contactLink, contactDomain}} -> + if (claimDomain <$> contactDomain) == domain_ + then pure $ CRUserProfileNoChange user + else do + cl' <- case domain_ of + Nothing -> pure contactLink + Just domain -> do + UserContactLink {shortLinkDataSet, connLinkContact = CCLink _ sl_} <- withFastStore (`getUserAddress` user) + case sl_ of + Just sl | shortLinkDataSet -> do + NameRecord {nrSimplexContact} <- withAgent $ \a -> resolveSimplexName a nm (aUserId user) domain + unless (nameResolvesTo sl nrSimplexContact) $ throwChatError $ CESimplexDomainNotReady domain SDENoValidLink + pure $ Just (CLShort sl) + _ -> throwCmdError "create the address short link and add it to name" + let p' = (fromLocalProfile p :: Profile) {contactDomain = mkDomainClaim <$> domain_, contactLink = cl'} + updateProfile_ user p' True $ withFastStore $ \db -> do + user' <- updateUserProfile db user p' + liftIO $ setUserSimplexDomain db user' domain_ APISetContactPrefs contactId prefs' -> withUser $ \user -> do ct <- withFastStore $ \db -> getContact db cxt user contactId updateContactPrefs user ct prefs' @@ -1829,7 +1849,7 @@ processChatCommand cxt nm = \case APIGroupInfo gId -> withUser $ \user -> CRGroupInfo user <$> withFastStore (\db -> getGroupInfo db cxt user gId) APIGetUpdatedGroupLinkData groupId -> withUser $ \user -> do - gInfo@GroupInfo {groupProfile = p, groupSummary = GroupSummary {publicMemberCount = localCount}} <- withFastStore $ \db -> getGroupInfo db cxt user groupId + gInfo@GroupInfo {groupProfile = p} <- withFastStore $ \db -> getGroupInfo db cxt user groupId case p of GroupProfile {publicGroup = Just PublicGroupProfile {groupLink = sLnk}} | useRelays' gInfo -> do (_, cData@(ContactLinkData _ UserContactData {relays = currentRelayLinks})) <- getShortLinkConnReq' nm user sLnk @@ -1983,8 +2003,9 @@ processChatCommand cxt nm = \case -- [incognito] generate profile for connection incognitoProfile <- if incognito then Just <$> liftIO generateRandomProfile else pure Nothing subMode <- chatReadVar subscriptionMode + -- TODO [badges] bind link and badge to handshake context linkProfile <- presentUserBadge user incognitoProfile $ userProfileDirect user incognitoProfile Nothing True - let userData = contactShortLinkData linkProfile Nothing + let userData = contactShortLinkData linkProfile {contactDomain = Nothing} Nothing userLinkData = UserInvLinkData userData (connId, ccLink) <- withAgent $ \a -> createConnection a nm (aUserId user) True False SCMInvitation (Just userLinkData) Nothing IKPQOn subMode ccLink' <- shortenCreatedLink ccLink @@ -2037,10 +2058,11 @@ processChatCommand cxt nm = \case createDirectConnection db newUser agConnId ccLink' Nothing ConnNew Nothing subMode initialChatVersion PQSupportOn deleteAgentConnectionAsync (aConnId' conn) pure conn' - APIConnectPlan userId (Just cLink) resolveKnown linkOwnerSig_ -> withUserId userId $ \user -> - uncurry (CRConnectionPlan user) <$> connectPlan user cLink resolveKnown linkOwnerSig_ + APIConnectPlan userId (Just ct) resolveMode linkOwnerSig_ -> withUserId userId $ \user -> do + (ccLink, planSimplexName, otherSimplexName, plan) <- connectPlan user ct resolveMode linkOwnerSig_ Nothing + pure $ CRConnectionPlan user ccLink planSimplexName otherSimplexName plan APIConnectPlan _ Nothing _ _ -> throwChatError CEInvalidConnReq - APIPrepareContact userId accLink contactSLinkData -> withUserId userId $ \user -> do + APIPrepareContact userId accLink verifiedDomain contactSLinkData -> withUserId userId $ \user -> do let ContactShortLinkData {profile, message, business} = contactSLinkData welcomeSharedMsgId <- forM message $ \_ -> getSharedMsgId case accLink of @@ -2050,7 +2072,7 @@ processChatCommand cxt nm = \case groupPreferences = maybe defaultBusinessGroupPrefs businessGroupPrefs preferences groupProfile = businessGroupProfile profile groupPreferences gVar <- asks random - (gInfo, hostMember_) <- withStore $ \db -> createPreparedGroup db gVar cxt user groupProfile True ccLink welcomeSharedMsgId False GRMember Nothing + (gInfo, hostMember_) <- withStore $ \db -> createPreparedGroup db gVar cxt user groupProfile True ccLink welcomeSharedMsgId False GRMember Nothing Nothing hostMember <- maybe (throwCmdError "no host member") pure hostMember_ void $ createChatItem user (CDGroupSnd gInfo Nothing) False CIChatBanner Nothing Nothing (Just epochStart) let cd = CDGroupRcv gInfo Nothing hostMember @@ -2063,7 +2085,7 @@ processChatCommand cxt nm = \case _ -> Chat cInfo [] emptyChatStats pure $ CRNewPreparedChat user $ AChat SCTGroup chat ACCL _ (CCLink cReq _) -> do - ct <- withStore $ \db -> createPreparedContact db cxt user profile accLink welcomeSharedMsgId + ct <- withStore $ \db -> createPreparedContact db cxt user profile accLink welcomeSharedMsgId (True <$ verifiedDomain) void $ createChatItem user (CDDirectSnd ct) False CIChatBanner Nothing Nothing (Just epochStart) let cd = CDDirectRcv ct createItem sharedMsgId content = createChatItem user cd False content sharedMsgId Nothing Nothing @@ -2075,14 +2097,10 @@ processChatCommand cxt nm = \case Just (AChatItem SCTDirect dir _ ci) -> Chat cInfo [CChatItem dir ci] emptyChatStats {unreadCount = 1, minUnreadItemId = chatItemId' ci} _ -> Chat cInfo [] emptyChatStats pure $ CRNewPreparedChat user $ AChat SCTDirect chat - APIPrepareGroup userId ccLink direct groupSLinkData -> withUserId userId $ \user -> do - let GroupShortLinkData {groupProfile = gp@GroupProfile {description}, publicGroupData = publicGroupData_} = groupSLinkData - publicMemberCount_ = (\PublicGroupData {publicMemberCount} -> publicMemberCount) <$> publicGroupData_ + APIPrepareGroup userId ccLink direct verifiedDomain groupSLinkData -> withUserId userId $ \user -> do + let GroupShortLinkData {groupProfile = GroupProfile {description}} = groupSLinkData welcomeSharedMsgId <- forM description $ \_ -> getSharedMsgId - let useRelays = not direct - subRole <- if useRelays then asks $ channelSubscriberRole . config else pure GRMember - gVar <- asks random - (gInfo, hostMember_) <- withStore $ \db -> createPreparedGroup db gVar cxt user gp False ccLink welcomeSharedMsgId useRelays subRole publicMemberCount_ + (gInfo, hostMember_) <- preparedGroupFromLink user ccLink direct groupSLinkData welcomeSharedMsgId (True <$ verifiedDomain) void $ createChatItem user (CDGroupSnd gInfo Nothing) False CIChatBanner Nothing Nothing (Just epochStart) let cd = maybe (CDChannelRcv gInfo Nothing) (CDGroupRcv gInfo Nothing) hostMember_ cInfo = GroupChat gInfo Nothing @@ -2265,10 +2283,28 @@ processChatCommand cxt nm = \case CVRConnectedContact ct -> pure $ CRContactAlreadyExists user ct CVRSentInvitation conn incognitoProfile -> pure $ CRSentInvitation user (mkPendingContactConnection conn Nothing) incognitoProfile APIConnect _ _ Nothing -> throwChatError CEInvalidConnReq - Connect incognito (Just cLink@(ACL m cLink')) -> withUser $ \user -> do - (ccLink, plan) <- connectPlan user cLink False Nothing `catchAllErrors` \e -> case cLink' of CLFull cReq -> pure (ACCL m (CCLink cReq Nothing), CPInvitationLink (ILPOk Nothing Nothing)); _ -> throwError e - connectWithPlan user incognito ccLink plan + Connect incognito (Just ct) -> withUser $ \user -> do + let con m cReq = pure (ACCL m (CCLink cReq Nothing), Nothing, Nothing, CPInvitationLink (ILPOk Nothing Nothing)) + (ccLink, planSimplexName, otherSimplexName, plan) <- connectPlan user ct PRMUnknown Nothing Nothing `catchAllErrors` \e -> case ct of + ACTarget m (CTFullContact cReq) -> con m cReq + ACTarget m (CTInv (CLFull cReq)) -> con m cReq + _ -> throwError e + connectWithPlan user incognito ccLink planSimplexName otherSimplexName plan Connect _ Nothing -> throwChatError CEInvalidConnReq + APIVerifyContactDomain contactId -> withUser $ \user -> do + ct@Contact {profile = LocalProfile {contactDomain}, preparedContact} <- withFastStore $ \db -> getContact db cxt user contactId + let connLink_ = preparedContact >>= \PreparedContact {connLinkToConnect = ACCL m (CCLink _ sLnk_)} -> ACSL m <$> sLnk_ + domain <- maybe (throwCmdError "contact has no name to verify") pure contactDomain + (verified, reason) <- verifyEntityDomain user nm NTContact domain connLink_ + ct' <- maybe (pure ct) (\v -> withFastStore' $ \db -> setContactDomainVerified db user ct v) verified + pure $ CRContactDomainVerified user ct' reason + APIVerifyGroupDomain groupId -> withUser $ \user -> do + g@GroupInfo {groupProfile = GroupProfile {publicGroup}, preparedGroup} <- withFastStore $ \db -> getGroupInfo db cxt user groupId + let connLink_ = preparedGroup >>= \PreparedGroup {connLinkToConnect = CCLink _ sLnk_} -> ACSL SCMContact <$> sLnk_ + domain <- maybe (throwCmdError "group has no name to verify") pure $ publicGroup >>= publicGroupAccess >>= groupDomainClaim + (verified, reason) <- verifyEntityDomain user nm NTPublicGroup domain connLink_ + g' <- maybe (pure g) (\v -> withFastStore' $ \db -> setGroupDomainVerified db user g v) verified + pure $ CRGroupDomainVerified user g' reason APIConnectContactViaAddress userId incognito contactId -> withUserId userId $ \user -> do ct@Contact {profile = LocalProfile {contactLink}} <- withFastStore $ \db -> getContact db cxt user contactId ccLink <- case contactLink of @@ -2285,7 +2321,7 @@ processChatCommand cxt nm = \case throwError e ConnectSimplex incognito -> withUser $ \user -> do plan <- contactRequestPlan user adminContactReq Nothing Nothing `catchAllErrors` const (pure $ CPContactAddress (CAPOk Nothing Nothing)) - connectWithPlan user incognito (ACCL SCMContact (CCLink adminContactReq Nothing)) plan + connectWithPlan user incognito (ACCL SCMContact (CCLink adminContactReq Nothing)) Nothing Nothing plan DeleteContact cName cdm -> withContactName cName $ \ctId -> APIDeleteChat (ChatRef CTDirect ctId Nothing) cdm ClearContact cName -> withContactName cName $ \chatId -> APIClearChat $ ChatRef CTDirect chatId Nothing APIListContacts userId -> withUserId userId $ \user -> @@ -2298,16 +2334,20 @@ processChatCommand cxt nm = \case Left e -> throwError $ ChatErrorStore e Right _ -> throwError $ ChatErrorStore SEDuplicateContactLink subMode <- chatReadVar subscriptionMode + gVar <- asks random + rootKey@(rootPubKey, rootPrivKey) <- liftIO $ atomically $ C.generateKeyPair gVar + let entityId = C.sha256Hash $ C.pubKeyBytes rootPubKey + (ccLink, preparedParams) <- withAgent $ \a -> prepareConnectionLink a (aUserId user) rootKey entityId True Nothing + ccLink' <- shortenCreatedLink ccLink -- TODO [relays] relay: add identity, key to link data? userData <- if isTrue userChatRelay then pure $ relayShortLinkData (userProfileDirect user Nothing Nothing True) else (`contactShortLinkData` Nothing) <$> presentUserBadge user Nothing (userProfileDirect user Nothing Nothing True) let userLinkData = UserContactLinkData UserContactData {direct = True, owners = [], relays = [], userData} - (connId, ccLink) <- withAgent $ \a -> createConnection a nm (aUserId user) True True SCMContact (Just userLinkData) Nothing IKPQOn subMode - ccLink' <- shortenCreatedLink ccLink + connId <- withAgent $ \a -> createConnectionForLink a nm (aUserId user) True ccLink preparedParams userLinkData IKPQOn subMode let ccLink'' = if isTrue userChatRelay then setShortLinkType CCTRelay ccLink' else ccLink' - withFastStore $ \db -> createUserContactLink db user connId ccLink'' subMode + withFastStore $ \db -> createUserContactLink db user connId ccLink'' subMode rootPrivKey pure $ CRUserContactLinkCreated user ccLink'' CreateMyAddress -> withUser $ \User {userId} -> processChatCommand cxt nm $ APICreateMyAddress userId @@ -2538,7 +2578,7 @@ processChatCommand cxt nm = \case then throwError e else do let relayResults = map toRelayResult results - toRelayResult (r, Left e) = AddRelayResult r (Just e) + toRelayResult (r, Left e') = AddRelayResult r (Just e') toRelayResult (r, Right _) = AddRelayResult r Nothing pure $ CRPublicGroupCreationFailed user relayResults where @@ -2756,34 +2796,35 @@ processChatCommand cxt nm = \case -- TODO [relays] possible optimization is to read only required members + relays g@(Group gInfo members) <- withFastStore $ \db -> getGroup db cxt user groupId when (selfSelected gInfo) $ throwCmdError "can't change role for self" - let (invitedMems, currentMems, unchangedMems, maxRole, anyAdmin, anyPending, anyPrivilegedTarget, finalPrivilegedCount) = selectMembers members + let (invitedMems, currentMems, unchangedMems, maxRole, anyAdmin, anyPending, anyPrivilegedTarget, anyRosterChange, finalPrivilegedCount) = selectMembers members when (length invitedMems + length currentMems + length unchangedMems /= length memberIds) $ throwChatError CEGroupMemberNotFound when (length memberIds > 1 && (anyAdmin || newRole >= GRAdmin)) $ throwCmdError "can't change role of multiple members when admins selected, or new role is admin" when anyPending $ throwCmdError "can't change role of members pending approval" assertUserGroupRole gInfo $ maximum ([GRAdmin, maxRole, newRole] :: [GroupMemberRole]) - -- in relay groups the roster has a single signer, so only the owner may change moderator/admin roles + -- in relay groups the roster has a single signer, so only the owner may change member/moderator/admin roles when (useRelays' gInfo && (isRosterRole newRole || anyPrivilegedTarget) && memberRole' (membership gInfo) /= GROwner) $ throwCmdError "only the group owner can change moderator and admin roles" when (useRelays' gInfo && isRosterRole newRole && finalPrivilegedCount > maxGroupRosterSize) $ throwCmdError $ "the number of members, moderators and admins would exceed the limit of " <> show maxGroupRosterSize (errs1, changed1) <- changeRoleInvitedMems user gInfo invitedMems - let doBumpRoster = useRelays' gInfo && memberRole' (membership gInfo) == GROwner && (isRosterRole newRole || anyPrivilegedTarget) - rosterVer <- if doBumpRoster then Just <$> reserveRosterVersion gInfo else pure Nothing + let doBumpRoster = useRelays' gInfo && memberRole' (membership gInfo) == GROwner && anyRosterChange + -- roster (with the change projected in) before the delta, so a relay stores the blob at this version before forwarding the delta + rosterVer <- if doBumpRoster then Just <$> broadcastRoster user gInfo (RDRoleChanged newRole currentMems) else pure Nothing (errs2, changed2, acis, msgSigned) <- changeRoleCurrentMems user g rosterVer currentMems - forM_ rosterVer $ \v -> broadcastRoster user gInfo v `catchAllErrors` eToView unless (null acis) $ toView $ CEvtNewChatItems user acis let errs = errs1 <> errs2 unless (null errs) $ toView $ CEvtChatErrors errs pure $ CRMembersRoleUser {user, groupInfo = gInfo, members = changed1 <> changed2, toRole = newRole, msgSigned} -- same order is not guaranteed where selfSelected GroupInfo {membership} = elem (groupMemberId' membership) memberIds - -- anyPrivilegedTarget: a target currently moderator/admin; finalPrivilegedCount: - -- moderators + admins after the change (targets take newRole, others keep their role). - selectMembers :: [GroupMember] -> ([GroupMember], [GroupMember], [GroupMember], GroupMemberRole, Bool, Bool, Bool, Int) - selectMembers = foldr' addMember ([], [], [], GRObserver, False, False, False, 0) + -- anyPrivilegedTarget: a target currently member/moderator/admin (gates the owner-only check); anyRosterChange: + -- a current member's role change that alters the roster blob - the only case that bumps the version, since a + -- bump with no delta reads as a gap to subscribers; finalPrivilegedCount: moderators + admins after the change. + selectMembers :: [GroupMember] -> ([GroupMember], [GroupMember], [GroupMember], GroupMemberRole, Bool, Bool, Bool, Bool, Int) + selectMembers = foldr' addMember ([], [], [], GRObserver, False, False, False, False, 0) where - addMember m@GroupMember {groupMemberId, memberStatus, memberRole} (invited, current, unchanged, maxRole, anyAdmin, anyPending, anyPrivTarget, privCount) + addMember m@GroupMember {groupMemberId, memberStatus, memberRole} (invited, current, unchanged, maxRole, anyAdmin, anyPending, anyPrivTarget, anyRosterChange, privCount) | groupMemberId `elem` memberIds = let maxRole' = max maxRole memberRole anyAdmin' = anyAdmin || memberRole >= GRAdmin @@ -2791,10 +2832,11 @@ processChatCommand cxt nm = \case anyPrivTarget' = anyPrivTarget || isRosterRole memberRole privCount' = if isRosterRole newRole then privCount + 1 else privCount in if - | memberRole == newRole -> (invited, current, m : unchanged, maxRole', anyAdmin', anyPending', anyPrivTarget', privCount') - | memberStatus == GSMemInvited -> (m : invited, current, unchanged, maxRole', anyAdmin', anyPending', anyPrivTarget', privCount') - | otherwise -> (invited, m : current, unchanged, maxRole', anyAdmin', anyPending', anyPrivTarget', privCount') - | otherwise = (invited, current, unchanged, maxRole, anyAdmin, anyPending, anyPrivTarget, if isRosterRole memberRole then privCount + 1 else privCount) + | memberRole == newRole -> (invited, current, m : unchanged, maxRole', anyAdmin', anyPending', anyPrivTarget', anyRosterChange, privCount') + | memberStatus == GSMemInvited -> (m : invited, current, unchanged, maxRole', anyAdmin', anyPending', anyPrivTarget', anyRosterChange, privCount') + -- a current member's role actually changes here; it alters the roster iff the old or new role is on it + | otherwise -> (invited, m : current, unchanged, maxRole', anyAdmin', anyPending', anyPrivTarget', anyRosterChange || isRosterRole newRole || isRosterRole memberRole, privCount') + | otherwise = (invited, current, unchanged, maxRole, anyAdmin, anyPending, anyPrivTarget, anyRosterChange, if isRosterRole memberRole then privCount + 1 else privCount) changeRoleInvitedMems :: User -> GroupInfo -> [GroupMember] -> CM ([ChatError], [GroupMember]) changeRoleInvitedMems user gInfo memsToChange = do -- not batched, as we need to send different invitations to different connections anyway @@ -2886,7 +2928,7 @@ processChatCommand cxt nm = \case withGroupLock "removeMembers" groupId $ do -- TODO [relays] possible optimization is to read only required members + relays Group gInfo members <- withFastStore $ \db -> getGroup db cxt user groupId - let (count, invitedMems, pendingApprvMems, pendingRvwMems, currentMems, maxRole, anyAdmin, anyPrivilegedRemoved) = selectMembers gmIds members + let (count, invitedMems, pendingApprvMems, pendingRvwMems, currentMems, maxRole, anyAdmin, anyPrivilegedRemoved, anyRosterRemoved) = selectMembers gmIds members gmIds = S.fromList $ L.toList groupMemberIds memCount = length groupMemberIds when (count /= memCount) $ throwChatError CEGroupMemberNotFound @@ -2896,15 +2938,15 @@ processChatCommand cxt nm = \case throwCmdError "only the group owner can remove members, moderators and admins" (errs1, deleted1) <- deleteInvitedMems user invitedMems let recipients = filter memberCurrent members - let doBumpRoster = useRelays' gInfo && memberRole' (membership gInfo) == GROwner && anyPrivilegedRemoved - rosterVer <- if doBumpRoster then Just <$> reserveRosterVersion gInfo else pure Nothing + let doBumpRoster = useRelays' gInfo && memberRole' (membership gInfo) == GROwner && anyRosterRemoved + -- roster (excluding the removed members) before the delta, so a relay stores the blob at this version before forwarding the delta + rosterVer <- if doBumpRoster then Just <$> broadcastRoster user gInfo (RDRemoved currentMems) else pure Nothing (errs2, deleted2, acis2, signed2) <- deleteMemsSend user gInfo Nothing rosterVer recipients currentMems (errs3, deleted3, acis3, signed3) <- foldM (\acc m -> deletePendingMember acc user gInfo [m] m) ([], [], [], False) pendingApprvMems let moderators = filter (\GroupMember {memberRole} -> memberRole >= GRModerator) members (errs4, deleted4, acis4, signed4) <- foldM (\acc m -> deletePendingMember acc user gInfo (m : moderators) m) ([], [], [], False) pendingRvwMems - forM_ rosterVer $ \v -> broadcastRoster user gInfo v `catchAllErrors` eToView let acis = acis2 <> acis3 <> acis4 errs = errs1 <> errs2 <> errs3 <> errs4 deleted = deleted1 <> deleted2 <> deleted3 <> deleted4 @@ -2919,20 +2961,24 @@ processChatCommand cxt nm = \case unless (null errs) $ toView $ CEvtChatErrors errs pure $ CRUserDeletedMembers user gInfo' deleted withMessages msgSigned -- same order is not guaranteed where - selectMembers :: S.Set GroupMemberId -> [GroupMember] -> (Int, [GroupMember], [GroupMember], [GroupMember], [GroupMember], GroupMemberRole, Bool, Bool) - selectMembers gmIds = foldl' addMember (0, [], [], [], [], GRObserver, False, False) + -- anyPrivilegedRemoved: any removed member is member/moderator/admin (gates the owner-only check); anyRosterRemoved: + -- a current roster member is removed - the only case that alters the blob and so bumps the version (pending/ + -- invited members aren't on the roster, and a bump with no delta reads as a gap to subscribers). + selectMembers :: S.Set GroupMemberId -> [GroupMember] -> (Int, [GroupMember], [GroupMember], [GroupMember], [GroupMember], GroupMemberRole, Bool, Bool, Bool) + selectMembers gmIds = foldl' addMember (0, [], [], [], [], GRObserver, False, False, False) where - addMember acc@(n, invited, pendingApprv, pendingRvw, current, maxRole, anyAdmin, anyPrivRemoved) m@GroupMember {groupMemberId, memberStatus, memberRole} + addMember acc@(n, invited, pendingApprv, pendingRvw, current, maxRole, anyAdmin, anyPrivRemoved, anyRosterRemoved) m@GroupMember {groupMemberId, memberStatus, memberRole} | groupMemberId `S.member` gmIds = let maxRole' = max maxRole memberRole anyAdmin' = anyAdmin || memberRole >= GRAdmin anyPrivRemoved' = anyPrivRemoved || isRosterRole memberRole n' = n + 1 in case memberStatus of - GSMemInvited -> (n', m : invited, pendingApprv, pendingRvw, current, maxRole', anyAdmin', anyPrivRemoved') - GSMemPendingApproval -> (n', invited, m : pendingApprv, pendingRvw, current, maxRole', anyAdmin', anyPrivRemoved') - GSMemPendingReview -> (n', invited, pendingApprv, m : pendingRvw, current, maxRole', anyAdmin', anyPrivRemoved') - _ -> (n', invited, pendingApprv, pendingRvw, m : current, maxRole', anyAdmin', anyPrivRemoved') + GSMemInvited -> (n', m : invited, pendingApprv, pendingRvw, current, maxRole', anyAdmin', anyPrivRemoved', anyRosterRemoved) + GSMemPendingApproval -> (n', invited, m : pendingApprv, pendingRvw, current, maxRole', anyAdmin', anyPrivRemoved', anyRosterRemoved) + GSMemPendingReview -> (n', invited, pendingApprv, m : pendingRvw, current, maxRole', anyAdmin', anyPrivRemoved', anyRosterRemoved) + -- removed current member: alters the roster blob iff it currently holds a roster role + _ -> (n', invited, pendingApprv, pendingRvw, m : current, maxRole', anyAdmin', anyPrivRemoved', anyRosterRemoved || isRosterRole memberRole) | otherwise = acc deleteInvitedMems :: User -> [GroupMember] -> CM ([ChatError], [GroupMember]) deleteInvitedMems user memsToDelete = do @@ -3094,11 +3140,15 @@ processChatCommand cxt nm = \case updateGroupProfileByName gName $ \p -> p {description} ShowGroupDescription gName -> withUser $ \user -> CRGroupDescription user <$> withFastStore (\db -> getGroupInfoByName db cxt user gName) - SetPublicGroupAccess gName access -> withUser $ \user -> do - gInfo@GroupInfo {groupProfile = p@GroupProfile {publicGroup}} <- withStore $ \db -> - getGroupIdByName db user gName >>= getGroupInfo db cxt user + APISetPublicGroupAccess gId access@PublicGroupAccess {groupDomainClaim = newClaim} -> withUser $ \user -> do + gInfo@GroupInfo {groupProfile = p@GroupProfile {publicGroup}} <- withStore $ \db -> getGroupInfo db cxt user gId case publicGroup of - Just pg -> runUpdateGroupProfile user gInfo p {publicGroup = Just pg {publicGroupAccess = Just access}} + Just pg@PublicGroupProfile {groupLink, publicGroupAccess = existingAccess} -> do + forM_ (claimDomain <$> newClaim) $ \newDomain -> + when (Just newDomain /= (claimDomain <$> (existingAccess >>= groupDomainClaim))) $ do + NameRecord {nrSimplexChannel} <- withAgent $ \a -> resolveSimplexName a nm (aUserId user) newDomain + unless (nameResolvesTo groupLink nrSimplexChannel) $ throwChatError $ CESimplexDomainNotReady newDomain SDENoValidLink + runUpdateGroupProfile user gInfo p {publicGroup = Just pg {publicGroupAccess = Just access}} Nothing -> throwChatError $ CECommandError "not a public group" APICreateGroupLink groupId mRole -> withUser $ \user -> withGroupLock "createGroupLink" groupId $ do gInfo@GroupInfo {groupProfile} <- withFastStore $ \db -> getGroupInfo db cxt user groupId @@ -3213,6 +3263,9 @@ processChatCommand cxt nm = \case sqSecured <- withAgent $ \a -> joinConnection a nm (aUserId user) (aConnId conn) True cReq dm PQSupportOff subMode let newStatus = if sqSecured then ConnSndReady else ConnJoined void $ withFastStore' $ \db -> updateConnectionStatusFromTo db conn ConnPrepared newStatus + SetPublicGroupAccess gName access -> withUser $ \user -> do + groupId <- withFastStore $ \db -> getGroupIdByName db user gName + processChatCommand cxt nm $ APISetPublicGroupAccess groupId access CreateGroupLink gName mRole -> withUser $ \user -> do groupId <- withFastStore $ \db -> getGroupIdByName db user gName processChatCommand cxt nm $ APICreateGroupLink groupId mRole @@ -3741,9 +3794,7 @@ processChatCommand cxt nm = \case -- gInfo_ is Maybe (Maybe GroupInfo), where Just Nothing means "some unknown group", e.g. when joining via link without profile profileToSend <- presentUserBadge user incognitoProfile $ case gInfo_ of - Just gInfo_' -> - let allowSimplexLinks = maybe True groupUserAllowSimplexLinks gInfo_' - in userProfileInGroup' user allowSimplexLinks incognitoProfile + Just gInfo_' -> userProfileInGroup' user gInfo_' incognitoProfile Nothing -> userProfileDirect user incognitoProfile Nothing True dm <- case gInfo_ of Just (Just gInfo) | useRelays' gInfo -> case relayMemberId_ of @@ -3819,16 +3870,16 @@ processChatCommand cxt nm = \case -- non-incognito (filtered above), so the user's badge is presented; a profile update keeps the badge instead of clearing it ctSndEvent :: ChangedProfileContact -> CM (ConnOrGroupId, Maybe MsgSigning, ChatMsgEvent 'Json) ctSndEvent ChangedProfileContact {mergedProfile', conn = Connection {connId}} = do - p <- presentUserBadge user' Nothing mergedProfile' - pure (ConnectionId connId, Nothing, XInfo p) + p'' <- presentUserBadge user' Nothing mergedProfile' + pure (ConnectionId connId, Nothing, XInfo p'') ctMsgReq :: ChangedProfileContact -> Either ChatError SndMessage -> Either ChatError ChatMsgReq ctMsgReq ChangedProfileContact {conn} = fmap $ \SndMessage {msgId, msgBody} -> (conn, MsgFlags {notification = hasNotification XInfo_}, (vrValue msgBody, [msgId])) setMyAddressData :: User -> UserContactLink -> CM UserContactLink - setMyAddressData user@User {userChatRelay} ucl@UserContactLink {userContactLinkId, connLinkContact = CCLink connFullLink _sLnk_, addressSettings} = do + setMyAddressData user@User {userChatRelay} ucl@UserContactLink {userContactLinkId, connLinkContact = CCLink connFullLink _, addressSettings} = do conn <- withFastStore $ \db -> getUserAddressConnection db cxt user - shortLinkProfile <- presentUserBadge user Nothing $ userProfileDirect user Nothing Nothing True + shortLinkProfile <- presentUserBadge user Nothing (userProfileDirect user Nothing Nothing True) -- TODO [short links] do not save address to server if data did not change, spinners, error handling let userData | isTrue userChatRelay = relayShortLinkData shortLinkProfile @@ -4051,9 +4102,8 @@ processChatCommand cxt nm = \case conn <- createRelayConnection db cxt user (groupMemberId' relayMember) connId ConnPrepared chatV subMode pure (relayMember, conn, groupRelay) let GroupMember {memberRole = userRole, memberId = userMemberId} = membership - allowSimplexLinks = groupUserAllowSimplexLinks gInfo GroupMember {memberId = relayMemberId} = relayMember - membershipProfile <- presentUserBadge user (incognitoMembershipProfile gInfo) $ redactedMemberProfile allowSimplexLinks $ fromLocalProfile $ memberProfile membership + membershipProfile <- presentUserBadge user (incognitoMembershipProfile gInfo) $ redactedMemberProfile gInfo membership $ fromLocalProfile $ memberProfile membership let relayInv = GroupRelayInvitation { fromMember = MemberIdRole userMemberId userRole, fromMemberProfile = membershipProfile, @@ -4129,13 +4179,13 @@ processChatCommand cxt nm = \case pure (gId, chatSettings) _ -> throwCmdError "not supported" processChatCommand cxt nm $ APISetChatSettings (ChatRef cType chatId Nothing) $ updateSettings chatSettings - connectPlan :: User -> AConnectionLink -> Bool -> Maybe LinkOwnerSig -> CM (ACreatedConnLink, ConnectionPlan) - connectPlan user (ACL SCMInvitation cLink) _ sig_ = case cLink of + connectPlan :: User -> AConnectTarget -> PlanResolveMode -> Maybe LinkOwnerSig -> Maybe (Either ChatError NameRecord) -> CM (ACreatedConnLink, Maybe SimplexNameInfo, Maybe SimplexNameInfo, ConnectionPlan) + connectPlan user (ACTarget SCMInvitation (CTInv cLink)) _ sig_ _ = case cLink of CLFull cReq -> invitationReqAndPlan cReq Nothing Nothing Nothing CLShort l -> do let l' = serverShortLink l knownLinkPlans l' >>= \case - Just r -> pure r + Just (l, p) -> pure (l, Nothing, Nothing, p) Nothing -> do (FixedLinkData {linkConnReq = cReq, rootKey}, cData) <- getShortLinkConnReq nm user l' contactSLinkData_ <- mapM linkDataBadge =<< liftIO (decodeLinkUserData cData) @@ -4150,52 +4200,112 @@ processChatCommand cxt nm = \case Nothing -> bimap inv (CPInvitationLink . ILPKnown) <$$> getContactViaShortLinkToConnect db cxt user l' invitationReqAndPlan cReq sLnk_ cld ov = do plan <- invitationRequestPlan user cReq cld ov `catchAllErrors` (pure . CPError) - pure (ACCL SCMInvitation (CCLink cReq sLnk_), plan) - connectPlan user (ACL SCMContact cLink) resolveKnown sig_ = case cLink of - CLFull cReq -> do + pure (ACCL SCMInvitation (CCLink cReq sLnk_), Nothing, Nothing, plan) + connectPlan user (ACTarget SCMContact ct) resolveMode sig_ nameRec = case ct of + CTDomain d + -- local search only: look up #d then @d in the store, without online name resolution + | resolveMode == PRMNever -> connectPlanNoName $ ChatError CENotResolvedLocally + | otherwise -> + tryAllErrors (withAgent $ \a -> resolveSimplexName a nm (aUserId user) d) >>= \case + Right nr + | isJust (firstNameLink CCTChannel (nrSimplexChannel nr)) -> + (addOther nr <$> connectPlanName NTPublicGroup (Right nr)) `catchAllErrors` \e -> + (addOther nr <$> connectPlanName NTContact (Right nr) `catchAllErrors` \_ -> throwError e) + | isJust (firstNameLink CCTContact (nrSimplexContact nr)) -> + addOther nr <$> connectPlanName NTContact (Right nr) + | otherwise -> connectPlanNoName $ ChatError $ CESimplexDomainNotReady d SDENoValidLink + Left e -> connectPlanNoName e + where + connectPlanName nameType nr_ = connectPlan user connTarget resolveMode sig_ (Just nr_) + where + connTarget = ACTarget SCMContact $ CTShortContact $ CTName $ SimplexNameInfo nameType d + connectPlanNoName e = + connectPlanName NTPublicGroup (Left e) `catchAllErrors` \e' -> + (connectPlanName NTContact (Left e) `catchAllErrors` \_ -> throwError e') + -- the same domain can resolve to both an @ name (contact or business) and a # channel; + -- keyed off the resolved name's type, so a contact name returning a business group still offers the channel + addOther nr (l, planName, _, p) = (l, planName, otherName, p) + where + otherName = case planName of + Just (SimplexNameInfo NTContact _) | isJust (firstNameLink CCTChannel (nrSimplexChannel nr)) -> Just $ SimplexNameInfo NTPublicGroup d + Just (SimplexNameInfo NTPublicGroup _) | isJust (firstNameLink CCTContact (nrSimplexContact nr)) -> Just $ SimplexNameInfo NTContact d + _ -> Nothing + CTFullContact cReq -> do plan <- contactOrGroupRequestPlan user cReq `catchAllErrors` (pure . CPError) - pure (ACCL SCMContact $ CCLink cReq Nothing, plan) - CLShort l@(CSLContact _ ct _ _) -> - case ct of + pure (ACCL SCMContact $ CCLink cReq Nothing, Nothing, Nothing, plan) + CTShortContact nl -> + (\(l, p) -> (l, simplexName_, Nothing, p)) <$> case ctType of CCTContact -> knownLinkPlans >>= \case Just r -> pure r Nothing -> do + when (resolveMode == PRMNever) $ throwChatError CENotResolvedLocally + l' <- resolveSLink (FixedLinkData {linkConnReq = cReq, rootKey}, cData) <- getShortLinkConnReq nm user l' + contactSLinkData_ <- mapM linkDataBadge =<< liftIO (decodeLinkUserData cData) + let linkProfile_ = (\ContactShortLinkData {profile} -> profile) <$> contactSLinkData_ + linkDomain_ = linkProfile_ >>= \Profile {contactDomain} -> claimDomain <$> contactDomain + planDomain = case nl of CTName ni -> Just (nameDomain ni); _ -> Nothing + refreshContact ct' = case (planDomain, linkProfile_) of + (Just _, Just p) -> updateContactFromLinkData user ct' p + _ -> pure ct' + forM_ planDomain $ \nameDomain -> + unless (linkDomain_ == Just nameDomain) $ throwChatError $ CESimplexDomainNotReady nameDomain SDEUnknownDomain withFastStore' (\db -> getContactWithoutConnViaShortAddress db cxt user l') >>= \case - Just ct' | not (contactDeleted ct') -> pure (con cReq, CPContactAddress (CAPContactViaAddress ct')) + Just ct' | not (contactDeleted ct') -> do + ct'' <- refreshContact ct' + pure (con l' cReq, CPContactAddress (CAPContactViaAddress ct'')) _ -> do - contactSLinkData_ <- mapM linkDataBadge =<< liftIO (decodeLinkUserData cData) let ContactLinkData _ UserContactData {owners} = cData ov = verifyLinkOwner rootKey owners l' sig_ plan <- contactRequestPlan user cReq contactSLinkData_ ov - pure (con cReq, plan) + case plan of + CPContactAddress (CAPKnown ct') -> do + ct'' <- refreshContact ct' + pure (con l' cReq, plan {contactAddressPlan = CAPKnown ct''}) + CPContactAddress (CAPContactViaAddress ct') -> do + ct'' <- refreshContact ct' + pure (con l' cReq, plan {contactAddressPlan = CAPContactViaAddress ct''}) + _ -> pure (con l' cReq, plan) where + knownLinkPlans :: CM (Maybe (ACreatedConnLink, ConnectionPlan)) knownLinkPlans = withFastStore $ \db -> - liftIO (getUserContactLinkViaShortLink db user l') >>= \case - Just UserContactLink {connLinkContact = CCLink cReq _} -> pure $ Just (con cReq, CPContactAddress CAPOwnLink) + liftIO (getUserContactLinkViaTarget db user nl') >>= \case + Just UserContactLink {connLinkContact} -> pure $ Just (ACCL SCMContact connLinkContact, CPContactAddress CAPOwnLink) Nothing -> - getContactViaShortLinkToConnect db cxt user l' >>= \case - Just (cReq, ct') -> pure $ if contactDeleted ct' then Nothing else Just (con cReq, CPContactAddress (CAPKnown ct')) - Nothing -> (gPlan =<<) <$> getGroupViaShortLinkToConnect db cxt user l' + getContactToConnect db cxt user nl' >>= \case + Just (ccl, ct') -> pure $ if contactDeleted ct' then Nothing else Just (ACCL SCMContact ccl, CPContactAddress (CAPKnown ct')) + Nothing -> (gPlan =<<) <$> getGroupToConnect db cxt user nl' CCTGroup -> groupShortLinkPlan CCTChannel -> groupShortLinkPlan CCTRelay -> throwCmdError "chat relay links are not supported in this version" where - l' = serverShortLink l - con cReq = ACCL SCMContact $ CCLink cReq (Just l') - gPlan (cReq, g) = if memberRemoved (membership g) then Nothing else Just (con cReq, CPGroupLink (GLPKnown g (BoolDef False) Nothing (ListDef []))) + (nl', simplexName_) = case nl of + CTLink sl -> (CTLink (serverShortLink sl), Nothing) + CTName ni -> (nl, Just ni) + ctType = case nl of + CTLink (CSLContact _ t _ _) -> t + CTName SimplexNameInfo {nameType = NTContact} -> CCTContact + CTName SimplexNameInfo {nameType = NTPublicGroup} -> CCTChannel + resolveSLink = case nl' of + CTLink l' -> pure l' + CTName n -> serverShortLink <$> resolveNameLink n + con l' cReq = ACCL SCMContact $ CCLink cReq (Just l') + gPlan (ccl, g) = if memberRemoved (membership g) then Nothing else Just (ACCL SCMContact ccl, CPGroupLink (GLPKnown g False Nothing (ListDef []))) + groupShortLinkPlan :: CM (ACreatedConnLink, ConnectionPlan) groupShortLinkPlan = knownLinkPlans >>= \case Just (_, CPGroupLink (GLPKnown g _ _ _)) - | resolveKnown -> resolveKnownGroup g + | resolveMode == PRMAllGroups -> resolveKnownGroup g Just r -> pure r Nothing -> do + when (resolveMode == PRMNever) $ throwChatError CENotResolvedLocally + l' <- resolveSLink (fd, cData@(ContactLinkData _ UserContactData {direct, owners, relays})) <- getShortLinkConnReq' nm user l' groupSLinkData_ <- liftIO $ decodeLinkUserData cData if - | not direct && unsupportedGroupType groupSLinkData_ -> pure (con (linkConnReq fd), CPGroupLink (GLPUpdateRequired groupSLinkData_)) - | not direct && null relays -> pure (con (linkConnReq fd), CPGroupLink (GLPNoRelays groupSLinkData_)) + | not direct && unsupportedGroupType groupSLinkData_ -> pure (con l' (linkConnReq fd), CPGroupLink (GLPUpdateRequired groupSLinkData_)) + | not direct && null relays -> pure (con l' (linkConnReq fd), CPGroupLink (GLPNoRelays groupSLinkData_)) | otherwise -> do let FixedLinkData {linkConnReq = cReq, linkEntityId, rootKey} = fd linkInfo = GroupShortLinkInfo {direct, groupRelays = relays, publicGroupId = B64UrlByteString <$> linkEntityId} @@ -4206,17 +4316,35 @@ processChatCommand cxt nm = \case (Nothing, Nothing) -> pure () _ -> throwChatError CEInvalidConnReq let ov = verifyLinkOwner rootKey owners l' sig_ - plan <- groupJoinRequestPlan user cReq (Just linkInfo) groupSLinkData_ ov - pure (con cReq, plan) + planDomain = case nl of CTName ni -> Just (nameDomain ni); _ -> Nothing + plan0 <- groupJoinRequestPlan user cReq (Just linkInfo) groupSLinkData_ ov + -- a joined channel is found by link but not by name (its domain is not verified locally, + -- e.g. an un-upgraded relay dropped the claim); refresh its profile from the fresh link + -- data and mark it verified, so the check below passes and future by-name lookups match + plan <- case (planDomain, plan0, groupSLinkData_) of + (Just _, CPGroupLink (GLPKnown g u o os), Just sLinkData) -> + (\(g', _) -> CPGroupLink (GLPKnown g' u o os)) <$> updateGroupFromLinkData user g sLinkData + _ -> pure plan0 + forM_ planDomain $ \nameDomain -> + let domain_ = (\GroupProfile {publicGroup} -> claimDomain <$> (publicGroup >>= publicGroupAccess >>= groupDomainClaim)) =<< case plan of + CPGroupLink (GLPOk _ (Just GroupShortLinkData {groupProfile}) _) -> Just groupProfile + CPGroupLink (GLPKnown GroupInfo {groupProfile} _ _ _) -> Just groupProfile + CPGroupLink (GLPOwnLink GroupInfo {groupProfile}) -> Just groupProfile + CPGroupLink (GLPConnectingProhibit (Just GroupInfo {groupProfile})) -> Just groupProfile + _ -> (\GroupShortLinkData {groupProfile} -> groupProfile) <$> groupSLinkData_ + in unless (domain_ == Just nameDomain) $ throwChatError $ CESimplexDomainNotReady nameDomain SDEUnknownDomain + pure (con l' cReq, plan) where unsupportedGroupType = \case Just GroupShortLinkData {groupProfile = GroupProfile {publicGroup = Just PublicGroupProfile {groupType}}} -> groupType /= GTChannel _ -> False + knownLinkPlans :: CM (Maybe (ACreatedConnLink, ConnectionPlan)) knownLinkPlans = withFastStore $ \db -> - liftIO (getGroupInfoViaUserShortLink db cxt user l') >>= \case - Just (cReq, g) -> pure $ Just (con cReq, CPGroupLink (GLPOwnLink g)) - Nothing -> (gPlan =<<) <$> getGroupViaShortLinkToConnect db cxt user l' + liftIO (getGroupInfoViaUserTarget db cxt user nl') >>= \case + Just (ccl, g) -> pure $ Just (ACCL SCMContact ccl, CPGroupLink (GLPOwnLink g)) + Nothing -> (gPlan =<<) <$> getGroupToConnect db cxt user nl' resolveKnownGroup g = do + l' <- resolveSLink (fd@FixedLinkData {rootKey = rk}, cData@(ContactLinkData _ UserContactData {owners})) <- getShortLinkConnReq' nm user l' groupSLinkData_ <- liftIO $ decodeLinkUserData cData let ov = verifyLinkOwner rk owners l' sig_ @@ -4224,21 +4352,31 @@ processChatCommand cxt nm = \case (g', updated) <- case groupSLinkData_ of Just sLinkData -> updateGroupFromLinkData user g sLinkData _ -> pure (g, False) - pure (con (linkConnReq fd), CPGroupLink (GLPKnown g' (BoolDef updated) ov (ListDef glOwners))) - connectWithPlan :: User -> IncognitoEnabled -> ACreatedConnLink -> ConnectionPlan -> CM ChatResponse - connectWithPlan user@User {userId} incognito ccLink plan + pure (con l' (linkConnReq fd), CPGroupLink (GLPKnown g' updated ov (ListDef glOwners))) + -- resolve a name to its first contact/channel short link + resolveNameLink :: SimplexNameInfo -> CM (ConnShortLink 'CMContact) + resolveNameLink SimplexNameInfo {nameType, nameDomain} = do + NameRecord {nrSimplexContact, nrSimplexChannel} <- maybe (withAgent $ \a -> resolveSimplexName a nm (aUserId user) nameDomain) (ExceptT . pure) nameRec + let (candidates, ctType') = case nameType of + NTContact -> (nrSimplexContact, CCTContact) + NTPublicGroup -> (nrSimplexChannel, CCTChannel) + maybe (throwChatError $ CESimplexDomainNotReady nameDomain SDENoValidLink) pure $ firstNameLink ctType' candidates + connectWithPlan :: User -> IncognitoEnabled -> ACreatedConnLink -> Maybe SimplexNameInfo -> Maybe SimplexNameInfo -> ConnectionPlan -> CM ChatResponse + connectWithPlan user@User {userId} incognito ccLink planSimplexName otherSimplexName plan | connectionPlanProceed plan = do case plan of CPError e -> eToView e; _ -> pure () case plan of CPContactAddress (CAPContactViaAddress Contact {contactId}) -> processChatCommand cxt nm $ APIConnectContactViaAddress userId incognito contactId + CPContactAddress (CAPOk (Just sld) _) | isJust vName -> connectContactViaName sld vName CPGroupLink (GLPOk (Just GroupShortLinkInfo {direct = False}) (Just gld) _) - | ACCL SCMContact ccl <- ccLink -> joinChannelViaRelays ccl gld + | ACCL SCMContact ccl <- ccLink -> joinChannelViaRelays ccl gld vName _ -> processChatCommand cxt nm $ APIConnect userId incognito $ Just ccLink - | otherwise = pure $ CRConnectionPlan user ccLink plan + | otherwise = pure $ CRConnectionPlan user ccLink planSimplexName otherSimplexName plan where - joinChannelViaRelays :: CreatedLinkContact -> GroupShortLinkData -> CM ChatResponse - joinChannelViaRelays ccl gld = do + vName = nameDomain <$> planSimplexName + joinChannelViaRelays :: CreatedLinkContact -> GroupShortLinkData -> Maybe SimplexDomain -> CM ChatResponse + joinChannelViaRelays ccl gld vName = do GroupInfo {groupId} <- prepareChannelGroup processChatCommand cxt nm APIConnectPreparedGroup {groupId, incognito, ownerContact = Nothing, msgContent_ = Nothing} `catchAllErrors` \e -> do @@ -4246,13 +4384,19 @@ processChatCommand cxt nm = \case throwError e where prepareChannelGroup = - processChatCommand cxt nm (APIPrepareGroup userId ccl False gld) >>= \case + processChatCommand cxt nm (APIPrepareGroup userId ccl False vName gld) >>= \case CRNewPreparedChat _ (AChat SCTGroup (Chat (GroupChat gInfo _) _ _)) -> pure gInfo _ -> throwChatError $ CEException "joinChannelViaRelays: unexpected response from APIPrepareGroup" deletePreparedChannel groupId = do gInfo <- withFastStore $ \db -> getGroupInfo db cxt user groupId deleteGroupConnections user gInfo False withFastStore' $ \db -> deleteGroup db user gInfo + connectContactViaName :: ContactShortLinkData -> Maybe SimplexDomain -> CM ChatResponse + connectContactViaName sld vName = + processChatCommand cxt nm (APIPrepareContact userId ccLink vName sld) >>= \case + CRNewPreparedChat _ (AChat SCTDirect (Chat (DirectChat Contact {contactId}) _ _)) -> + processChatCommand cxt nm (APIConnectPreparedContact contactId incognito Nothing) + _ -> throwChatError $ CEException "connectContactViaName: unexpected response from APIPrepareContact" invitationRequestPlan :: User -> ConnReqInvitation -> Maybe ContactShortLinkData -> Maybe OwnerVerification -> CM ConnectionPlan invitationRequestPlan user cReq cld ov = do maybe (CPInvitationLink (ILPOk cld ov)) (invitationEntityPlan cld ov) @@ -4285,21 +4429,22 @@ processChatCommand cxt nm = \case contactRequestPlan user (CRContactUri crData) cld ov = do let cReqSchemas = contactCReqSchemas crData cReqHashes = bimap contactCReqHash contactCReqHash cReqSchemas + plan p = pure $ CPContactAddress p withFastStore' (\db -> getUserContactLinkByConnReq db user cReqSchemas) >>= \case - Just _ -> pure $ CPContactAddress CAPOwnLink + Just _ -> plan $ CAPOwnLink Nothing -> withFastStore' (\db -> getContactConnEntityByConnReqHash db cxt user cReqHashes) >>= \case Nothing -> withFastStore' (\db -> getContactWithoutConnViaAddress db cxt user cReqSchemas) >>= \case - Just ct | not (contactDeleted ct) -> pure $ CPContactAddress (CAPContactViaAddress ct) - _ -> pure $ CPContactAddress (CAPOk cld ov) + Just ct | not (contactDeleted ct) -> plan $ CAPContactViaAddress ct + _ -> plan $ CAPOk cld ov Just (RcvDirectMsgConnection Connection {connStatus} Nothing) - | connStatus == ConnPrepared -> pure $ CPContactAddress (CAPOk cld ov) - | otherwise -> pure $ CPContactAddress CAPConnectingConfirmReconnect + | connStatus == ConnPrepared -> plan $ CAPOk cld ov + | otherwise -> plan CAPConnectingConfirmReconnect Just (RcvDirectMsgConnection _ (Just ct)) - | not (contactReady ct) && contactActive ct -> pure $ CPContactAddress (CAPConnectingProhibit ct) - | contactDeleted ct -> pure $ CPContactAddress (CAPOk cld ov) - | otherwise -> pure $ CPContactAddress (CAPKnown ct) + | not (contactReady ct) && contactActive ct -> plan $ CAPConnectingProhibit ct + | contactDeleted ct -> plan $ CAPOk cld ov + | otherwise -> plan $ CAPKnown ct -- TODO [short links] RcvGroupMsgConnection branch is deprecated? (old group link protocol?) Just (RcvGroupMsgConnection _ gInfo _) -> groupPlan gInfo Nothing Nothing Nothing Just _ -> throwCmdError "found connection entity is not RcvDirectMsgConnection or RcvGroupMsgConnection" @@ -4307,27 +4452,30 @@ processChatCommand cxt nm = \case groupJoinRequestPlan user (CRContactUri crData) linkInfo gld ov = do let cReqSchemas = contactCReqSchemas crData cReqHashes = bimap contactCReqHash contactCReqHash cReqSchemas + plan p = pure $ CPGroupLink p withFastStore' (\db -> getGroupInfoByUserContactLinkConnReq db cxt user cReqSchemas) >>= \case - Just g -> pure $ CPGroupLink (GLPOwnLink g) + Just g -> plan $ GLPOwnLink g Nothing -> do connEnt_ <- withFastStore' $ \db -> getContactConnEntityByConnReqHash db cxt user cReqHashes gInfo_ <- withFastStore' $ \db -> getGroupInfoByGroupLinkHash db cxt user cReqHashes case (gInfo_, connEnt_) of - (Nothing, Nothing) -> pure $ CPGroupLink (GLPOk linkInfo gld ov) + (Nothing, Nothing) -> plan $ GLPOk linkInfo gld ov -- TODO [short links] RcvDirectMsgConnection branches are deprecated? (old group link protocol?) - (Nothing, Just (RcvDirectMsgConnection _conn Nothing)) -> pure $ CPGroupLink GLPConnectingConfirmReconnect + (Nothing, Just (RcvDirectMsgConnection _conn Nothing)) -> plan $ GLPConnectingConfirmReconnect (Nothing, Just (RcvDirectMsgConnection _ (Just ct))) - | not (contactReady ct) && contactActive ct -> pure $ CPGroupLink (GLPConnectingProhibit gInfo_) - | otherwise -> pure $ CPGroupLink (GLPOk linkInfo gld ov) + | not (contactReady ct) && contactActive ct -> plan $ GLPConnectingProhibit gInfo_ + | otherwise -> plan $ GLPOk linkInfo gld ov (Nothing, Just _) -> throwCmdError "found connection entity is not RcvDirectMsgConnection" (Just gInfo, _) -> groupPlan gInfo linkInfo gld ov groupPlan :: GroupInfo -> Maybe GroupShortLinkInfo -> Maybe GroupShortLinkData -> Maybe OwnerVerification -> CM ConnectionPlan groupPlan gInfo@GroupInfo {membership} linkInfo gld ov - | memberStatus membership == GSMemRejected = pure $ CPGroupLink (GLPKnown gInfo (BoolDef False) ov (ListDef [])) + | memberStatus membership == GSMemRejected = plan $ GLPKnown gInfo False ov (ListDef []) | not (memberActive membership) && not (memberRemoved membership) = - pure $ CPGroupLink (GLPConnectingProhibit $ Just gInfo) - | memberActive membership = pure $ CPGroupLink (GLPKnown gInfo (BoolDef False) ov (ListDef [])) - | otherwise = pure $ CPGroupLink (GLPOk linkInfo gld ov) + plan $ GLPConnectingProhibit $ Just gInfo + | memberActive membership = plan $ GLPKnown gInfo False ov (ListDef []) + | otherwise = plan $ GLPOk linkInfo gld ov + where + plan p = pure $ CPGroupLink p contactCReqSchemas :: ConnReqUriData -> (ConnReqContact, ConnReqContact) contactCReqSchemas crData = ( CRContactUri crData {crScheme = SSSimplex}, @@ -4665,11 +4813,56 @@ processChatCommand cxt nm = \case gInfo <- withFastStore $ \db -> getGroupInfo db cxt user gId a $ SRGroup gId scope (sendAsGroup' gInfo scope) _ -> throwCmdError "not supported" + preparedGroupFromLink :: User -> CreatedLinkContact -> DirectLink -> GroupShortLinkData -> Maybe SharedMsgId -> Maybe Bool -> CM (GroupInfo, Maybe GroupMember) + preparedGroupFromLink user ccLink direct groupSLinkData welcomeSharedMsgId nameVerified = do + let GroupShortLinkData {groupProfile = gp, publicGroupData = publicGroupData_} = groupSLinkData + publicMemberCount_ = (\PublicGroupData {publicMemberCount} -> publicMemberCount) <$> publicGroupData_ + useRelays = not direct + subRole <- if useRelays then asks $ channelSubscriberRole . config else pure GRMember + gVar <- asks random + withStore $ \db -> createPreparedGroup db gVar cxt user gp False ccLink welcomeSharedMsgId useRelays subRole publicMemberCount_ nameVerified + getSharedMsgId :: CM SharedMsgId getSharedMsgId = do gVar <- asks random liftIO $ SharedMsgId <$> encodedRandomBytes gVar 12 +firstNameLink :: ContactConnType -> [Text] -> Maybe (ConnShortLink 'CMContact) +firstNameLink ctType = foldr (\t r -> nameLink t <|> r) Nothing + where + nameLink t = case strDecode @(ConnShortLink 'CMContact) (encodeUtf8 t) of + Right sl@(CSLContact _ ct _ _) | ct == ctType -> Just sl + _ -> Nothing + +nameResolvesTo :: ConnShortLink 'CMContact -> [Text] -> Bool +nameResolvesTo sLnk = any (either (const False) (sameShortLinkContact sLnk) . strDecode . encodeUtf8) + +verifyEntityDomain :: User -> NetworkRequestMode -> SimplexNameType -> SimplexDomainClaim -> Maybe AConnShortLink -> CM (Maybe Bool, Maybe Text) +verifyEntityDomain user nm nameType SimplexDomainClaim {domain = StrJSON domain, proof = proof_} connLink_ = case (proof_, connLink_) of + (Nothing, _) -> pure (Nothing, Just "no name proof to verify") + (_, Nothing) -> pure (Nothing, Just "no connection link to check the name against") + (Just proof, Just (ACSL SCMContact profileSLnk)) -> do + NameRecord {nrSimplexContact, nrSimplexChannel} <- withAgent $ \a -> resolveSimplexName a nm (aUserId user) domain + let resolvedLinks = case nameType of + NTContact -> nrSimplexContact + NTPublicGroup -> nrSimplexChannel + if not (nameResolvesTo profileSLnk resolvedLinks) + then pure (Just False, Just "the name does not resolve to this address") + else do + ok <- verifyDomainProof proof profileSLnk + pure (Just ok, if ok then Nothing else Just "the name proof was not signed by this address's owner") + (Just _, Just _) -> pure (Nothing, Just "unexpected connection link type for name verification") + where + verifyDomainProof :: SimplexDomainProof -> ShortLinkContact -> CM Bool + verifyDomainProof SimplexDomainProof {linkOwnerId, presHeader, signature} sLnk@(CSLContact _ ct srv key) = do + (FixedLinkData {rootKey}, ContactLinkData _ UserContactData {owners}) <- getShortLinkConnReq nm user sLnk + let ownerKey_ = case linkOwnerId of + Nothing -> Just rootKey + Just (StrJSON oid) -> ownerKey <$> find (\OwnerAuth {ownerId} -> ownerId == oid) owners + pure $ maybe False (\k -> C.verify' k signature proofPayload) ownerKey_ + where + proofPayload = strEncode (Str "simplex_domain_v1", presHeader, domain, ct, srv, key) + data ConnectViaContactResult = CVRConnectedContact Contact | CVRSentInvitation Connection (Maybe Profile) @@ -5146,6 +5339,7 @@ chatCommandP = "/_call status @" *> (APICallStatus <$> A.decimal <* A.space <*> strP), "/_call get" $> APIGetCallInvitations, "/_profile " *> (APIUpdateProfile <$> A.decimal <* A.space <*> jsonP), + "/_set domain " *> (APISetUserDomain <$> A.decimal <*> optional (A.space *> strP)), "/_set alias @" *> (APISetContactAlias <$> A.decimal <*> (A.space *> textP <|> pure "")), "/_set alias #" *> (APISetGroupAlias <$> A.decimal <*> (A.space *> textP <|> pure "")), "/_set alias :" *> (APISetConnectionAlias <$> A.decimal <*> (A.space *> textP <|> pure "")), @@ -5286,6 +5480,7 @@ chatCommandP = "/set welcome " *> char_ '#' *> (UpdateGroupDescription <$> displayNameP <* A.space <*> (Just <$> msgTextP)), "/delete welcome " *> char_ '#' *> (UpdateGroupDescription <$> displayNameP <*> pure Nothing), "/show welcome " *> char_ '#' *> (ShowGroupDescription <$> displayNameP), + "/_public group access #" *> (APISetPublicGroupAccess <$> A.decimal <* A.space <*> jsonP), "/_create link #" *> (APICreateGroupLink <$> A.decimal <*> (memberRole <|> pure GRMember)), "/_set link role #" *> (APIGroupLinkMemberRole <$> A.decimal <*> memberRole), "/_delete link #" *> (APIDeleteGroupLink <$> A.decimal), @@ -5302,9 +5497,9 @@ chatCommandP = (">#" <|> "> #") *> (SendGroupMessageQuote <$> displayNameP <* A.space <* char_ '@' <*> (Just <$> displayNameP) <* A.space <*> quotedMsg <*> msgTextP), "/_contacts " *> (APIListContacts <$> A.decimal), "/contacts" $> ListContacts, - "/_connect plan " *> (APIConnectPlan <$> A.decimal <* A.space <*> ((Just <$> strP) <|> A.takeTill (== ' ') $> Nothing) <*> ((" resolve=" *> onOffP) <|> pure False) <*> optional (" sig=" *> jsonP)), - "/_prepare contact " *> (APIPrepareContact <$> A.decimal <* A.space <*> connLinkP <* A.space <*> jsonP), - "/_prepare group " *> (APIPrepareGroup <$> A.decimal <* A.space <*> connLinkP' <*> (" direct=" *> onOffP <|> pure True) <* A.space <*> jsonP), + "/_connect plan " *> (APIConnectPlan <$> A.decimal <* A.space <*> ((Just <$> strP) <|> A.takeTill (== ' ') $> Nothing) <*> ((" resolve=" *> planResolveModeP) <|> pure PRMUnknown) <*> optional (" sig=" *> jsonP)), + "/_prepare contact " *> (APIPrepareContact <$> A.decimal <* A.space <*> connLinkP <*> optional (" domain=" *> strP) <* A.space <*> jsonP), + "/_prepare group " *> (APIPrepareGroup <$> A.decimal <* A.space <*> connLinkP' <*> (" direct=" *> onOffP <|> pure True) <*> optional (" domain=" *> strP) <* A.space <*> jsonP), "/_set contact user @" *> (APIChangePreparedContactUser <$> A.decimal <* A.space <*> A.decimal), "/_set group user #" *> (APIChangePreparedGroupUser <$> A.decimal <* A.space <*> A.decimal), "/_connect contact @" *> (APIConnectPreparedContact <$> A.decimal <*> incognitoOnOffP <*> optional (A.space *> msgContentP)), @@ -5315,6 +5510,8 @@ chatCommandP = "/_set conn user :" *> (APIChangeConnectionUser <$> A.decimal <* A.space <*> A.decimal), ("/connect" <|> "/c") *> (AddContact <$> incognitoP), ("/connect" <|> "/c") *> (Connect <$> incognitoP <* A.space <*> ((Just <$> strP) <|> A.takeTill isSpace $> Nothing)), + "/_verify domain @" *> (APIVerifyContactDomain <$> A.decimal), + "/_verify domain #" *> (APIVerifyGroupDomain <$> A.decimal), ForwardMessage <$> chatNameP <* " <- @" <*> displayNameP <* A.space <*> msgTextP, ForwardGroupMessage <$> chatNameP <* " <- #" <*> displayNameP <* A.space <* A.char '@' <*> (Just <$> displayNameP) <* A.space <*> msgTextP, ForwardGroupMessage <$> chatNameP <* " <- #" <*> displayNameP <*> pure Nothing <* A.space <*> msgTextP, @@ -5490,10 +5687,10 @@ chatCommandP = onOffP = ("on" $> True) <|> ("off" $> False) publicGroupAccessP = do groupWebPage <- optional (" web=" *> (safeDecodeUtf8 <$> A.takeTill A.isSpace)) - groupDomain <- optional (" domain=" *> (safeDecodeUtf8 <$> A.takeTill A.isSpace)) + groupDomain <- optional (" domain=" *> strP) domainWebPage <- (" domain_page=" *> onOffP) <|> pure False allowEmbedding <- (" embed=" *> onOffP) <|> pure False - pure PublicGroupAccess {groupWebPage, groupDomain, domainWebPage, allowEmbedding} + pure PublicGroupAccess {groupWebPage, groupDomainClaim = mkDomainClaim <$> groupDomain, domainWebPage, allowEmbedding} profileNameDescr = (,) <$> displayNameP <*> shortDescrP -- 'Help with bot':'link ','Menu of commands':[...] botCommandsP :: Parser [ChatBotCommand] @@ -5514,7 +5711,7 @@ chatCommandP = newUserP relay = do (cName, shortDescr) <- profileNameDescr service <- (" service=" *> onOffP) <|> pure False - let profile = Just Profile {displayName = cName, fullName = "", shortDescr, image = Nothing, contactLink = Nothing, peerType = Nothing, preferences = Nothing, badge = Nothing} + let profile = Just Profile {displayName = cName, fullName = "", shortDescr, image = Nothing, contactLink = Nothing, peerType = Nothing, preferences = Nothing, badge = Nothing, contactDomain = Nothing} pure NewUser {profile, pastTimestamp = False, userChatRelay = BoolDef relay, clientService = BoolDef service} newBotUserP = do files_ <- optional $ "files=" *> onOffP <* A.space @@ -5523,7 +5720,7 @@ chatCommandP = let preferences = case files_ of Just True -> Nothing _ -> Just (emptyChatPrefs :: Preferences) {files = Just FilesPreference {allow = FANo}} - profile = Just Profile {displayName = cName, fullName = "", shortDescr, image = Nothing, contactLink = Nothing, peerType = Just CPTBot, preferences, badge = Nothing} + profile = Just Profile {displayName = cName, fullName = "", shortDescr, image = Nothing, contactLink = Nothing, peerType = Just CPTBot, preferences, badge = Nothing, contactDomain = Nothing} pure NewUser {profile, pastTimestamp = False, userChatRelay = BoolDef False, clientService = BoolDef service} jsonP :: J.FromJSON a => Parser a jsonP = J.eitherDecodeStrict' <$?> A.takeByteString @@ -5635,9 +5832,9 @@ chatCommandP = srvRolesP = srvRoles <$?> A.takeTill (\c -> c == ':' || c == ',') where srvRoles = \case - "off" -> Right $ ServerRoles False False - "proxy" -> Right ServerRoles {storage = False, proxy = True} - "storage" -> Right ServerRoles {storage = True, proxy = False} + "off" -> Right $ ServerRoles False False False + "proxy" -> Right ServerRoles {storage = False, proxy = True, names = False} + "storage" -> Right ServerRoles {storage = True, proxy = False, names = False} "on" -> Right allRoles _ -> Left "bad ServerRoles" netCfgP = do diff --git a/src/Simplex/Chat/Library/Internal.hs b/src/Simplex/Chat/Library/Internal.hs index c7f44d125d..c6c7251fc4 100644 --- a/src/Simplex/Chat/Library/Internal.hs +++ b/src/Simplex/Chat/Library/Internal.hs @@ -53,7 +53,8 @@ import Data.Text.Encoding (encodeUtf8) import Data.Time (addUTCTime) import Data.Time.Calendar (fromGregorian) import Data.Time.Clock (UTCTime (..), diffUTCTime, getCurrentTime, nominalDiffTimeToSeconds, secondsToDiffTime) -import Simplex.Chat.Badges (BadgeCredential (..), BadgePresHeader (..), BadgeProof (..), BadgeStatus (..), LocalBadge (..), badgeProof, mkBadgeStatus, verifyBadge) +import Simplex.Chat.Badges (BadgeCredential (..), ProofPresHeader (..), BadgeProof (..), BadgeStatus (..), LocalBadge (..), badgeProof, mkBadgeStatus, verifyBadge) +import Simplex.Chat.Names (SimplexDomainClaim (..), claimDomain) import Simplex.Chat.Call import Simplex.Chat.Controller import Simplex.Chat.Files @@ -928,13 +929,15 @@ acceptContactRequestAsync profileToSend <- presentUserBadge user incognitoProfile $ userProfileDirect user (fromIncognitoProfile <$> incognitoProfile) (Just ct) True cxt <- chatStoreCxt let chatV = vr cxt `peerConnChatVersion` cReqChatVRange - (cmdId, acId) <- agentAcceptContactAsync user True cReqInvId (XInfo profileToSend) subMode cReqPQSup chatV + (cmdId, acId) <- prepareAgentAccept user True cReqInvId cReqPQSup currentTs <- liftIO getCurrentTime - withStore $ \db -> do + ct' <- withStore $ \db -> do forM_ xContactId $ \xcId -> liftIO $ setContactAcceptedXContactId db ct xcId Connection {connId} <- liftIO $ createAcceptedContactConn db user (Just uclId) contactId acId chatV cReqChatVRange cReqPQSup incognitoProfile subMode currentTs liftIO $ setCommandConnId db user cmdId connId getContact db cxt user contactId + agentAcceptContactAsync cmdId acId True cReqInvId (XInfo profileToSend) cReqPQSup chatV subMode + pure ct' acceptGroupJoinRequestAsync :: User -> Int64 -> GroupInfo -> InvitationId -> VersionRangeChat -> Profile -> Maybe XContactId -> Maybe MemberId -> Maybe SharedMsgId -> GroupAcceptance -> GroupMemberRole -> Maybe IncognitoProfile -> Maybe MemberKey -> Maybe GroupMember -> CM GroupMember acceptGroupJoinRequestAsync @@ -982,10 +985,12 @@ acceptGroupJoinRequestAsync } subMode <- chatReadVar subscriptionMode let chatV = vr cxt `peerConnChatVersion` cReqChatVRange - connIds <- agentAcceptContactAsync user True cReqInvId msg subMode PQSupportOff chatV - withStore $ \db -> do - liftIO $ createJoiningMemberConnection db user uclId connIds chatV cReqChatVRange groupMemberId subMode + (cmdId, acId) <- prepareAgentAccept user True cReqInvId PQSupportOff + m <- withStore $ \db -> do + liftIO $ createJoiningMemberConnection db user uclId (cmdId, acId) chatV cReqChatVRange groupMemberId subMode getGroupMemberById db cxt user groupMemberId + agentAcceptContactAsync cmdId acId True cReqInvId msg PQSupportOff chatV subMode + pure m acceptGroupJoinSendRejectAsync :: User -> Int64 -> GroupInfo -> InvitationId -> VersionRangeChat -> Profile -> Maybe XContactId -> GroupRejectionReason -> CM GroupMember acceptGroupJoinSendRejectAsync @@ -1012,10 +1017,12 @@ acceptGroupJoinSendRejectAsync } subMode <- chatReadVar subscriptionMode let chatV = vr cxt `peerConnChatVersion` cReqChatVRange - connIds <- agentAcceptContactAsync user False cReqInvId msg subMode PQSupportOff chatV - withStore $ \db -> do - liftIO $ createJoiningMemberConnection db user uclId connIds chatV cReqChatVRange groupMemberId subMode + (cmdId, acId) <- prepareAgentAccept user False cReqInvId PQSupportOff + m <- withStore $ \db -> do + liftIO $ createJoiningMemberConnection db user uclId (cmdId, acId) chatV cReqChatVRange groupMemberId subMode getGroupMemberById db cxt user groupMemberId + agentAcceptContactAsync cmdId acId False cReqInvId msg PQSupportOff chatV subMode + pure m acceptBusinessJoinRequestAsync :: User -> Int64 -> GroupInfo -> GroupMember -> UserContactRequest -> CM (GroupInfo, GroupMember) acceptBusinessJoinRequestAsync @@ -1044,10 +1051,11 @@ acceptBusinessJoinRequestAsync } subMode <- chatReadVar subscriptionMode let chatV = vr cxt `peerConnChatVersion` cReqChatVRange - connIds <- agentAcceptContactAsync user True cReqInvId msg subMode PQSupportOff chatV + (cmdId, acId) <- prepareAgentAccept user True cReqInvId PQSupportOff withStore' $ \db -> do forM_ xContactId $ \xcId -> setBusinessChatAcceptedXContactId db gInfo xcId - createJoiningMemberConnection db user uclId connIds chatV cReqChatVRange groupMemberId subMode + createJoiningMemberConnection db user uclId (cmdId, acId) chatV cReqChatVRange groupMemberId subMode + agentAcceptContactAsync cmdId acId True cReqInvId msg PQSupportOff chatV subMode let cd = CDGroupSnd gInfo Nothing -- TODO [short links] move to profileContactRequest? createInternalChatItem user cd (CISndGroupE2EEInfo $ e2eInfoGroup gInfo) Nothing @@ -1070,12 +1078,14 @@ acceptRelayJoinRequestAsync subMode <- chatReadVar subscriptionMode cxt <- chatStoreCxt let chatV = vr cxt `peerConnChatVersion` cReqChatVRange - connIds <- agentAcceptContactAsync user True cReqInvId msg subMode PQSupportOff chatV - withStore $ \db -> do - liftIO $ createJoiningMemberConnection db user uclId connIds chatV cReqChatVRange groupMemberId subMode + (cmdId, acId) <- prepareAgentAccept user True cReqInvId PQSupportOff + r <- withStore $ \db -> do + liftIO $ createJoiningMemberConnection db user uclId (cmdId, acId) chatV cReqChatVRange groupMemberId subMode gInfo' <- liftIO $ updateRelayOwnStatusFromTo db gInfo RSInvited RSAccepted ownerMember' <- getGroupMemberById db cxt user groupMemberId pure (gInfo', ownerMember') + agentAcceptContactAsync cmdId acId True cReqInvId msg PQSupportOff chatV subMode + pure r rejectRelayInvitationAsync :: User @@ -1095,9 +1105,10 @@ rejectRelayInvitationAsync user uclId cxt groupRelayInv invId reqChatVRange init subMode <- chatReadVar subscriptionMode chatVR <- chatVersionRange let chatV = chatVR `peerConnChatVersion` reqChatVRange - connIds <- agentAcceptContactAsync user False invId msg subMode PQSupportOff chatV + (cmdId, acId) <- prepareAgentAccept user False invId PQSupportOff withStore' $ \db -> - createJoiningMemberConnection db user uclId connIds chatV reqChatVRange groupMemberId subMode + createJoiningMemberConnection db user uclId (cmdId, acId) chatV reqChatVRange groupMemberId subMode + agentAcceptContactAsync cmdId acId False invId msg PQSupportOff chatV subMode businessGroupProfile :: Profile -> GroupPreferences -> GroupProfile businessGroupProfile Profile {displayName, fullName, shortDescr, image} groupPreferences = @@ -1186,8 +1197,8 @@ serveRoster :: User -> GroupInfo -> GroupMember -> CM () serveRoster user gInfo member = when (member `supportsVersion` groupRosterVersion) $ do cxt <- chatStoreCxt - withStore' (\db -> getGroupRoster db gInfo) >>= \case - Just (ownerGMId, brokerTs, sm@SignedMsg {signedBody}, blob_) -> + withStore' (\db -> getStoredGroupRoster db gInfo) >>= \case + Just (ownerGMId, brokerTs, sm@SignedMsg {signedBody}, blob_, storedVer_) -> case J.eitherDecodeStrict' signedBody :: Either String (ChatMessage 'Json) of Left e -> logError $ "serveRoster: cannot decode saved roster message: " <> tshow e Right chatMsg@ChatMessage {msgId} -> @@ -1197,6 +1208,10 @@ serveRoster user gInfo member = sendFwdMemberMessage member fwd (VMSigned MSSVerified sm chatMsg) forM_ ((,) <$> msgId <*> blob_) $ \(sid, blob) -> sendInlineBlobChunks user gInfo [member] sid blob + -- record the blob's own stored version as served, not roster_version (the gate): a delta can + -- advance the gate past the stored blob on a failed blob send, and recording the gate would + -- over-claim what this member was actually served, suppressing legitimate catch-up + forM_ storedVer_ $ \v -> withStore' $ \db -> setMemberRosterServedVersion db member v Left e -> logError $ "serveRoster: roster owner not found: " <> tshow e Nothing -> pure () @@ -1223,13 +1238,14 @@ introduceInChannel cxt user gInfo subscriber@GroupMember {activeConn = Just conn sendGroupMemberMessages user gInfo conn evts userProfileInGroup :: User -> GroupInfo -> Maybe Profile -> Profile -userProfileInGroup user = userProfileInGroup' user . groupUserAllowSimplexLinks +userProfileInGroup user g = userProfileInGroup' user (Just g) {-# INLINE userProfileInGroup #-} -userProfileInGroup' :: User -> Bool -> Maybe Profile -> Profile -userProfileInGroup' User {profile = p} allowSimplexLinks incognitoProfile = +-- Nothing group ⇒ no redaction (e.g. joining via a link with no group profile yet). +userProfileInGroup' :: User -> Maybe GroupInfo -> Maybe Profile -> Profile +userProfileInGroup' User {profile = p} mg incognitoProfile = let p' = fromMaybe (fromLocalProfile p) incognitoProfile - in redactedMemberProfile allowSimplexLinks p' + in maybe p' (\g -> redactedMemberProfile g (membership g) p') mg memberInfo :: GroupInfo -> GroupMember -> MemberInfo memberInfo g m@GroupMember {memberId, memberRole, memberProfile, memberPubKey, activeConn} = @@ -1237,16 +1253,18 @@ memberInfo g m@GroupMember {memberId, memberRole, memberProfile, memberPubKey, a { memberId, memberRole, v = ChatVersionRange . peerChatVRange <$> activeConn, - profile = redactedMemberProfile allowSimplexLinks $ fromLocalProfile memberProfile, + profile = redactedMemberProfile g m $ fromLocalProfile memberProfile, memberKey = MemberKey <$> memberPubKey } - where - allowSimplexLinks = groupFeatureMemberAllowed SGFSimplexLinks m g && groupFeatureMemberAllowed SGFDirectMessages m g -redactedMemberProfile :: Bool -> Profile -> Profile -redactedMemberProfile allowSimplexLinks Profile {displayName, fullName, shortDescr, image, peerType, badge} = - Profile {displayName, fullName, shortDescr = removeSimplexLink =<< shortDescr, image, contactLink = Nothing, preferences = Nothing, peerType, badge} +redactedMemberProfile :: GroupInfo -> GroupMember -> Profile -> Profile +redactedMemberProfile g m Profile {displayName, fullName, shortDescr, image, contactLink = lnk, peerType, badge, contactDomain} = + Profile {displayName, fullName, shortDescr = removeSimplexLink =<< shortDescr, image, contactLink, preferences = Nothing, peerType, badge, contactDomain = redactedDomain} where + contactLink = if allowSimplexLinks then lnk else Nothing + redactedDomain = if allowDirect then (\d -> d {proof = Nothing} :: SimplexDomainClaim) <$> contactDomain else Nothing + allowDirect = groupFeatureMemberAllowed SGFDirectMessages m g + allowSimplexLinks = groupFeatureMemberAllowed SGFSimplexLinks m g && allowDirect removeSimplexLink s | allowSimplexLinks = Just s | hasObfuscatedSimplexLink s = Nothing @@ -1446,8 +1464,8 @@ updatePublicGroupData user gInfo | otherwise = pure gInfo updateGroupFromLinkData :: User -> GroupInfo -> GroupShortLinkData -> CM (GroupInfo, Bool) -updateGroupFromLinkData user gInfo@GroupInfo {groupProfile = p, groupSummary = GroupSummary {publicMemberCount = localCount}} GroupShortLinkData {groupProfile, publicGroupData} - | profileChanged || countChanged = do +updateGroupFromLinkData user gInfo@GroupInfo {groupProfile = p, groupDomainVerified, groupSummary = GroupSummary {publicMemberCount = localCount}} GroupShortLinkData {groupProfile, publicGroupData} + | profileChanged || countChanged || verifyChanged = do cxt <- chatStoreCxt withStore $ \db -> do g <- if profileChanged then updateGroupProfile db user gInfo groupProfile else pure gInfo @@ -1455,13 +1473,32 @@ updateGroupFromLinkData user gInfo@GroupInfo {groupProfile = p, groupSummary = G Just PublicGroupData {publicMemberCount} | countChanged -> setPublicMemberCount db cxt user g publicMemberCount _ -> pure g - pure (g', profileChanged) + -- the group's own link is authoritative for its domain claim, so a claim in the link profile is + -- verified; updateGroupProfile above clears verification on a claim change, so set it afterwards + g'' <- if verifyChanged then liftIO $ setGroupDomainVerified db user g' True else pure g' + pure (g'', profileChanged) | otherwise = pure (gInfo, False) where profileChanged = p /= groupProfile countChanged = case publicGroupData of Just PublicGroupData {publicMemberCount} -> Just publicMemberCount /= localCount _ -> False + groupClaim GroupProfile {publicGroup} = claimDomain <$> (publicGroup >>= publicGroupAccess >>= groupDomainClaim) + newClaim = groupClaim groupProfile + verifyChanged = isJust newClaim && (groupDomainVerified /= Just True || groupClaim p /= newClaim) + +updateContactFromLinkData :: User -> Contact -> Profile -> CM Contact +updateContactFromLinkData user ct@Contact {profile = profile@LocalProfile {contactDomain = prevClaim, contactDomainVerified}} linkProfile@Profile {contactDomain = newClaim} + | profileChanged || verifyChanged = do + cxt <- chatStoreCxt + withFastStore $ \db -> do + ct' <- updateContactProfile db cxt user ct linkProfile + if verifyChanged then liftIO $ setContactDomainVerified db user ct' True else pure ct' + | otherwise = pure ct + where + profileChanged = fromLocalProfile profile /= linkProfile + claimChanged = (claimDomain <$> prevClaim) /= (claimDomain <$> newClaim) + verifyChanged = contactDomainVerified /= Just True || claimChanged -- TODO [relays] owner: set owners on updating link data (multi-owner) groupLinkData :: GroupInfo -> GroupLink -> [GroupRelay] -> (UserConnLinkData 'CMContact, CRClientData) @@ -2050,6 +2087,7 @@ presentUserBadge User {profile = LocalProfile {localBadge}} incognitoProfile p = Left e -> p <$ logError ("presentUserBadge: proof generation failed: " <> T.pack e) _ -> pure p + -- receiving side of contact/invitation link data: verify the badge proof from the link profile -- and set the crypto-free display badge for the UI (the raw proof stays in profile for APIPrepareContact) linkDataBadge :: ContactShortLinkData -> CM ContactShortLinkData @@ -2267,24 +2305,39 @@ sendGroupMessage' user gInfo members chatMsgEvent = ((Right msg) :| [], _) -> pure msg _ -> throwChatError $ CEInternalError "sendGroupMessage': expected 1 message" +-- The roster change being broadcast, projected onto the current roster members in broadcastRoster. This lets the +-- roster blob be built (and sent) before the change is applied to the owner's own member records, so the owner +-- never demotes/removes a member locally before the change has been propagated to relays. +data RosterDelta + = RDRoleChanged GroupMemberRole [GroupMember] -- these members now hold this role + | RDRemoved [GroupMember] -- these members are removed from the group + +applyRosterDelta :: RosterDelta -> [GroupMember] -> [GroupMember] +applyRosterDelta delta current = case delta of + RDRoleChanged role changed -> map (\m -> (m :: GroupMember) {memberRole = role}) changed <> without changed + RDRemoved removed -> without removed + where + without ms = let ids = S.fromList (map groupMemberId' ms) in filter ((`S.notMember` ids) . groupMemberId') current + -- TODO [relays] improvement: publish roster_version in link data so the owner can recover the latest version -- TODO after restoring from a stale backup (relays accept only strictly-greater versions) --- Persist the next roster version before sending the events that carry it (so a recipient never advances --- past a version the owner hasn't recorded). The matching blob is broadcast separately, by broadcastRoster, --- after the change is applied to the owner's members - so the served roster excludes demoted/removed members. -reserveRosterVersion :: GroupInfo -> CM VersionRoster -reserveRosterVersion gInfo = do +-- Reserve and persist the next roster version (committed before the events that carry it, so a recipient never +-- advances past a version the owner hasn't recorded), then broadcast the matching blob with the change projected +-- onto the served roster (so it excludes demoted/removed members). Returns the reserved version for the delta +-- that follows. The blob send is best-effort - a failed send heals on the next change or on resume. +broadcastRoster :: User -> GroupInfo -> RosterDelta -> CM VersionRoster +broadcastRoster user gInfo delta = do let rosterVer = maybe (VersionRoster 0) (\(VersionRoster n) -> VersionRoster (n + 1)) (rosterVersion gInfo) withStore' $ \db -> setGroupRosterVersion db gInfo rosterVer + sendRosterBlob rosterVer `catchAllErrors` eToView pure rosterVer - -broadcastRoster :: User -> GroupInfo -> VersionRoster -> CM () -broadcastRoster user gInfo rosterVer = do - cxt <- chatStoreCxt - (relays, rosterMems) <- withStore' $ \db -> - (,) <$> getGroupRelayMembers db cxt user gInfo <*> getGroupRosterMembers db cxt user gInfo - forM_ (L.nonEmpty relays) $ \relays' -> - sendRoster user gInfo (L.toList relays') rosterVer (buildGroupRoster rosterMems) + where + sendRosterBlob rosterVer = do + cxt <- chatStoreCxt + (relays, rosterMems) <- withStore' $ \db -> + (,) <$> getGroupRelayMembers db cxt user gInfo <*> getGroupRosterMembers db cxt user gInfo + forM_ (L.nonEmpty relays) $ \relays' -> + sendRoster user gInfo (L.toList relays') rosterVer (buildGroupRoster $ applyRosterDelta delta rosterMems) -- Send the current roster (no version bump) to a newly added relay so it can serve joiners. sendGroupRosterToRelay :: User -> GroupInfo -> GroupMember -> CM () @@ -2349,9 +2402,8 @@ sendGroupMessages user gInfo scope asGroup members events = do _ -> False sendProfileUpdate = do let members' = filter (`supportsVersion` memberProfileUpdateVersion) members - allowSimplexLinks = groupUserAllowSimplexLinks gInfo -- shouldSendProfileUpdate excludes incognito membership, so the badge is presented - profileUpdate <- presentUserBadge user Nothing $ redactedMemberProfile allowSimplexLinks $ fromLocalProfile p + profileUpdate <- presentUserBadge user Nothing $ redactedMemberProfile gInfo (membership gInfo) $ fromLocalProfile p void $ sendGroupMessage' user gInfo members' $ XInfo profileUpdate currentTs <- liftIO getCurrentTime withStore' $ \db -> updateUserMemberProfileSentAt db user gInfo currentTs @@ -2716,18 +2768,24 @@ msgContentHasLink mc ft_ = case msgContentTag mc of MCLink_ -> True _ -> maybe False hasLinks ft_ -createAgentConnectionAsync :: ConnectionModeI c => User -> CommandFunction -> Bool -> SConnectionMode c -> SubscriptionMode -> CM (CommandId, ConnId) -createAgentConnectionAsync user cmdFunction enableNtfs cMode subMode = do +prepareAgentCreation :: ConnectionModeI c => User -> CommandFunction -> Bool -> SConnectionMode c -> CM (CommandId, ConnId) +prepareAgentCreation user cmdFunction enableNtfs cMode = do cmdId <- withStore' $ \db -> createCommand db user Nothing cmdFunction - connId <- withAgent $ \a -> createConnectionAsync a (aUserId user) (aCorrId cmdId) enableNtfs cMode IKPQOff subMode + connId <- withAgent $ \a -> prepareConnectionToCreate a (aUserId user) enableNtfs cMode PQSupportOff pure (cmdId, connId) -joinAgentConnectionAsync :: User -> Maybe Connection -> Bool -> ConnectionRequestUri c -> ConnInfo -> SubscriptionMode -> CM (CommandId, ConnId) -joinAgentConnectionAsync user conn_ enableNtfs cReqUri cInfo subMode = do +prepareAgentJoin :: User -> Maybe Connection -> Bool -> ConnectionRequestUri c -> CM (CommandId, ConnId) +prepareAgentJoin user conn_ enableNtfs cReqUri = do cmdId <- withStore' $ \db -> createCommand db user (dbConnId <$> conn_) CFJoinConn - connId <- withAgent $ \a -> joinConnectionAsync a (aUserId user) (aCorrId cmdId) (aConnId <$> conn_) enableNtfs cReqUri cInfo PQSupportOff subMode + connId <- case conn_ of + Just conn -> pure $ aConnId conn + Nothing -> withAgent $ \a -> prepareConnectionToJoin a (aUserId user) enableNtfs cReqUri PQSupportOff pure (cmdId, connId) +joinAgentConnectionAsync :: ConnectionModeI c => CommandId -> Bool -> ConnId -> Bool -> ConnectionRequestUri c -> ConnInfo -> SubscriptionMode -> CM () +joinAgentConnectionAsync cmdId updateConn connId enableNtfs cReqUri cInfo subMode = + withAgent $ \a -> joinConnectionAsync a (aCorrId cmdId) updateConn connId enableNtfs cReqUri cInfo PQSupportOff subMode + allowAgentConnectionAsync :: MsgEncodingI e => User -> Connection -> ConfirmationId -> ChatMsgEvent e -> CM () allowAgentConnectionAsync user conn@Connection {connId, pqSupport, connChatVersion} confId msg = do cmdId <- withStore' $ \db -> createCommand db user (Just connId) CFAllowConn @@ -2735,13 +2793,17 @@ allowAgentConnectionAsync user conn@Connection {connId, pqSupport, connChatVersi withAgent $ \a -> allowConnectionAsync a (aCorrId cmdId) (aConnId conn) confId dm withStore' $ \db -> updateConnectionStatus db conn ConnAccepted -agentAcceptContactAsync :: MsgEncodingI e => User -> Bool -> InvitationId -> ChatMsgEvent e -> SubscriptionMode -> PQSupport -> VersionChat -> CM (CommandId, ConnId) -agentAcceptContactAsync user enableNtfs invId msg subMode pqSup chatV = do +prepareAgentAccept :: User -> Bool -> InvitationId -> PQSupport -> CM (CommandId, ConnId) +prepareAgentAccept user enableNtfs invId pqSup = do cmdId <- withStore' $ \db -> createCommand db user Nothing CFAcceptContact - dm <- encodeConnInfoPQ pqSup chatV msg - connId <- withAgent $ \a -> acceptContactAsync a (aUserId user) (aCorrId cmdId) enableNtfs invId dm pqSup subMode + connId <- withAgent $ \a -> prepareConnectionToAccept a (aUserId user) enableNtfs invId pqSup pure (cmdId, connId) +agentAcceptContactAsync :: MsgEncodingI e => CommandId -> ConnId -> Bool -> InvitationId -> ChatMsgEvent e -> PQSupport -> VersionChat -> SubscriptionMode -> CM () +agentAcceptContactAsync cmdId connId enableNtfs invId msg pqSup chatV subMode = do + dm <- encodeConnInfoPQ pqSup chatV msg + withAgent $ \a -> acceptContactAsync a (aCorrId cmdId) connId enableNtfs invId dm pqSup subMode + deleteAgentConnectionAsync :: ConnId -> CM () deleteAgentConnectionAsync acId = deleteAgentConnectionAsync' acId False {-# INLINE deleteAgentConnectionAsync #-} @@ -3091,7 +3153,8 @@ simplexTeamContactProfile = contactLink = Just $ CLFull adminContactReq, peerType = Nothing, preferences = Nothing, - badge = Nothing + badge = Nothing, + contactDomain = Nothing } simplexStatusContactProfile :: Profile @@ -3104,7 +3167,8 @@ simplexStatusContactProfile = contactLink = Just (either error CLFull $ strDecode "simplex:/contact/#/?v=1-2&smp=smp%3A%2F%2Fu2dS9sG8nMNURyZwqASV4yROM28Er0luVTx5X1CsMrU%3D%40smp4.simplex.im%2FShQuD-rPokbDvkyotKx5NwM8P3oUXHxA%23%2F%3Fv%3D1-2%26dh%3DMCowBQYDK2VuAyEA6fSx1k9zrOmF0BJpCaTarZvnZpMTAVQhd3RkDQ35KT0%253D%26srv%3Do5vmywmrnaxalvz6wi3zicyftgio6psuvyniis6gco6bp6ekl4cqj4id.onion"), peerType = Just CPTBot, preferences = Nothing, - badge = Nothing + badge = Nothing, + contactDomain = Nothing } timeItToView :: String -> CM' a -> CM' a diff --git a/src/Simplex/Chat/Library/Subscriber.hs b/src/Simplex/Chat/Library/Subscriber.hs index c964df2b3d..52d70f1fae 100644 --- a/src/Simplex/Chat/Library/Subscriber.hs +++ b/src/Simplex/Chat/Library/Subscriber.hs @@ -381,8 +381,6 @@ processAgentMessageConn :: StoreCxt -> User -> ACorrId -> ConnId -> AEvent 'AECo processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = do -- Missing connection/entity errors here will be sent to the view but not shown as CRITICAL alert, -- as in this case no need to ACK message - we can't process messages for this connection anyway. - -- SEDBException will be re-trown as CRITICAL as it is likely to indicate a temporary database condition - -- that will be resolved with app restart. entity <- critical agentConnId $ withStore (\db -> getConnectionEntity db cxt user $ AgentConnId agentConnId) >>= updateConnStatus case agentMessage of END -> case entity of @@ -641,9 +639,10 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = forM_ gli_ $ \GroupLinkInfo {groupId, memberRole = gLinkMemRole} -> do groupInfo <- withStore $ \db -> getGroupInfo db cxt user groupId subMode <- chatReadVar subscriptionMode - groupConnIds <- createAgentConnectionAsync user CFCreateConnGrpInv True SCMInvitation subMode + groupConnIds@(cmdId, connId) <- prepareAgentCreation user CFCreateConnGrpInv True SCMInvitation gVar <- asks random withStore $ \db -> createNewContactMemberAsync db gVar user groupInfo ct' gLinkMemRole groupConnIds connChatVersion peerChatVRange subMode + withAgent $ \a -> createConnectionAsync a (aCorrId cmdId) connId True SCMInvitation CR.IKPQOff subMode -- TODO REMOVE LEGACY ^^^ SENT msgId proxy -> do void $ continueSending connEntity conn @@ -838,8 +837,7 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = XGrpMemInfo memId _memProfile | sameMemberId memId m -> do let GroupMember {memberId = membershipMemId} = membership - allowSimplexLinks = groupUserAllowSimplexLinks gInfo - membershipProfile <- presentUserBadge user (incognitoMembershipProfile gInfo) $ redactedMemberProfile allowSimplexLinks $ fromLocalProfile $ memberProfile membership + membershipProfile <- presentUserBadge user (incognitoMembershipProfile gInfo) $ redactedMemberProfile gInfo membership $ fromLocalProfile $ memberProfile membership -- TODO update member profile -- [async agent commands] no continuation needed, but command should be asynchronous for stability allowAgentConnectionAsync user conn' confId $ XGrpMemInfo membershipMemId membershipProfile @@ -1089,11 +1087,11 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = XGrpMemIntro memInfo memRestrictions_ -> Nothing <$ xGrpMemIntro gInfo' m'' memInfo memRestrictions_ XGrpMemInv memId introInv -> Nothing <$ xGrpMemInv gInfo' m'' memId introInv XGrpMemFwd memInfo introInv -> Nothing <$ xGrpMemFwd gInfo' m'' memInfo introInv - XGrpMemRole memId memRole memberKey rosterVer -> fmap ctx <$> xGrpMemRole gInfo' m'' memId memRole memberKey rosterVer msg brokerTs + XGrpMemRole memId memRole memberKey rosterVer -> fmap ctx <$> xGrpMemRole gInfo' Nothing m'' memId memRole memberKey rosterVer msg brokerTs XGrpMemRestrict memId memRestrictions -> fmap ctx <$> xGrpMemRestrict gInfo' m'' memId memRestrictions msg brokerTs XGrpMemCon memId -> Nothing <$ xGrpMemCon gInfo' m'' memId XGrpMemDel memId withMessages rosterVer -> case encoding @e of - SJson -> fmap ctx <$> xGrpMemDel gInfo' m'' memId withMessages rosterVer verifiedMsg msg brokerTs False + SJson -> fmap ctx <$> xGrpMemDel gInfo' Nothing m'' memId withMessages rosterVer verifiedMsg msg brokerTs False SBinary -> pure Nothing XGrpLeave -> fmap ctx <$> xGrpLeave gInfo' m'' msg brokerTs XGrpDel -> Just (DeliveryTaskContext (DJSGroup {jobSpec = DJRelayRemoved}) False) <$ xGrpDel gInfo' m'' msg brokerTs @@ -1101,6 +1099,7 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = XGrpPrefs ps' -> fmap ctx <$> xGrpPrefs gInfo' m'' ps' msg XGrpRoster gr -> fmap ctx <$> xGrpRoster gInfo' m'' m'' gr verifiedMsg sharedMsgId_ brokerTs XGrpRosterAck ackVer ackErr -> Nothing <$ xGrpRosterAck gInfo' m'' ackVer ackErr + XGrpRosterRequest reqVer -> Nothing <$ xGrpRosterRequest gInfo' m'' reqVer -- TODO [knocking] why don't we forward these messages? XGrpDirectInv connReq mContent_ msgScope -> memberCanSend (Just m'') msgScope $ Nothing <$ xGrpDirectInv gInfo' m'' conn' connReq mContent_ msg brokerTs XGrpMsgForward fwd msg' -> Nothing <$ xGrpMsgForward gInfo' Nothing m'' fwd (ParsedMsg Nothing Nothing msg') brokerTs @@ -1244,7 +1243,8 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = profileToSend <- presentUserBadge user incognitoProfile $ userProfileInGroup user gInfo incognitoProfile dm <- encodeXMemberConnInfo gInfo relayMemberId profileToSend subMode <- chatReadVar subscriptionMode - void $ joinAgentConnectionAsync user (Just conn) True cReq dm subMode + (cmdId, connId') <- prepareAgentJoin user (Just conn) True cReq + joinAgentConnectionAsync cmdId True connId' True cReq dm subMode CFGetRelayDataAccept -> do let GroupMember {memberId = MemberId expectedMemberId} = m if linkEntityId == Just expectedMemberId @@ -1400,13 +1400,13 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = CFSetShortLink -> case (ucGroupId_, auData) of (Just groupId, UserContactLinkData UserContactData {relays = relayLinks}) -> do - (gInfo, gLink, relays, relaysChanged, newlyActiveLinks, newlyActiveGMIds) <- withStore $ \db -> do + (gInfo, gLink, relays, relaysChanged, newlyActiveLinks) <- withStore $ \db -> do gInfo <- getGroupInfo db cxt user groupId gLink <- getGroupLink db user gInfo relays <- liftIO $ getGroupRelays db gInfo - (relays', changed, newlyActiveLinks, newlyActiveGMIds) <- liftIO $ foldrM (updateRelay db) ([], False, [], []) relays + (relays', changed, newlyActiveLinks) <- liftIO $ foldrM (updateRelay db) ([], False, []) relays liftIO $ setGroupInProgressDone db gInfo - pure (gInfo, gLink, relays', changed, newlyActiveLinks, newlyActiveGMIds) + pure (gInfo, gLink, relays', changed, newlyActiveLinks) toView $ CEvtGroupLinkDataUpdated user gInfo gLink relays relaysChanged let GroupSummary {publicMemberCount} = groupSummary gInfo -- Owner is counted in publicMemberCount; > 1 means at least one subscriber. @@ -1424,16 +1424,16 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = unless (null recipients) $ void $ sendGroupMessages user gInfo Nothing False recipients events where - updateRelay :: DB.Connection -> GroupRelay -> ([GroupRelay], Bool, [ShortLinkContact], [GroupMemberId]) -> IO ([GroupRelay], Bool, [ShortLinkContact], [GroupMemberId]) - updateRelay db relay@GroupRelay {groupMemberId, relayLink, relayStatus} (acc, changed, newlyActiveLinks, newlyActiveGMIds) = + updateRelay :: DB.Connection -> GroupRelay -> ([GroupRelay], Bool, [ShortLinkContact]) -> IO ([GroupRelay], Bool, [ShortLinkContact]) + updateRelay db relay@GroupRelay {relayLink, relayStatus} (acc, changed, newlyActiveLinks) = case relayLink of Just rLink -- version is gated upstream at publish (getPublishableGroupRelays): an RSAccepted relay -- whose link is in the published data is necessarily pre-roster, so activate it too | rLink `elem` relayLinks && (relayStatus == RSAcknowledgedRoster || relayStatus == RSAccepted) -> do relay' <- updateRelayStatus db relay RSActive - pure (relay' : acc, True, rLink : newlyActiveLinks, groupMemberId : newlyActiveGMIds) - | rLink `elem` relayLinks -> pure (relay : acc, changed, newlyActiveLinks, newlyActiveGMIds) + pure (relay' : acc, True, rLink : newlyActiveLinks) + | rLink `elem` relayLinks -> pure (relay : acc, changed, newlyActiveLinks) | relayStatus == RSActive -> do -- Relay link absent from link data — deactivate. -- RSAccepted relays are not deactivated: their own link data update @@ -1442,8 +1442,8 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = -- TODO the SMP server, but this owner won't receive a LINK callback for it -- TODO (LINK only fires in response to own setConnShortLink calls). relay' <- updateRelayStatus db relay RSInactive - pure (relay' : acc, True, newlyActiveLinks, newlyActiveGMIds) - _ -> pure (relay : acc, changed, newlyActiveLinks, newlyActiveGMIds) + pure (relay' : acc, True, newlyActiveLinks) + _ -> pure (relay : acc, changed, newlyActiveLinks) _ -> throwChatError $ CECommandError "LINK event expected for a group link only" _ -> throwChatError $ CECommandError "unexpected cmdFunction" MERR _ err -> do @@ -1641,12 +1641,12 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = let sig = C.signatureBytes $ C.sign' privKey challenge msg = XGrpRelayTest challenge (Just sig) subMode <- chatReadVar subscriptionMode - chatVR <- chatVersionRange - let chatV = chatVR `peerConnChatVersion` chatVRange - (cmdId, acId) <- agentAcceptContactAsync user True invId msg subMode PQSupportOff chatV + let chatV = vr cxt `peerConnChatVersion` chatVRange + (cmdId, acId) <- prepareAgentAccept user True invId PQSupportOff withStore $ \db -> do Connection {connId = testCId} <- createRelayTestConnection db cxt user acId ConnAccepted chatV subMode liftIO $ setCommandConnId db user cmdId testCId + agentAcceptContactAsync cmdId acId True invId msg PQSupportOff chatV subMode | otherwise = messageError "relay test sent to non-relay link" where User {userChatRelay} = user @@ -2612,12 +2612,13 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = then do subMode <- chatReadVar subscriptionMode dm <- encodeConnInfo $ XGrpAcpt membershipMemId - connIds <- joinAgentConnectionAsync user Nothing True connRequest dm subMode + connIds@(cmdId, acId) <- prepareAgentJoin user Nothing True connRequest withStore' $ \db -> do setViaGroupLinkUri db groupId connId createMemberConnectionAsync db user hostId connIds connChatVersion peerChatVRange subMode updateGroupMemberStatusById db userId hostId GSMemAccepted updateGroupMemberStatus db userId membership GSMemAccepted + joinAgentConnectionAsync cmdId False acId True connRequest dm subMode toView $ CEvtUserAcceptedGroupSent user gInfo {membership = membership {memberStatus = GSMemAccepted}} (Just ct) else do let content = CIRcvGroupInvitation (CIGroupInvitation {groupId, groupMemberId, localDisplayName, groupProfile, status = CIGISPending}) memRole @@ -2812,8 +2813,7 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = | otherwise = pure m where - contentChanged = not (sameProfileContent (redactedMemberProfile allowSimplexLinks (fromLocalProfile p)) (redactedMemberProfile allowSimplexLinks p')) - allowSimplexLinks = groupFeatureMemberAllowed SGFSimplexLinks m gInfo && groupFeatureMemberAllowed SGFDirectMessages m gInfo + contentChanged = not (sameProfileContent (redactedMemberProfile gInfo m (fromLocalProfile p)) (redactedMemberProfile gInfo m p')) updateBusinessChatProfile g@GroupInfo {businessChat} = case businessChat of Just bc | isMainBusinessMember bc m -> do g' <- withStore $ \db -> updateGroupProfileFromMember db user g p' @@ -3179,16 +3179,14 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = Just (ChatVersionRange mcvr) | maxVersion mcvr >= groupDirectInvVersion -> do subMode <- chatReadVar subscriptionMode - -- [async agent commands] commands should be asynchronous, continuation is to send XGrpMemInv - have to remember one has completed and process on second - groupConnIds <- createConn subMode + groupConnIds@(cmdId, connId) <- prepareAgentCreation user CFCreateConnGrpMemInv (chatHasNtfs chatSettings) SCMInvitation let chatV = maybe (minVersion (vr cxt)) (\peerVR -> vr cxt `peerConnChatVersion` fromChatVRange peerVR) memChatVRange void $ withStore $ \db -> do reMember <- createIntroReMember db cxt user gInfo memInfo memRestrictions createIntroReMemberConn db user m reMember chatV memInfo groupConnIds subMode + withAgent $ \a -> createConnectionAsync a (aCorrId cmdId) connId (chatHasNtfs chatSettings) SCMInvitation CR.IKPQOff subMode | otherwise -> messageError "x.grp.mem.intro: member chat version range incompatible" _ -> messageError "x.grp.mem.intro can be only sent by host member" - where - createConn subMode = createAgentConnectionAsync user CFCreateConnGrpMemInv (chatHasNtfs chatSettings) SCMInvitation subMode sendXGrpMemInv :: Int64 -> Maybe ConnReqInvitation -> XGrpMemIntroCont -> CM () sendXGrpMemInv hostConnId directConnReq XGrpMemIntroCont {groupId, groupMemberId, memberId, groupConnReq} = do @@ -3228,45 +3226,76 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = pure toMember subMode <- chatReadVar subscriptionMode -- [incognito] send membership incognito profile, create direct connection as incognito - let allowSimplexLinks = groupUserAllowSimplexLinks gInfo - membershipProfile <- presentUserBadge user (incognitoMembershipProfile gInfo) $ redactedMemberProfile allowSimplexLinks $ fromLocalProfile $ memberProfile membership + membershipProfile <- presentUserBadge user (incognitoMembershipProfile gInfo) $ redactedMemberProfile gInfo membership $ fromLocalProfile $ memberProfile membership dm <- encodeConnInfo $ XGrpMemInfo membershipMemId membershipProfile -- [async agent commands] no continuation needed, but commands should be asynchronous for stability - groupConnIds <- joinAgentConnectionAsync user Nothing (chatHasNtfs chatSettings) groupConnReq dm subMode - directConnIds <- forM directConnReq $ \dcr -> joinAgentConnectionAsync user Nothing True dcr dm subMode + let enableNtfsGrp = chatHasNtfs chatSettings + groupConnIds@(gCmdId, gAcId) <- prepareAgentJoin user Nothing enableNtfsGrp groupConnReq + directConnIds <- mapM (prepareAgentJoin user Nothing True) directConnReq let customUserProfileId = localProfileId <$> incognitoMembershipProfile gInfo mcvr = maybe chatInitialVRange fromChatVRange memChatVRange chatV = vr cxt `peerConnChatVersion` mcvr withStore' $ \db -> createIntroToMemberContact db user m toMember chatV mcvr groupConnIds directConnIds customUserProfileId subMode + joinAgentConnectionAsync gCmdId False gAcId enableNtfsGrp groupConnReq dm subMode + forM_ ((,) <$> directConnIds <*> directConnReq) $ \((dCmdId, dAcId), dcr) -> + joinAgentConnectionAsync dCmdId False dAcId True dcr dm subMode -- rollback defense (channels): apply an owner-signed role/removal only at a version >= the persisted -- roster_version (not the batch-constant gInfo, which a relay can stale by reordering events in one -- batch), then advance it in the same transaction; a strictly lower version is a replay and is ignored. -- Only an owner sender may advance it: a non-owner signed event is rejected by the action that follows, -- but must not bump roster_version first, or every later owner roster at a lower version is dropped. - applyAtRosterVersion :: GroupInfo -> GroupMember -> Maybe VersionRoster -> CM (Maybe DeliveryJobScope) -> CM (Maybe DeliveryJobScope) - applyAtRosterVersion gInfo sender rosterVer_ action + applyAtRosterVersion :: GroupInfo -> Maybe GroupMember -> GroupMember -> Maybe VersionRoster -> CM (Maybe DeliveryJobScope) -> CM (Maybe DeliveryJobScope) + applyAtRosterVersion gInfo fwdRelay_ sender rosterVer_ action | not (useRelays' gInfo) = action | otherwise = case rosterVer_ of Nothing -> action Just _ | memberRole' sender /= GROwner -> action Just v -> do - accept <- withStore' $ \db -> do - cur <- getGroupRosterVersion db gInfo - let fresh = maybe True (v >=) cur - when fresh $ setGroupRosterVersion db gInfo v - pure fresh + (accept, prevComplete) <- withStore' $ \db -> do + gate <- getGroupRosterVersion db gInfo + prevComplete <- getCompleteRosterVersion db gInfo + let fresh = maybe True (v >=) gate + when fresh $ do + setGroupRosterVersion db gInfo v + -- advance the frontier when this delta is the next version. One version can carry several deltas + -- (a multi-member role change), delivered in order, so seeing any one of them advances the frontier + -- past that whole version. + when (v == nextCompleteVersion prevComplete) $ + setCompleteRosterVersion db gInfo v + pure (fresh, prevComplete) if accept - then action + then (requestRosterOnGap v prevComplete `catchAllErrors` eToView) >> action else messageWarning "x.grp.mem: roster version not newer than current, ignoring" $> Nothing + where + -- the next contiguous version after the complete frontier. With no frontier the baseline is the first + -- roster version (VersionRoster 0, see broadcastRoster): a subscriber seeing v0 without a prior roster is + -- current, not gapped, as it cannot have missed an earlier version - so v0 neither requests nor stays behind. + nextCompleteVersion = \case + Just (VersionRoster c) -> VersionRoster (c + 1) + Nothing -> VersionRoster 0 + -- a subscriber whose complete frontier (before this delta) lags more than one below it has missed versions: + -- ask the relay that forwarded it (it holds >= v = the new gate) to re-serve the full roster, carrying the + -- previous frontier so only a fuller snapshot is served. A stuck frontier re-asks on every following delta + -- until a roster fills it. Best-effort; relays and the direct path (fwdRelay_ = Nothing) don't ask, nor a + -- relay that predates roster support. + requestRosterOnGap v prevComplete + | isUserGrpFwdRelay gInfo = pure () + | otherwise = case fwdRelay_ of + Just relay + | gap, relay `supportsVersion` groupRosterVersion -> + void $ sendGroupMessage' user gInfo [relay] (XGrpRosterRequest prevComplete) + _ -> pure () + where + gap = v > nextCompleteVersion prevComplete - xGrpMemRole :: GroupInfo -> GroupMember -> MemberId -> GroupMemberRole -> Maybe MemberKey -> Maybe VersionRoster -> RcvMessage -> UTCTime -> CM (Maybe DeliveryJobScope) - xGrpMemRole gInfo@GroupInfo {membership} m@GroupMember {memberRole = senderRole} memId memRole memberKey_ rosterVer_ msg@RcvMessage {msgSigned} brokerTs + xGrpMemRole :: GroupInfo -> Maybe GroupMember -> GroupMember -> MemberId -> GroupMemberRole -> Maybe MemberKey -> Maybe VersionRoster -> RcvMessage -> UTCTime -> CM (Maybe DeliveryJobScope) + xGrpMemRole gInfo@GroupInfo {membership} fwdRelay_ m@GroupMember {memberRole = senderRole} memId memRole memberKey_ rosterVer_ msg@RcvMessage {msgSigned} brokerTs | membershipMemId == memId = - applyAtRosterVersion gInfo m rosterVer_ $ + applyAtRosterVersion gInfo fwdRelay_ m rosterVer_ $ let gInfo' = gInfo {membership = membership {memberRole = memRole}} in changeMemberRole gInfo' membership False (\db -> updateGroupMemberRole db user membership memRole) (RGEUserRole memRole) True - | otherwise = applyAtRosterVersion gInfo m rosterVer_ $ do + | otherwise = applyAtRosterVersion gInfo fwdRelay_ m rosterVer_ $ do defaultRole <- unknownMemberRole gInfo -- an owner-signed event with a key TOFU-creates an unknown member only for a roster role; else a plain lookup let allowCreate = useRelays' gInfo && senderRole == GROwner && isRosterRole memRole && isJust memberKey_ @@ -3340,7 +3369,7 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = -- transfer record + its scratch file in one transaction (file owned by the transfer, keyed per source) rft@RcvFileTransfer {fileId} <- withStore $ \db -> do transferId <- liftIO $ createRosterTransfer db gInfo (groupMemberId' fromMember) newVer fileDigest (groupMemberId' author) brokerTs relayHdr - createRosterRcvFile db userId gInfo fromMember transferId sharedMsgId rosterFInv (Just IFMSent) (fromIntegral chSize) + createRosterRcvFile db userId gInfo fromMember transferId sharedMsgId rosterFInv (Just IFMSent) chSize -- accept the chat-item-free file before chunk 1 (FIFO before it) so chunk 1 isn't rejected on RFSNew -- transient scratch file (consumed into roster_blob, then deleted): temp folder, not the user's files folder / Downloads tmpDir <- lift getChatTempDirectory @@ -3366,10 +3395,10 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = Just RcvRosterTransfer {rosterTransferId = transferId, rosterTransferVersion = pendingVer, rosterTransferDigest = pendingDigest, rosterTransferOwnerGMId = ownerGMId, rosterTransferBrokerTs = rosterBrokerTs, rosterTransferHeader = header_} -> do owner_ <- withStore' $ \db -> eitherToMaybe <$> runExceptT (getGroupMemberById db cxt user ownerGMId) blob <- readAssembledRoster - let isRelay = isUserGrpFwdRelay gInfo + let isRelay' = isUserGrpFwdRelay gInfo ackErr err = do cleanupRosterTransferById transferId - when isRelay $ forM_ owner_ $ \owner -> sendRosterAck gInfo owner pendingVer (Just err) + when isRelay' $ forM_ owner_ $ \owner -> sendRosterAck gInfo owner pendingVer (Just err) if FD.FileDigest (LC.sha512Hash (LB.fromStrict blob)) /= pendingDigest then ackErr "relay could not verify the roster blob" else case parseAll rosterBlobP blob of @@ -3393,7 +3422,7 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = forM_ results_ $ \results -> do emitRosterResults gInfo author rosterBrokerTs results -- ack while setting up (own status accepted/acknowledged); a serving (active) relay must not ack broadcasts. - when (isRelay && (relayOwnStatus gInfo == Just RSAccepted || relayOwnStatus gInfo == Just RSAcknowledgedRoster)) $ do + when (isRelay' && (relayOwnStatus gInfo == Just RSAccepted || relayOwnStatus gInfo == Just RSAcknowledgedRoster)) $ do sendRosterAck gInfo author pendingVer Nothing withStore' $ \db -> void $ updateRelayOwnStatusFromTo db gInfo RSAccepted RSAcknowledgedRoster where @@ -3442,18 +3471,22 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = `catchAllErrors` \_ -> pure (cs, as) emitRosterResults :: GroupInfo -> GroupMember -> UTCTime -> ([MemberId], [(GroupMember, GroupMemberRole, Bool)]) -> CM () - emitRosterResults gInfo author rosterBrokerTs (conflicts, applied) = do + emitRosterResults gInfo@GroupInfo {membership} author rosterBrokerTs (conflicts, applied) = do forM_ conflicts $ \mid' -> messageWarning $ "x.grp.roster: member key conflict, keeping trusted key, memberId=" <> safeDecodeUtf8 (strEncode mid') forM_ applied $ \(member, fromRole, created) -> - unless created $ createItems member fromRole + unless created $ emitRoleChange member fromRole where - createItems member fromRole = do + emitRoleChange member fromRole = do let toRole = memberRole' member - gEvent = RGEMemberRole (groupMemberId' member) (fromLocalProfile $ memberProfile member) toRole - (gInfo', author', scopeInfo) <- mkGroupChatScope gInfo author - ci <- createChatItem user (CDGroupRcv gInfo' scopeInfo author') False (CIRcvGroupEvent gEvent) Nothing (Just MSSVerified) (Just rosterBrokerTs) - toView $ CEvtNewChatItems user [ci] + (gInfo', author') <- + if sameMemberId (memberId' membership) member + then do + (gInfo', author', scopeInfo) <- mkGroupChatScope gInfo author + ci <- createChatItem user (CDGroupRcv gInfo' scopeInfo author') False (CIRcvGroupEvent $ RGEUserRole toRole) Nothing (Just MSSVerified) (Just rosterBrokerTs) + toView $ CEvtNewChatItems user [ci] + pure (gInfo', author') + else pure (gInfo, author) toView CEvtMemberRole {user, groupInfo = gInfo', byMember = author', member, fromRole, toRole, msgSigned = Just MSSVerified} sendRosterAck :: GroupInfo -> GroupMember -> VersionRoster -> Maybe Text -> CM () @@ -3479,6 +3512,19 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = messageError $ "x.grp.roster.ack: relay could not save roster, marked rejected: " <> e _ -> pure () + -- A relay re-serves the full roster to a subscriber that detected a version gap, but only when its STORED + -- blob is newer than BOTH the requester's version (Nothing = none) and the version it last served this member + -- - the latter bounds reflected amplification (a member can't re-trigger a full serve). Gating on the stored + -- blob (not roster_version, the gate) means the relay serves only a blob the requester will accept. + -- serveRoster records the served version (on all serve paths) and is a no-op without a roster. + xGrpRosterRequest :: GroupInfo -> GroupMember -> Maybe VersionRoster -> CM () + xGrpRosterRequest gInfo m reqVer_ = + when (isUserGrpFwdRelay gInfo) $ do + (stored_, served_) <- withStore' $ \db -> + (,) <$> getStoredRosterVersion db gInfo <*> getMemberRosterServedVersion db m + forM_ stored_ $ \stored -> + when (maybe True (stored >) reqVer_ && maybe True (stored >) served_) $ serveRoster user gInfo m + checkHostRole :: GroupMember -> GroupMemberRole -> CM () checkHostRole GroupMember {memberRole, localDisplayName} memRole = when (memberRole < GRAdmin || memberRole < memRole) $ throwChatError (CEGroupContactRole localDisplayName) @@ -3523,11 +3569,11 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = withStore $ \db -> setMemberVectorRelationConnected db sendingMem refMem MRSubjectConnected withStore $ \db -> setMemberVectorRelationConnected db refMem sendingMem MRReferencedConnected - xGrpMemDel :: GroupInfo -> GroupMember -> MemberId -> Bool -> Maybe VersionRoster -> VerifiedMsg 'Json -> RcvMessage -> UTCTime -> Bool -> CM (Maybe DeliveryJobScope) - xGrpMemDel gInfo@GroupInfo {membership} m@GroupMember {memberRole = senderRole} memId withMessages rosterVer_ verifiedMsg msg@RcvMessage {msgSigned} brokerTs forwarded = do + xGrpMemDel :: GroupInfo -> Maybe GroupMember -> GroupMember -> MemberId -> Bool -> Maybe VersionRoster -> VerifiedMsg 'Json -> RcvMessage -> UTCTime -> Bool -> CM (Maybe DeliveryJobScope) + xGrpMemDel gInfo@GroupInfo {membership} fwdRelay_ m@GroupMember {memberRole = senderRole} memId withMessages rosterVer_ verifiedMsg msg@RcvMessage {msgSigned} brokerTs forwarded = do let GroupMember {memberId = membershipMemId} = membership if membershipMemId == memId - then applyAtRosterVersion gInfo m rosterVer_ $ checkRole membership $ do + then applyAtRosterVersion gInfo fwdRelay_ m rosterVer_ $ checkRole membership $ do deleteGroupLinkIfExists user gInfo -- TODO [relays] possible improvement is to immediately delete rcv queues if isUserGrpFwdRelay unless (isUserGrpFwdRelay gInfo) $ deleteGroupConnections user gInfo False @@ -3539,7 +3585,7 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = deleteMemberItem msg gInfo RGEUserDeleted toView $ CEvtDeletedMemberUser user gInfo {membership = membership'} m withMessages msgSigned pure $ Just DJSGroup {jobSpec = DJRelayRemoved} - else applyAtRosterVersion gInfo m rosterVer_ $ + else applyAtRosterVersion gInfo fwdRelay_ m rosterVer_ $ withStore' (\db -> runExceptT $ getGroupMemberByMemberId db cxt user gInfo memId) >>= \case Left _ -> do messageError "x.grp.mem.del with unknown member ID" @@ -3712,11 +3758,12 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = } joinExistingContact subMode mCt@Contact {contactId = mContactId} | autoAcceptMemberContacts user = do - (cmdId, acId) <- joinConn subMode + (cmdId, acId) <- prepareAgentJoin user Nothing True connReq mCt' <- withStore $ \db -> do updateMemberContactInvited db user mCt groupDirectInv void $ liftIO $ createMemberContactConn db user acId (Just cmdId) g mConn ConnJoined mContactId subMode getContact db cxt user mContactId + joinMemberContactAsync cmdId acId subMode securityCodeChanged mCt' createItems mCt' m | otherwise = do @@ -3730,13 +3777,14 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = createItems mCt' m createNewContact subMode | autoAcceptMemberContacts user = do - (cmdId, acId) <- joinConn subMode + (cmdId, acId) <- prepareAgentJoin user Nothing True connReq -- [incognito] reuse membership incognito profile (mCt, m') <- withStore $ \db -> do (mContactId, m') <- liftIO $ createMemberContactInvited db user g m groupDirectInv void $ liftIO $ createMemberContactConn db user acId (Just cmdId) g mConn ConnJoined mContactId subMode mCt <- getContact db cxt user mContactId pure (mCt, m') + joinMemberContactAsync cmdId acId subMode createInternalChatItem user (CDDirectSnd mCt) CIChatBanner (Just epochStart) createItems mCt m' | otherwise = do @@ -3749,12 +3797,12 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = createInternalChatItem user (CDDirectSnd mCt) CIChatBanner (Just epochStart) createInternalChatItem user (CDDirectRcv mCt) (CIRcvDirectEvent $ RDEGroupInvLinkReceived gp) Nothing createItems mCt m' - joinConn subMode = do + joinMemberContactAsync cmdId acId subMode = do -- [incognito] send membership incognito profile p <- presentUserBadge user (incognitoMembershipProfile g) $ userProfileDirect user (fromLocalProfile <$> incognitoMembershipProfile g) Nothing True -- TODO PQ should negotitate contact connection with PQSupportOn? (use encodeConnInfoPQ) dm <- encodeConnInfo $ XInfo p - joinAgentConnectionAsync user Nothing True connReq dm subMode + joinAgentConnectionAsync cmdId False acId True connReq dm subMode createItems mCt' m' = do (g', m'', scopeInfo) <- mkGroupChatScope g m' createInternalChatItem user (CDGroupRcv g' scopeInfo m'') (CIRcvGroupEvent RGEMemberCreatedContact) Nothing @@ -3805,9 +3853,9 @@ processAgentMessageConn cxt user@User {userId} corrId agentConnId agentMessage = XInfo p -> withAuthor XInfo_ $ \author -> void $ xInfoMember gInfo author p rcvMsg msgTs XGrpRelayNew rl -> withAuthor XGrpRelayNew_ $ \author -> void $ xGrpRelayNew gInfo author rl XGrpMemNew memInfo msgScope -> withAuthor XGrpMemNew_ $ \author -> void $ xGrpMemNew gInfo author memInfo msgScope rcvMsg msgTs - XGrpMemRole memId memRole memberKey rosterVer -> withAuthor XGrpMemRole_ $ \author -> void $ xGrpMemRole gInfo author memId memRole memberKey rosterVer rcvMsg msgTs + XGrpMemRole memId memRole memberKey rosterVer -> withAuthor XGrpMemRole_ $ \author -> void $ xGrpMemRole gInfo (Just m) author memId memRole memberKey rosterVer rcvMsg msgTs XGrpMemRestrict memId memRestrictions -> withAuthor XGrpMemRestrict_ $ \author -> void $ xGrpMemRestrict gInfo author memId memRestrictions rcvMsg msgTs - XGrpMemDel memId withMessages rosterVer -> withAuthor XGrpMemDel_ $ \author -> void $ xGrpMemDel gInfo author memId withMessages rosterVer verifiedMsg rcvMsg msgTs True + XGrpMemDel memId withMessages rosterVer -> withAuthor XGrpMemDel_ $ \author -> void $ xGrpMemDel gInfo (Just m) author memId withMessages rosterVer verifiedMsg rcvMsg msgTs True XGrpLeave -> withAuthor XGrpLeave_ $ \author -> void $ xGrpLeave gInfo author rcvMsg msgTs XGrpDel -> withAuthor XGrpDel_ $ \author -> void $ xGrpDel gInfo author rcvMsg msgTs XGrpInfo p' -> withAuthor XGrpInfo_ $ \author -> void $ xGrpInfo gInfo author p' rcvMsg msgTs diff --git a/src/Simplex/Chat/Names.hs b/src/Simplex/Chat/Names.hs new file mode 100644 index 0000000000..081d7129a5 --- /dev/null +++ b/src/Simplex/Chat/Names.hs @@ -0,0 +1,61 @@ +{-# LANGUAGE CPP #-} +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE DuplicateRecordFields #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE KindSignatures #-} +{-# LANGUAGE NamedFieldPuns #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE TemplateHaskell #-} + +module Simplex.Chat.Names + ( SimplexDomainClaim (..), + SimplexDomainProof (..), + mkDomainClaim, + claimDomain, + ) +where + +import qualified Data.Aeson.TH as JQ +import Simplex.Chat.Badges (ProofPresHeader) +import Simplex.Messaging.Agent.Protocol (OwnerId, SimplexDomain) +import Simplex.Messaging.Agent.Store.DB (fromTextField_) +import qualified Simplex.Messaging.Crypto as C +import Simplex.Messaging.Encoding.String +import Simplex.Messaging.Parsers (defaultJSON) +import Simplex.Messaging.Util (decodeJSON, encodeJSON) +#if defined(dbPostgres) +import Database.PostgreSQL.Simple.FromField (FromField (..)) +import Database.PostgreSQL.Simple.ToField (ToField (..)) +#else +import Database.SQLite.Simple.FromField (FromField (..)) +import Database.SQLite.Simple.ToField (ToField (..)) +#endif + +-- A name claim proof: signed by the address owner's key over proof payload - see verifyDomainProof. +data SimplexDomainProof = SimplexDomainProof + { linkOwnerId :: Maybe (StrJSON "OwnerId" OwnerId), + presHeader :: ProofPresHeader, + signature :: C.Signature 'C.Ed25519 + } + deriving (Eq, Show) + +$(JQ.deriveJSON defaultJSON ''SimplexDomainProof) + +instance ToField SimplexDomainProof where toField = toField . encodeJSON + +instance FromField SimplexDomainProof where fromField = fromTextField_ decodeJSON + +data SimplexDomainClaim = SimplexDomainClaim + { domain :: StrJSON "SimplexDomain" SimplexDomain, + proof :: Maybe SimplexDomainProof + } + deriving (Eq, Show) + +mkDomainClaim :: SimplexDomain -> SimplexDomainClaim +mkDomainClaim = (`SimplexDomainClaim` Nothing) . StrJSON + +claimDomain :: SimplexDomainClaim -> SimplexDomain +claimDomain (SimplexDomainClaim n _) = unStrJSON n + +$(JQ.deriveJSON defaultJSON ''SimplexDomainClaim) diff --git a/src/Simplex/Chat/Operators.hs b/src/Simplex/Chat/Operators.hs index 6816a5f692..ad03529613 100644 --- a/src/Simplex/Chat/Operators.hs +++ b/src/Simplex/Chat/Operators.hs @@ -511,7 +511,9 @@ data UserServersError | USEDuplicateChatRelayAddress {duplicateChatRelay :: Text, duplicateAddress :: ShortLinkContact} deriving (Show) -data UserServersWarning = USWNoChatRelays {user :: Maybe User} +data UserServersWarning + = USWNoChatRelays {user :: Maybe User} + | USWNoNamesServers {user :: Maybe User} deriving (Show) validateUserServers :: UserServersClass u' => [u'] -> [(User, [UserOperatorServers])] -> ([UserServersError], [UserServersWarning]) @@ -552,15 +554,19 @@ validateUserServers curr others = (currUserErrs <> concatMap otherUserErrs other addAddress (xs, dups) x | any (sameShortLinkContact x) xs = (xs, x : dups) | otherwise = (x : xs, dups) - currUserWarns = noChatRelaysWarns Nothing curr - otherUserWarns (user, uss) = noChatRelaysWarns (Just user) uss + currUserWarns = noChatRelaysWarns Nothing curr <> noNamesServersWarns Nothing curr + otherUserWarns (user, uss) = noChatRelaysWarns (Just user) uss <> noNamesServersWarns (Just user) uss noChatRelaysWarns :: UserServersClass u => Maybe User -> [u] -> [UserServersWarning] - noChatRelaysWarns user uss - | noChatRelays opEnabled = [USWNoChatRelays user] - | otherwise = [] + noChatRelaysWarns user uss = [USWNoChatRelays user | noChatRelays opEnabled] where noChatRelays cond = not $ any relayEnabled $ userChatRelays $ filter cond uss relayEnabled (AUCR _ UserChatRelay {deleted, enabled}) = enabled && not deleted + noNamesServersWarns :: UserServersClass u => Maybe User -> [u] -> [UserServersWarning] + noNamesServersWarns user uss = [USWNoNamesServers user | noNamesServers] + where + noNamesServers = not $ any srvEnabled $ userServers SPSMP $ filter namesEnabled uss + srvEnabled (AUS _ UserServer {deleted, enabled}) = enabled && not deleted + namesEnabled = maybe True (\op@ServerOperator {enabled} -> enabled && names (operatorRoles SPSMP op)) . operator' userChatRelays :: UserServersClass u => [u] -> [AUserChatRelay] userChatRelays = map aUserChatRelay' . concatMap chatRelays' opEnabled :: UserServersClass u => u -> Bool diff --git a/src/Simplex/Chat/Operators/Presets.hs b/src/Simplex/Chat/Operators/Presets.hs index 53f31e005d..d55d23e2b9 100644 --- a/src/Simplex/Chat/Operators/Presets.hs +++ b/src/Simplex/Chat/Operators/Presets.hs @@ -39,8 +39,8 @@ operatorFlux = serverDomains = ["simplexonflux.com"], conditionsAcceptance = CARequired Nothing, enabled = True, - smpRoles = ServerRoles {storage = False, proxy = True}, - xftpRoles = ServerRoles {storage = False, proxy = True} + smpRoles = ServerRoles {storage = False, proxy = True, names = True}, + xftpRoles = allRoles } -- Please note: if any servers are removed from the lists below, they MUST be added here. diff --git a/src/Simplex/Chat/ProfileGenerator.hs b/src/Simplex/Chat/ProfileGenerator.hs index 7d272481f6..4d10945ab6 100644 --- a/src/Simplex/Chat/ProfileGenerator.hs +++ b/src/Simplex/Chat/ProfileGenerator.hs @@ -10,7 +10,7 @@ generateRandomProfile :: IO Profile generateRandomProfile = do adjective <- pick adjectives noun <- pickNoun adjective 2 - pure $ Profile {displayName = adjective <> noun, fullName = "", shortDescr = Nothing, image = Nothing, contactLink = Nothing, peerType = Nothing, preferences = Nothing, badge = Nothing} + pure $ Profile {displayName = adjective <> noun, fullName = "", shortDescr = Nothing, image = Nothing, contactLink = Nothing, peerType = Nothing, preferences = Nothing, badge = Nothing, contactDomain = Nothing} where pick :: [a] -> IO a pick xs = (xs !!) <$> randomRIO (0, length xs - 1) diff --git a/src/Simplex/Chat/Protocol.hs b/src/Simplex/Chat/Protocol.hs index 223fe492a9..2fb8361fdb 100644 --- a/src/Simplex/Chat/Protocol.hs +++ b/src/Simplex/Chat/Protocol.hs @@ -525,6 +525,7 @@ data ChatMsgEvent (e :: MsgEncoding) where XGrpDirectInv :: ConnReqInvitation -> Maybe MsgContent -> Maybe MsgScope -> ChatMsgEvent 'Json XGrpRoster :: GroupRoster -> ChatMsgEvent 'Json XGrpRosterAck :: VersionRoster -> Maybe Text -> ChatMsgEvent 'Json + XGrpRosterRequest :: Maybe VersionRoster -> ChatMsgEvent 'Json XGrpMsgForward :: GrpMsgForward -> ChatMessage 'Json -> ChatMsgEvent 'Json XInfoProbe :: Probe -> ChatMsgEvent 'Json XInfoProbeCheck :: ProbeHash -> ChatMsgEvent 'Json @@ -1099,6 +1100,7 @@ data CMEventTag (e :: MsgEncoding) where XGrpDirectInv_ :: CMEventTag 'Json XGrpRoster_ :: CMEventTag 'Json XGrpRosterAck_ :: CMEventTag 'Json + XGrpRosterRequest_ :: CMEventTag 'Json XGrpMsgForward_ :: CMEventTag 'Json XInfoProbe_ :: CMEventTag 'Json XInfoProbeCheck_ :: CMEventTag 'Json @@ -1161,6 +1163,7 @@ instance MsgEncodingI e => StrEncoding (CMEventTag e) where XGrpDirectInv_ -> "x.grp.direct.inv" XGrpRoster_ -> "x.grp.roster" XGrpRosterAck_ -> "x.grp.roster.ack" + XGrpRosterRequest_ -> "x.grp.roster.request" XGrpMsgForward_ -> "x.grp.msg.forward" XInfoProbe_ -> "x.info.probe" XInfoProbeCheck_ -> "x.info.probe.check" @@ -1224,6 +1227,7 @@ instance StrEncoding ACMEventTag where "x.grp.direct.inv" -> XGrpDirectInv_ "x.grp.roster" -> XGrpRoster_ "x.grp.roster.ack" -> XGrpRosterAck_ + "x.grp.roster.request" -> XGrpRosterRequest_ "x.grp.msg.forward" -> XGrpMsgForward_ "x.info.probe" -> XInfoProbe_ "x.info.probe.check" -> XInfoProbeCheck_ @@ -1283,6 +1287,7 @@ toCMEventTag msg = case msg of XGrpDirectInv {} -> XGrpDirectInv_ XGrpRoster _ -> XGrpRoster_ XGrpRosterAck {} -> XGrpRosterAck_ + XGrpRosterRequest _ -> XGrpRosterRequest_ XGrpMsgForward {} -> XGrpMsgForward_ XInfoProbe _ -> XInfoProbe_ XInfoProbeCheck _ -> XInfoProbeCheck_ @@ -1444,6 +1449,7 @@ appJsonToCM AppMessageJson {v, msgId, event, params} = do XGrpDirectInv_ -> XGrpDirectInv <$> p "connReq" <*> opt "content" <*> opt "scope" XGrpRoster_ -> XGrpRoster <$> (GroupRoster <$> p "version" <*> p "fileInv") XGrpRosterAck_ -> XGrpRosterAck <$> p "version" <*> opt "error" + XGrpRosterRequest_ -> XGrpRosterRequest <$> opt "version" XGrpMsgForward_ -> do fwdSender <- opt "memberId" >>= \case Just memberId -> FwdMember memberId . fromMaybe "" <$> opt "memberName" @@ -1518,6 +1524,7 @@ chatToAppMessage chatMsg@ChatMessage {chatVRange, msgId, chatMsgEvent} = case en XGrpDirectInv connReq content scope -> o $ ("content" .=? content) $ ("scope" .=? scope) ["connReq" .= connReq] XGrpRoster GroupRoster {version, fileInv} -> o ["version" .= version, "fileInv" .= fileInv] XGrpRosterAck version err -> o $ ("error" .=? err) ["version" .= version] + XGrpRosterRequest version -> o $ ("version" .=? version) [] XGrpMsgForward GrpMsgForward {fwdSender, fwdBrokerTs} msg -> o $ encodeFwdSender fwdSender ["msg" .= msg, "msgTs" .= fwdBrokerTs] where encodeFwdSender = \case diff --git a/src/Simplex/Chat/Store/Connections.hs b/src/Simplex/Chat/Store/Connections.hs index 2953c1de1f..74d574b643 100644 --- a/src/Simplex/Chat/Store/Connections.hs +++ b/src/Simplex/Chat/Store/Connections.hs @@ -116,15 +116,16 @@ getConnectionEntity db cxt user@User {userId, userContactId} agentConnId = do p.preferences, c.user_preferences, c.created_at, c.updated_at, c.chat_ts, c.conn_full_link_to_connect, c.conn_short_link_to_connect, c.welcome_shared_msg_id, c.request_shared_msg_id, c.contact_request_id, c.contact_group_member_id, c.contact_grp_inv_sent, c.grp_direct_inv_link, c.grp_direct_inv_from_group_id, c.grp_direct_inv_from_group_member_id, c.grp_direct_inv_from_member_conn_id, c.grp_direct_inv_started_connection, c.ui_themes, c.chat_deleted, c.custom_data, c.chat_item_ttl, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.contact_domain, p.contact_domain_proof, p.contact_domain_verified FROM contacts c JOIN contact_profiles p ON c.contact_profile_id = p.contact_profile_id WHERE c.user_id = ? AND c.contact_id = ? AND c.contact_status = ? AND c.deleted = 0 |] (userId, contactId, CSActive) toContact' :: UTCTime -> Int64 -> Connection -> [ChatTagId] -> ContactRow' -> Contact - toContact' currentTs contactId conn chatTags ((profileId, localDisplayName, displayName, fullName, shortDescr, image, contactLink, peerType, localAlias, BI contactUsed, contactStatus) :. (enableNtfs_, sendRcpts, BI favorite, preferences, userPreferences, createdAt, updatedAt, chatTs) :. preparedContactRow :. (contactRequestId, contactGroupMemberId, BI contactGrpInvSent) :. groupDirectInvRow :. (uiThemes, BI chatDeleted, customData, chatItemTTL) :. badgeRow) = - let profile = LocalProfile {profileId, displayName, fullName, shortDescr, image, contactLink, peerType, localBadge = rowToBadge currentTs badgeRow, preferences, localAlias} + toContact' currentTs contactId conn chatTags ((profileId, localDisplayName, displayName, fullName, shortDescr, image, contactLink, peerType, localAlias, BI contactUsed, contactStatus) :. (enableNtfs_, sendRcpts, BI favorite, preferences, userPreferences, createdAt, updatedAt, chatTs) :. preparedContactRow :. (contactRequestId, contactGroupMemberId, BI contactGrpInvSent) :. groupDirectInvRow :. (uiThemes, BI chatDeleted, customData, chatItemTTL) :. badgeRow :. domainRow) = + let profile = LocalProfile {profileId, displayName, fullName, shortDescr, image, contactLink, contactDomain = rowToContactDomain domainRow, contactDomainVerified = rowToDomainVerified domainRow, peerType, localBadge = rowToBadge currentTs badgeRow, preferences, localAlias} chatSettings = ChatSettings {enableNtfs = fromMaybe MFAll enableNtfs_, sendRcpts = unBI <$> sendRcpts, favorite} mergedPreferences = contactUserPreferences user userPreferences preferences $ connIncognito conn activeConn = Just conn @@ -143,26 +144,26 @@ getConnectionEntity db cxt user@User {userId, userContactId} agentConnId = do SELECT -- GroupInfo g.group_id, g.local_display_name, gp.display_name, gp.full_name, gp.short_descr, g.local_alias, gp.description, gp.image, gp.group_type, gp.group_link, gp.public_group_id, - gp.group_web_page, gp.group_domain, gp.domain_web_page, gp.allow_embedding, + gp.group_web_page, gp.group_domain, gp.domain_web_page, gp.allow_embedding, gp.group_domain_proof, g.enable_ntfs, g.send_rcpts, g.favorite, gp.preferences, gp.member_admission, g.created_at, g.updated_at, g.chat_ts, g.user_member_profile_sent_at, g.conn_full_link_to_connect, g.conn_short_link_to_connect, g.conn_link_prepared_connection, g.conn_link_started_connection, g.welcome_shared_msg_id, g.request_shared_msg_id, g.business_chat, g.business_member_id, g.customer_member_id, g.use_relays, g.relay_own_status, - g.ui_themes, g.summary_current_members_count, g.public_member_count, g.roster_version, g.custom_data, g.chat_item_ttl, g.members_require_attention, g.via_group_link_uri, + g.ui_themes, g.summary_current_members_count, g.public_member_count, g.roster_version, g.custom_data, g.chat_item_ttl, g.members_require_attention, g.via_group_link_uri, g.group_domain_verified, g.root_priv_key, g.root_pub_key, g.member_priv_key, -- GroupInfo {membership} mu.group_member_id, mu.group_id, mu.index_in_group, mu.member_id, mu.peer_chat_min_version, mu.peer_chat_max_version, mu.member_role, mu.member_category, mu.member_status, mu.show_messages, mu.member_restriction, mu.invited_by, mu.invited_by_group_member_id, mu.local_display_name, mu.contact_id, mu.contact_profile_id, pu.contact_profile_id, -- GroupInfo {membership = GroupMember {memberProfile}} pu.display_name, pu.full_name, pu.short_descr, pu.image, pu.contact_link, pu.chat_peer_type, pu.local_alias, pu.preferences, - pu.badge_proof, pu.badge_pres_header, pu.badge_expiry, pu.badge_type, pu.badge_verified, pu.badge_extra, pu.badge_master_key, pu.badge_signature, pu.badge_key_idx, + pu.badge_proof, pu.badge_pres_header, pu.badge_expiry, pu.badge_type, pu.badge_verified, pu.badge_extra, pu.badge_master_key, pu.badge_signature, pu.badge_key_idx, pu.contact_domain, pu.contact_domain_proof, pu.contact_domain_verified, mu.created_at, mu.updated_at, mu.support_chat_ts, mu.support_chat_items_unread, mu.support_chat_items_member_attention, mu.support_chat_items_mentions, mu.support_chat_last_msg_from_member_ts, mu.member_pub_key, mu.relay_link, -- from GroupMember m.group_member_id, m.group_id, m.index_in_group, m.member_id, m.peer_chat_min_version, m.peer_chat_max_version, m.member_role, m.member_category, m.member_status, m.show_messages, m.member_restriction, m.invited_by, m.invited_by_group_member_id, m.local_display_name, m.contact_id, m.contact_profile_id, p.contact_profile_id, p.display_name, p.full_name, p.short_descr, p.image, p.contact_link, p.chat_peer_type, p.local_alias, p.preferences, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified, m.created_at, m.updated_at, m.support_chat_ts, m.support_chat_items_unread, m.support_chat_items_member_attention, m.support_chat_items_mentions, m.support_chat_last_msg_from_member_ts, m.member_pub_key, m.relay_link FROM group_members m diff --git a/src/Simplex/Chat/Store/ContactRequest.hs b/src/Simplex/Chat/Store/ContactRequest.hs index 9c5fe0cd91..3bd481d7db 100644 --- a/src/Simplex/Chat/Store/ContactRequest.hs +++ b/src/Simplex/Chat/Store/ContactRequest.hs @@ -116,7 +116,7 @@ createOrUpdateContactRequest cp.preferences, ct.user_preferences, ct.created_at, ct.updated_at, ct.chat_ts, ct.conn_full_link_to_connect, ct.conn_short_link_to_connect, ct.welcome_shared_msg_id, ct.request_shared_msg_id, ct.contact_request_id, ct.contact_group_member_id, ct.contact_grp_inv_sent, ct.grp_direct_inv_link, ct.grp_direct_inv_from_group_id, ct.grp_direct_inv_from_group_member_id, ct.grp_direct_inv_from_member_conn_id, ct.grp_direct_inv_started_connection, ct.ui_themes, ct.chat_deleted, ct.custom_data, ct.chat_item_ttl, - cp.badge_proof, cp.badge_pres_header, cp.badge_expiry, cp.badge_type, cp.badge_verified, cp.badge_extra, cp.badge_master_key, cp.badge_signature, cp.badge_key_idx, + cp.badge_proof, cp.badge_pres_header, cp.badge_expiry, cp.badge_type, cp.badge_verified, cp.badge_extra, cp.badge_master_key, cp.badge_signature, cp.badge_key_idx, cp.contact_domain, cp.contact_domain_proof, cp.contact_domain_verified, -- Connection c.connection_id, c.agent_conn_id, c.conn_level, c.via_contact, c.via_user_contact_link, c.via_group_link, c.group_link_id, c.xcontact_id, c.custom_user_profile_id, c.conn_status, c.conn_type, c.contact_conn_initiated, c.local_alias, c.contact_id, c.group_member_id, c.user_contact_link_id, c.created_at, c.security_code, c.security_code_verified_at, c.pq_support, c.pq_encryption, c.pq_snd_enabled, c.pq_rcv_enabled, c.auth_err_counter, c.quota_err_counter, @@ -152,7 +152,7 @@ createOrUpdateContactRequest cr.pq_support, cr.welcome_shared_msg_id, cr.request_shared_msg_id, p.preferences, cr.created_at, cr.updated_at, cr.peer_chat_min_version, cr.peer_chat_max_version, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified FROM contact_requests cr JOIN contact_profiles p USING (contact_profile_id) WHERE cr.user_id = ? diff --git a/src/Simplex/Chat/Store/Direct.hs b/src/Simplex/Chat/Store/Direct.hs index 5068c5c61c..71e5c80a63 100644 --- a/src/Simplex/Chat/Store/Direct.hs +++ b/src/Simplex/Chat/Store/Direct.hs @@ -46,10 +46,12 @@ module Simplex.Chat.Store.Direct deleteContactWithoutGroups, getDeletedContacts, getContactByName, + getContactToConnect, getContact, getContactViaShortLinkToConnect, getContactIdByName, updateContactProfile, + setContactDomainVerified, updateContactUserPreferences, updateContactAlias, updateContactConnectionAlias, @@ -98,6 +100,7 @@ where import Control.Monad import Control.Monad.Except import Control.Monad.IO.Class +import Data.Bifunctor (first) import Data.Either (rights) import Data.Functor (($>)) import Data.Int (Int64) @@ -108,16 +111,18 @@ import Data.Type.Equality import Simplex.Chat.Badges (badgeToRow) import Simplex.Chat.Messages import Simplex.Chat.Store.Shared +import Simplex.Chat.Names (SimplexDomainClaim (..)) import Simplex.Chat.Types import Simplex.Chat.Types.Preferences import Simplex.Chat.Types.UITheme -import Simplex.Messaging.Agent.Protocol (AConnectionRequestUri (..), ACreatedConnLink (..), ConnId, ConnShortLink, ConnectionModeI (..), ConnectionRequestUri, CreatedConnLink (..), UserId) +import Simplex.Messaging.Agent.Protocol (AConnectionRequestUri (..), ACreatedConnLink (..), ConnId, ConnShortLink, ConnectionModeI (..), ConnectionRequestUri, CreatedConnLink (..), SConnectionMode (..), SimplexNameInfo (..), UserId) import Simplex.Messaging.Agent.Store.AgentStore (firstRow, maybeFirstRow) import Simplex.Messaging.Agent.Store.DB (BoolInt (..)) import qualified Simplex.Messaging.Agent.Store.DB as DB import Simplex.Messaging.Crypto.Ratchet (PQSupport, pattern PQSupportOff) import qualified Simplex.Messaging.Crypto.Ratchet as CR import Simplex.Messaging.Protocol (SubscriptionMode (..)) +import Simplex.Messaging.Util ((<$$>)) #if defined(dbPostgres) import Database.PostgreSQL.Simple (Only (..), Query, (:.) (..)) import Database.PostgreSQL.Simple.SqlQQ (sql) @@ -321,6 +326,7 @@ getContactByConnReqHash db cxt user@User {userId} cReqHash1 cReqHash2 = do ct.contact_group_member_id, ct.contact_grp_inv_sent, ct.grp_direct_inv_link, ct.grp_direct_inv_from_group_id, ct.grp_direct_inv_from_group_member_id, ct.grp_direct_inv_from_member_conn_id, ct.grp_direct_inv_started_connection, ct.ui_themes, ct.chat_deleted, ct.custom_data, ct.chat_item_ttl, cp.badge_proof, cp.badge_pres_header, cp.badge_expiry, cp.badge_type, cp.badge_verified, cp.badge_extra, cp.badge_master_key, cp.badge_signature, cp.badge_key_idx, + cp.contact_domain, cp.contact_domain_proof, cp.contact_domain_verified, -- Connection c.connection_id, c.agent_conn_id, c.conn_level, c.via_contact, c.via_user_contact_link, c.via_group_link, c.group_link_id, c.xcontact_id, c.custom_user_profile_id, c.conn_status, c.conn_type, c.contact_conn_initiated, c.local_alias, c.contact_id, c.group_member_id, c.user_contact_link_id, c.created_at, c.security_code, c.security_code_verified_at, c.pq_support, c.pq_encryption, c.pq_snd_enabled, c.pq_rcv_enabled, c.auth_err_counter, c.quota_err_counter, @@ -397,13 +403,13 @@ createIncognitoProfile db User {userId} p = do createdAt <- getCurrentTime createIncognitoProfile_ db userId createdAt p -createPreparedContact :: DB.Connection -> StoreCxt -> User -> Profile -> ACreatedConnLink -> Maybe SharedMsgId -> ExceptT StoreError IO Contact -createPreparedContact db cxt user p connLinkToConnect welcomeSharedMsgId = do +createPreparedContact :: DB.Connection -> StoreCxt -> User -> Profile -> ACreatedConnLink -> Maybe SharedMsgId -> Maybe Bool -> ExceptT StoreError IO Contact +createPreparedContact db cxt user p connLinkToConnect welcomeSharedMsgId verified_ = do currentTs <- liftIO getCurrentTime let prepared = Just (connLinkToConnect, welcomeSharedMsgId) ctUserPreferences = newContactUserPrefs user p - contactId <- createContact_ db cxt user p ctUserPreferences prepared "" currentTs - getContact db cxt user contactId + ct <- getContact db cxt user =<< createContact_ db cxt user p ctUserPreferences prepared "" currentTs + liftIO $ maybe (pure ct) (setContactDomainVerified db user ct) verified_ updatePreparedContactUser :: DB.Connection -> StoreCxt -> User -> Contact -> User -> ExceptT StoreError IO Contact updatePreparedContactUser @@ -559,22 +565,41 @@ updateContactProfile :: DB.Connection -> StoreCxt -> User -> Contact -> Profile updateContactProfile db cxt user@User {userId} c p' = do currentTs <- liftIO getCurrentTime badgeVerified <- liftIO $ profileBadgeVerified (badgeKeys cxt) lp p' - let profile = toLocalProfile profileId p' localAlias currentTs badgeVerified + let nameVerified = if claimChanged then Nothing else prevVerification + profile = toLocalProfile profileId p'' localAlias currentTs badgeVerified nameVerified updateContactProfile' currentTs badgeVerified profile where - Contact {contactId, localDisplayName, profile = lp@LocalProfile {profileId, displayName, localAlias}, userPreferences} = c - Profile {displayName = newName, preferences} = p' + Contact {contactId, localDisplayName, profile = lp@LocalProfile {profileId, displayName, localAlias, contactDomain = prevClaim, contactDomainVerified = prevVerification}, userPreferences} = c + Profile {displayName = newName, contactDomain, preferences} = p' mergedPreferences = contactUserPreferences user userPreferences preferences $ contactConnIncognito c + claimChanged = (domain <$> prevClaim) /= (domain <$> contactDomain) + p'' = (p' :: Profile) {contactDomain = (\d -> d {proof = if claimChanged then Nothing else proof =<< prevClaim}) <$> contactDomain} + clearVerificationIfClaimChanged = + when claimChanged $ + DB.execute db "UPDATE contact_profiles SET contact_domain_verified = NULL WHERE user_id = ? AND contact_profile_id = ?" (userId, profileId) updateContactProfile' currentTs badgeVerified profile | displayName == newName = do - liftIO $ updateContactProfile_' db userId profileId p' badgeVerified currentTs + liftIO $ updateContactProfile_' db userId profileId p'' badgeVerified currentTs + liftIO clearVerificationIfClaimChanged pure c {profile, mergedPreferences} | otherwise = ExceptT . withLocalDisplayName db userId newName $ \ldn -> do - updateContactProfile_' db userId profileId p' badgeVerified currentTs + updateContactProfile_' db userId profileId p'' badgeVerified currentTs updateContactLDN_ db user contactId localDisplayName ldn currentTs + clearVerificationIfClaimChanged pure $ Right c {localDisplayName = ldn, profile, mergedPreferences} +setContactDomainVerified :: DB.Connection -> User -> Contact -> Bool -> IO Contact +setContactDomainVerified db User {userId} ct@Contact {contactId, profile = p} verified = do + DB.execute + db + [sql| + UPDATE contact_profiles SET contact_domain_verified = ? + WHERE contact_profile_id IN (SELECT contact_profile_id FROM contacts WHERE user_id = ? AND contact_id = ?) + |] + (BI verified, userId, contactId) + pure (ct {profile = p {contactDomainVerified = Just verified}} :: Contact) + updateContactUserPreferences :: DB.Connection -> User -> Contact -> Preferences -> IO Contact updateContactUserPreferences db user@User {userId} c@Contact {contactId} userPreferences = do updatedAt <- getCurrentTime @@ -706,16 +731,17 @@ updateContactProfile_ db userId profileId profile badgeVerified = do updateContactProfile_' db userId profileId profile badgeVerified currentTs updateContactProfile_' :: DB.Connection -> UserId -> ProfileId -> Profile -> Maybe Bool -> UTCTime -> IO () -updateContactProfile_' db userId profileId Profile {displayName, fullName, shortDescr, image, contactLink, preferences, peerType, badge} badgeVerified updatedAt = +updateContactProfile_' db userId profileId Profile {displayName, fullName, shortDescr, image, contactLink, contactDomain, preferences, peerType, badge} badgeVerified updatedAt = DB.execute db [sql| UPDATE contact_profiles SET display_name = ?, full_name = ?, short_descr = ?, image = ?, contact_link = ?, preferences = ?, chat_peer_type = ?, updated_at = ?, - badge_proof = ?, badge_pres_header = ?, badge_expiry = ?, badge_type = ?, badge_verified = ?, badge_extra = ?, badge_master_key = ?, badge_signature = ?, badge_key_idx = ? + badge_proof = ?, badge_pres_header = ?, badge_expiry = ?, badge_type = ?, badge_verified = ?, badge_extra = ?, badge_master_key = ?, badge_signature = ?, badge_key_idx = ?, + contact_domain = ?, contact_domain_proof = ? WHERE user_id = ? AND contact_profile_id = ? |] - ((displayName, fullName, shortDescr, image, contactLink, preferences, peerType, updatedAt) :. badgeToRow badge badgeVerified :. (userId, profileId)) + ((displayName, fullName, shortDescr, image, contactLink, preferences, peerType, updatedAt) :. badgeToRow badge badgeVerified :. contactDomainToRow contactDomain :. (userId, profileId)) -- update only member profile fields (when member doesn't have associated contact - we can reset contactLink and prefs) updateMemberContactProfileReset_ :: DB.Connection -> UserId -> ProfileId -> Profile -> Maybe Bool -> IO () @@ -724,16 +750,17 @@ updateMemberContactProfileReset_ db userId profileId profile badgeVerified = do updateMemberContactProfileReset_' db userId profileId profile badgeVerified currentTs updateMemberContactProfileReset_' :: DB.Connection -> UserId -> ProfileId -> Profile -> Maybe Bool -> UTCTime -> IO () -updateMemberContactProfileReset_' db userId profileId Profile {displayName, fullName, shortDescr, image, badge} badgeVerified updatedAt = +updateMemberContactProfileReset_' db userId profileId Profile {displayName, fullName, shortDescr, image, contactDomain, badge} badgeVerified updatedAt = DB.execute db [sql| UPDATE contact_profiles SET display_name = ?, full_name = ?, short_descr = ?, image = ?, contact_link = NULL, preferences = NULL, updated_at = ?, - badge_proof = ?, badge_pres_header = ?, badge_expiry = ?, badge_type = ?, badge_verified = ?, badge_extra = ?, badge_master_key = ?, badge_signature = ?, badge_key_idx = ? + badge_proof = ?, badge_pres_header = ?, badge_expiry = ?, badge_type = ?, badge_verified = ?, badge_extra = ?, badge_master_key = ?, badge_signature = ?, badge_key_idx = ?, + contact_domain = ?, contact_domain_proof = ? WHERE user_id = ? AND contact_profile_id = ? |] - ((displayName, fullName, shortDescr, image, updatedAt) :. badgeToRow badge badgeVerified :. (userId, profileId)) + ((displayName, fullName, shortDescr, image, updatedAt) :. badgeToRow badge badgeVerified :. contactDomainToRow contactDomain :. (userId, profileId)) -- update only member profile fields (when member has associated contact - we keep contactLink and prefs) updateMemberContactProfile_ :: DB.Connection -> UserId -> ProfileId -> Profile -> Maybe Bool -> IO () @@ -742,16 +769,17 @@ updateMemberContactProfile_ db userId profileId profile badgeVerified = do updateMemberContactProfile_' db userId profileId profile badgeVerified currentTs updateMemberContactProfile_' :: DB.Connection -> UserId -> ProfileId -> Profile -> Maybe Bool -> UTCTime -> IO () -updateMemberContactProfile_' db userId profileId Profile {displayName, fullName, shortDescr, image, badge} badgeVerified updatedAt = +updateMemberContactProfile_' db userId profileId Profile {displayName, fullName, shortDescr, image, contactDomain, badge} badgeVerified updatedAt = DB.execute db [sql| UPDATE contact_profiles SET display_name = ?, full_name = ?, short_descr = ?, image = ?, updated_at = ?, - badge_proof = ?, badge_pres_header = ?, badge_expiry = ?, badge_type = ?, badge_verified = ?, badge_extra = ?, badge_master_key = ?, badge_signature = ?, badge_key_idx = ? + badge_proof = ?, badge_pres_header = ?, badge_expiry = ?, badge_type = ?, badge_verified = ?, badge_extra = ?, badge_master_key = ?, badge_signature = ?, badge_key_idx = ?, + contact_domain = ?, contact_domain_proof = ? WHERE user_id = ? AND contact_profile_id = ? |] - ((displayName, fullName, shortDescr, image, updatedAt) :. badgeToRow badge badgeVerified :. (userId, profileId)) + ((displayName, fullName, shortDescr, image, updatedAt) :. badgeToRow badge badgeVerified :. contactDomainToRow contactDomain :. (userId, profileId)) updateContactLDN_ :: DB.Connection -> User -> Int64 -> ContactName -> ContactName -> UTCTime -> IO () updateContactLDN_ db user@User {userId} contactId displayName newName updatedAt = do @@ -770,6 +798,22 @@ getContactByName db cxt user localDisplayName = do cId <- getContactIdByName db user localDisplayName getContact db cxt user cId +getContactToConnect :: DB.Connection -> StoreCxt -> User -> ContactNameOrLink -> ExceptT StoreError IO (Maybe (CreatedLinkContact, Contact)) +getContactToConnect db cxt user@User {userId} = \case + CTLink sl -> first (`CCLink` Just sl) <$$> getContactViaShortLinkToConnect db cxt user sl + CTName ni -> + liftIO (maybeFirstRow id $ DB.query db byNameQuery (userId, nameDomain ni)) >>= \case + Just (ctId :: Int64, Just (ACR cMode cReq), Just (sLnk :: ShortLinkContact)) | Just Refl <- testEquality cMode SCMContact -> + Just . (CCLink cReq (Just sLnk),) <$> getContact db cxt user ctId + _ -> pure Nothing + where + byNameQuery = + [sql| + SELECT ct.contact_id, ct.conn_full_link_to_connect, ct.conn_short_link_to_connect FROM contacts ct + JOIN contact_profiles cp ON cp.contact_profile_id = ct.contact_profile_id + WHERE ct.user_id = ? AND cp.contact_domain = ? AND cp.contact_domain_verified = 1 AND ct.deleted = 0 + |] + getUserContacts :: DB.Connection -> StoreCxt -> User -> IO [Contact] getUserContacts db cxt user@User {userId} = do contactIds <- map fromOnly <$> DB.query db "SELECT contact_id FROM contacts WHERE user_id = ? AND deleted = 0" (Only userId) @@ -809,7 +853,8 @@ contactRequestQuery = cr.pq_support, cr.welcome_shared_msg_id, cr.request_shared_msg_id, p.preferences, cr.created_at, cr.updated_at, cr.peer_chat_min_version, cr.peer_chat_max_version, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.contact_domain, p.contact_domain_proof, p.contact_domain_verified FROM contact_requests cr JOIN contact_profiles p USING (contact_profile_id) |] @@ -930,6 +975,7 @@ getContact_ db cxt user@User {userId} contactId deleted = do ct.contact_group_member_id, ct.contact_grp_inv_sent, ct.grp_direct_inv_link, ct.grp_direct_inv_from_group_id, ct.grp_direct_inv_from_group_member_id, ct.grp_direct_inv_from_member_conn_id, ct.grp_direct_inv_started_connection, ct.ui_themes, ct.chat_deleted, ct.custom_data, ct.chat_item_ttl, cp.badge_proof, cp.badge_pres_header, cp.badge_expiry, cp.badge_type, cp.badge_verified, cp.badge_extra, cp.badge_master_key, cp.badge_signature, cp.badge_key_idx, + cp.contact_domain, cp.contact_domain_proof, cp.contact_domain_verified, -- Connection c.connection_id, c.agent_conn_id, c.conn_level, c.via_contact, c.via_user_contact_link, c.via_group_link, c.group_link_id, c.xcontact_id, c.custom_user_profile_id, c.conn_status, c.conn_type, c.contact_conn_initiated, c.local_alias, c.contact_id, c.group_member_id, c.user_contact_link_id, c.created_at, c.security_code, c.security_code_verified_at, c.pq_support, c.pq_encryption, c.pq_snd_enabled, c.pq_rcv_enabled, c.auth_err_counter, c.quota_err_counter, diff --git a/src/Simplex/Chat/Store/Groups.hs b/src/Simplex/Chat/Store/Groups.hs index 60531cc1dc..d6f51fadc3 100644 --- a/src/Simplex/Chat/Store/Groups.hs +++ b/src/Simplex/Chat/Store/Groups.hs @@ -42,16 +42,18 @@ module Simplex.Chat.Store.Groups setGroupInvitationChatItemId, getGroup, getGroupInfoByUserContactLinkConnReq, - getGroupInfoViaUserShortLink, + getGroupInfoViaUserTarget, getGroupViaShortLinkToConnect, getGroupInfoByGroupLinkHash, updateGroupProfile, + setGroupDomainVerified, updateGroupPreferences, updateGroupProfileFromMember, getGroupIdByName, getGroupMemberIdByName, getActiveMembersByName, getGroupInfoByName, + getGroupToConnect, getGroupMember, getHostMember, getMentionedGroupMember, @@ -90,7 +92,12 @@ module Simplex.Chat.Store.Groups getPublishableGroupRelays, setGroupRosterVersion, getGroupRosterVersion, - getGroupRoster, + getStoredRosterVersion, + setMemberRosterServedVersion, + getMemberRosterServedVersion, + setCompleteRosterVersion, + getCompleteRosterVersion, + getStoredGroupRoster, RcvRosterTransfer (..), createRosterTransfer, getRosterTransferVersion, @@ -205,7 +212,7 @@ import Control.Monad import Control.Monad.Except import Control.Monad.IO.Class import Crypto.Random (ChaChaDRG) -import Data.Bifunctor (second) +import Data.Bifunctor (first, second) import Data.ByteString (ByteString) import qualified Data.ByteString as B import Data.Char (toLower) @@ -220,6 +227,7 @@ import qualified Data.Text as T import Data.Time.Clock (NominalDiffTime, UTCTime (..), addUTCTime, getCurrentTime) import Data.Text.Encoding (encodeUtf8) import Simplex.Chat.Badges (BadgeRow, badgeToRow, verifyBadge_) +import Simplex.Chat.Names (SimplexDomainClaim (..)) import Simplex.Chat.Messages import Simplex.Chat.Operators import Simplex.Chat.Protocol hiding (Binary) @@ -230,7 +238,7 @@ import Simplex.Chat.Types.MemberRelations (IntroductionDirection (..), MemberRel import Simplex.Chat.Types.Preferences import Simplex.Chat.Types.Shared import Simplex.Chat.Types.UITheme -import Simplex.Messaging.Agent.Protocol (ConfirmationId, ConnId, CreatedConnLink (..), InvitationId, OwnerAuth (..), UserId) +import Simplex.Messaging.Agent.Protocol (ConfirmationId, ConnId, CreatedConnLink (..), InvitationId, OwnerAuth (..), SimplexNameInfo (..), SimplexNameType (..), UserId) import Simplex.Messaging.Agent.Store.AgentStore (firstRow, fromOnlyBI, maybeFirstRow) import qualified Simplex.FileTransfer.Description as FD import Simplex.Messaging.Encoding (smpDecode, smpEncode) @@ -251,11 +259,11 @@ import Database.SQLite.Simple (Only (..), Query, (:.) (..)) import Database.SQLite.Simple.QQ (sql) #endif -type MaybeGroupMemberRow = (Maybe GroupMemberId, Maybe GroupId, Maybe Int64, Maybe MemberId, Maybe VersionChat, Maybe VersionChat, Maybe GroupMemberRole, Maybe GroupMemberCategory, Maybe GroupMemberStatus, Maybe BoolInt, Maybe MemberRestrictionStatus) :. (Maybe Int64, Maybe GroupMemberId, Maybe ContactName, Maybe ContactId, Maybe ProfileId) :. ((Maybe ProfileId, Maybe ContactName, Maybe Text, Maybe Text, Maybe ImageData, Maybe ConnLinkContact, Maybe ChatPeerType, Maybe LocalAlias, Maybe Preferences) :. BadgeRow) :. (Maybe UTCTime, Maybe UTCTime) :. (Maybe UTCTime, Maybe Int64, Maybe Int64, Maybe Int64, Maybe UTCTime, Maybe C.PublicKeyEd25519, Maybe ShortLinkContact) +type MaybeGroupMemberRow = (Maybe GroupMemberId, Maybe GroupId, Maybe Int64, Maybe MemberId, Maybe VersionChat, Maybe VersionChat, Maybe GroupMemberRole, Maybe GroupMemberCategory, Maybe GroupMemberStatus, Maybe BoolInt, Maybe MemberRestrictionStatus) :. (Maybe Int64, Maybe GroupMemberId, Maybe ContactName, Maybe ContactId, Maybe ProfileId) :. ((Maybe ProfileId, Maybe ContactName, Maybe Text, Maybe Text, Maybe ImageData, Maybe ConnLinkContact, Maybe ChatPeerType, Maybe LocalAlias, Maybe Preferences) :. BadgeRow :. ContactDomainRow) :. (Maybe UTCTime, Maybe UTCTime) :. (Maybe UTCTime, Maybe Int64, Maybe Int64, Maybe Int64, Maybe UTCTime, Maybe C.PublicKeyEd25519, Maybe ShortLinkContact) toMaybeGroupMember :: UTCTime -> Int64 -> MaybeGroupMemberRow -> Maybe GroupMember -toMaybeGroupMember now userContactId ((Just groupMemberId, Just groupId, Just indexInGroup, Just memberId, Just minVer, Just maxVer, Just memberRole, Just memberCategory, Just memberStatus, Just showMessages, memberBlocked') :. (invitedById, invitedByGroupMemberId, Just localDisplayName, memberContactId, Just memberContactProfileId) :. ((Just profileId, Just displayName, Just fullName, shortDescr, image, contactLink, peerType, Just localAlias, contactPreferences) :. badgeRow) :. (Just createdAt, Just updatedAt) :. (supportChatTs, Just supportChatUnread, Just supportChatUnanswered, Just supportChatMentions, supportChatLastMsgFromMemberTs, memberPubKey, relayLink)) = - Just $ toGroupMember now userContactId ((groupMemberId, groupId, indexInGroup, memberId, minVer, maxVer, memberRole, memberCategory, memberStatus, showMessages, memberBlocked') :. (invitedById, invitedByGroupMemberId, localDisplayName, memberContactId, memberContactProfileId) :. ((profileId, displayName, fullName, shortDescr, image, contactLink, peerType, localAlias, contactPreferences) :. badgeRow) :. (createdAt, updatedAt) :. (supportChatTs, supportChatUnread, supportChatUnanswered, supportChatMentions, supportChatLastMsgFromMemberTs, memberPubKey, relayLink)) +toMaybeGroupMember now userContactId ((Just groupMemberId, Just groupId, Just indexInGroup, Just memberId, Just minVer, Just maxVer, Just memberRole, Just memberCategory, Just memberStatus, Just showMessages, memberBlocked') :. (invitedById, invitedByGroupMemberId, Just localDisplayName, memberContactId, Just memberContactProfileId) :. ((Just profileId, Just displayName, Just fullName, shortDescr, image, contactLink, peerType, Just localAlias, contactPreferences) :. badgeRow :. domainRow) :. (Just createdAt, Just updatedAt) :. (supportChatTs, Just supportChatUnread, Just supportChatUnanswered, Just supportChatMentions, supportChatLastMsgFromMemberTs, memberPubKey, relayLink)) = + Just $ toGroupMember now userContactId ((groupMemberId, groupId, indexInGroup, memberId, minVer, maxVer, memberRole, memberCategory, memberStatus, showMessages, memberBlocked') :. (invitedById, invitedByGroupMemberId, localDisplayName, memberContactId, memberContactProfileId) :. ((profileId, displayName, fullName, shortDescr, image, contactLink, peerType, localAlias, contactPreferences) :. badgeRow :. domainRow) :. (createdAt, updatedAt) :. (supportChatTs, supportChatUnread, supportChatUnanswered, supportChatMentions, supportChatLastMsgFromMemberTs, memberPubKey, relayLink)) toMaybeGroupMember _ _ _ = Nothing createGroupLink :: DB.Connection -> TVar ChaChaDRG -> User -> GroupInfo -> ConnId -> CreatedLinkContact -> GroupLinkId -> GroupMemberRole -> SubscriptionMode -> ExceptT StoreError IO GroupLink @@ -395,9 +403,9 @@ createNewGroup db cxt user@User {userId} groupProfile incognitoProfile useRelays INSERT INTO group_profiles (display_name, full_name, short_descr, description, image, group_type, group_link, public_group_id, - group_web_page, group_domain, domain_web_page, allow_embedding, + group_web_page, group_domain, domain_web_page, allow_embedding, group_domain_proof, user_id, preferences, member_admission, created_at, updated_at) - VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) |] ((displayName, fullName, shortDescr, description, image, groupType_, groupLink_, publicGroupId_) :. publicGroupAccessRow publicGroup :. (userId, groupPreferences, memberAdmission, currentTs, currentTs)) @@ -443,7 +451,8 @@ createNewGroup db cxt user@User {userId} groupProfile incognitoProfile useRelays customData = Nothing, membersRequireAttention = 0, viaGroupLinkUri = Nothing, - groupKeys + groupKeys, + groupDomainVerified = Nothing } -- | creates a new group record for the group the current user was invited to, or returns an existing one @@ -521,7 +530,8 @@ createGroupInvitation db cxt user@User {userId} contact@Contact {contactId, acti customData = Nothing, membersRequireAttention = 0, viaGroupLinkUri = Nothing, - groupKeys = Nothing + groupKeys = Nothing, + groupDomainVerified = Nothing }, groupMemberId ) @@ -637,8 +647,8 @@ deleteContactCardKeepConn db connId Contact {contactId, profile = LocalProfile { DB.execute db "DELETE FROM contacts WHERE contact_id = ?" (Only contactId) DB.execute db "DELETE FROM contact_profiles WHERE contact_profile_id = ?" (Only profileId) -createPreparedGroup :: DB.Connection -> TVar ChaChaDRG -> StoreCxt -> User -> GroupProfile -> Bool -> CreatedLinkContact -> Maybe SharedMsgId -> Bool -> GroupMemberRole -> Maybe Int64 -> ExceptT StoreError IO (GroupInfo, Maybe GroupMember) -createPreparedGroup db gVar cxt user@User {userId, userContactId} groupProfile business connLinkToConnect welcomeSharedMsgId useRelays userMemberRole publicMemberCount_ = do +createPreparedGroup :: DB.Connection -> TVar ChaChaDRG -> StoreCxt -> User -> GroupProfile -> Bool -> CreatedLinkContact -> Maybe SharedMsgId -> Bool -> GroupMemberRole -> Maybe Int64 -> Maybe Bool -> ExceptT StoreError IO (GroupInfo, Maybe GroupMember) +createPreparedGroup db gVar cxt user@User {userId, userContactId} groupProfile business connLinkToConnect welcomeSharedMsgId useRelays userMemberRole publicMemberCount_ verified_ = do currentTs <- liftIO getCurrentTime let prepared = Just (connLinkToConnect, welcomeSharedMsgId) (groupId, groupLDN) <- createGroup_ db userId groupProfile prepared Nothing useRelays Nothing publicMemberCount_ currentTs @@ -657,7 +667,8 @@ createPreparedGroup db gVar cxt user@User {userId, userContactId} groupProfile b forM_ hostMember_ $ \hostMember -> when business $ liftIO $ setGroupBusinessChatInfo groupId membership hostMember g <- getGroupInfo db cxt user groupId - pure (g, hostMember_) + g' <- liftIO $ maybe (pure g) (setGroupDomainVerified db user g) verified_ + pure (g', hostMember_) where insertHost_ currentTs groupId groupLDN = do randHostId <- liftIO $ encodedRandomBytes gVar 12 @@ -899,9 +910,9 @@ createGroup_ db userId groupProfile prepared business useRelays relayOwnStatus p INSERT INTO group_profiles (display_name, full_name, short_descr, description, image, group_type, group_link, public_group_id, - group_web_page, group_domain, domain_web_page, allow_embedding, + group_web_page, group_domain, domain_web_page, allow_embedding, group_domain_proof, user_id, preferences, member_admission, created_at, updated_at) - VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) |] ((displayName, fullName, shortDescr, description, image, groupType_, groupLink_, publicGroupId_) :. publicGroupAccessRow publicGroup :. (userId, groupPreferences, memberAdmission, currentTs, currentTs)) @@ -1068,6 +1079,26 @@ getGroupInfoByName db cxt user gName = do gId <- getGroupIdByName db user gName getGroupInfo db cxt user gId +getGroupToConnect :: DB.Connection -> StoreCxt -> User -> ContactNameOrLink -> ExceptT StoreError IO (Maybe (CreatedLinkContact, GroupInfo)) +getGroupToConnect db cxt user@User {userId} = \case + CTLink sl -> first (`CCLink` Just sl) <$$> getGroupViaShortLinkToConnect db cxt user sl + CTName ni -> + -- @name is a business (presents as a contact); #name is a channel. The same domain can have both, + -- so the group type must match the requested name type. + let businessCond = case nameType ni of + NTContact -> " AND g.business_chat IS NOT NULL" + NTPublicGroup -> " AND g.business_chat IS NULL" + in liftIO (maybeFirstRow id $ DB.query db (byNameQuery <> businessCond) (userId, nameDomain ni)) >>= \case + Just (gId :: Int64, Just cReq, Just (sLnk :: ShortLinkContact)) -> Just . (CCLink cReq (Just sLnk),) <$> getGroupInfo db cxt user gId + _ -> pure Nothing + where + byNameQuery = + [sql| + SELECT g.group_id, g.conn_full_link_to_connect, g.conn_short_link_to_connect FROM groups g + JOIN group_profiles gp ON gp.group_profile_id = g.group_profile_id + WHERE g.user_id = ? AND gp.group_domain = ? AND g.group_domain_verified = 1 + |] + getGroupMember :: DB.Connection -> StoreCxt -> User -> GroupId -> GroupMemberId -> ExceptT StoreError IO GroupMember getGroupMember db cxt user@User {userId} groupId groupMemberId = do currentTs <- liftIO getCurrentTime @@ -1478,21 +1509,57 @@ getGroupRosterVersion db GroupInfo {groupId} = fmap join . maybeFirstRow fromOnly $ DB.query db "SELECT roster_version FROM groups WHERE group_id = ?" (Only groupId) --- The live roster header a relay re-serves to joiners, with the completed blob served alongside it --- (both are written together at completion, so the blob is present whenever the header is). -getGroupRoster :: DB.Connection -> GroupInfo -> IO (Maybe (GroupMemberId, UTCTime, SignedMsg, Maybe ByteString)) -getGroupRoster db GroupInfo {groupId} = +-- The version of the roster blob actually stored (written with the blob in setGroupLiveRoster), as opposed to +-- roster_version (the acceptance gate). The owner sends the blob before the delta, so these normally match; a +-- failed blob send leaves the gate (advanced by the delta) ahead of the stored blob until a later roster completes. +getStoredRosterVersion :: DB.Connection -> GroupInfo -> IO (Maybe VersionRoster) +getStoredRosterVersion db GroupInfo {groupId} = + fmap join . maybeFirstRow fromOnly $ + DB.query db "SELECT stored_roster_version FROM groups WHERE group_id = ?" (Only groupId) + +-- The newest roster version a relay re-served to this member on its catch-up request: bounds reflected +-- amplification, so a member can't re-trigger a full serve at a version it was already served. +setMemberRosterServedVersion :: DB.Connection -> GroupMember -> VersionRoster -> IO () +setMemberRosterServedVersion db GroupMember {groupMemberId} v = do + currentTs <- getCurrentTime + DB.execute db "UPDATE group_members SET roster_served_version = ?, updated_at = ? WHERE group_member_id = ?" (v, currentTs, groupMemberId) + +getMemberRosterServedVersion :: DB.Connection -> GroupMember -> IO (Maybe VersionRoster) +getMemberRosterServedVersion db GroupMember {groupMemberId} = + fmap join . maybeFirstRow fromOnly $ + DB.query db "SELECT roster_served_version FROM group_members WHERE group_member_id = ?" (Only groupMemberId) + +-- The highest version up to which the subscriber holds a complete, contiguous picture: advances by 1 on a +-- contiguous delta and to the roster's version on a roster apply, but stays put on a gapped delta (so a stuck +-- value re-triggers the catch-up request on every following delta until a roster fills the gap). This is the +-- subscriber's "what I have" for both gap detection and the request - as opposed to roster_version (highest seen, +-- the revert gate) and stored_roster_version (the blob a relay holds). +setCompleteRosterVersion :: DB.Connection -> GroupInfo -> VersionRoster -> IO () +setCompleteRosterVersion db GroupInfo {groupId} v = do + currentTs <- getCurrentTime + DB.execute db "UPDATE groups SET applied_complete_roster_version = ?, updated_at = ? WHERE group_id = ?" (v, currentTs, groupId) + +getCompleteRosterVersion :: DB.Connection -> GroupInfo -> IO (Maybe VersionRoster) +getCompleteRosterVersion db GroupInfo {groupId} = + fmap join . maybeFirstRow fromOnly $ + DB.query db "SELECT applied_complete_roster_version FROM groups WHERE group_id = ?" (Only groupId) + +-- The live roster header a relay re-serves to joiners, with the completed blob and its stored version +-- (all written together at completion, so the blob and version are present whenever the header is). +-- Returns the stored version, not roster_version (the gate), so callers serve/record exactly what they hold. +getStoredGroupRoster :: DB.Connection -> GroupInfo -> IO (Maybe (GroupMemberId, UTCTime, SignedMsg, Maybe ByteString, Maybe VersionRoster)) +getStoredGroupRoster db GroupInfo {groupId} = (>>= toRoster) <$> maybeFirstRow id ( DB.query db - "SELECT roster_sending_owner_gm_id, roster_broker_ts, roster_msg_chat_binding, roster_msg_signatures, roster_msg_body, roster_blob FROM groups WHERE group_id = ?" + "SELECT roster_sending_owner_gm_id, roster_broker_ts, roster_msg_chat_binding, roster_msg_signatures, roster_msg_body, roster_blob, stored_roster_version FROM groups WHERE group_id = ?" (Only groupId) ) where - toRoster (Just ownerGMId, Just brokerTs, Just cb, Just (Binary sigsBs), Just (Binary body), blob_) = - (\sigs -> (ownerGMId, brokerTs, SignedMsg cb sigs body, (\(Binary b) -> b) <$> blob_)) <$> eitherToMaybe (smpDecode sigsBs) + toRoster (Just ownerGMId, Just brokerTs, Just cb, Just (Binary sigsBs), Just (Binary body), blob_, storedVer_) = + (\sigs -> (ownerGMId, brokerTs, SignedMsg cb sigs body, (\(Binary b) -> b) <$> blob_, storedVer_)) <$> eitherToMaybe (smpDecode sigsBs) toRoster _ = Nothing -- A per-source in-flight roster transfer, keyed (group_id, from_member_id): replaces the single @@ -1577,6 +1644,10 @@ getRosterTransfer db fileId = -- Write the single live roster on groups from a completed transfer's values (header NULL on a member, -- so its live roster_msg_* stay NULL and it never re-serves; only relays re-serve). +-- Sets all three versions to the completed blob's version: the gate (roster_version - refuse anything older), +-- the stored version (stored_roster_version - the blob actually held and re-served), and the complete frontier +-- (applied_complete_roster_version - a snapshot makes the picture complete up to its version). Deltas advance the +-- gate always and the complete frontier only when contiguous, so complete <= stored <= roster_version normally. setGroupLiveRoster :: DB.Connection -> GroupInfo -> VersionRoster -> GroupMemberId -> UTCTime -> Maybe SignedMsg -> ByteString -> IO () setGroupLiveRoster db GroupInfo {groupId} v ownerGMId brokerTs sm_ blob = do currentTs <- getCurrentTime @@ -1584,13 +1655,13 @@ setGroupLiveRoster db GroupInfo {groupId} v ownerGMId brokerTs sm_ blob = do db [sql| UPDATE groups SET - roster_version = ?, roster_blob = ?, + roster_version = ?, stored_roster_version = ?, applied_complete_roster_version = ?, roster_blob = ?, roster_sending_owner_gm_id = ?, roster_broker_ts = ?, roster_msg_chat_binding = ?, roster_msg_signatures = ?, roster_msg_body = ?, updated_at = ? WHERE group_id = ? |] - ( (v, Binary blob, ownerGMId, brokerTs) + ( (v, v, v, Binary blob, ownerGMId, brokerTs) :. ((\SignedMsg {chatBinding} -> chatBinding) <$> sm_, (\SignedMsg {signatures} -> Binary (smpEncode signatures)) <$> sm_, (\SignedMsg {signedBody} -> Binary signedBody) <$> sm_, currentTs, groupId) ) @@ -1929,7 +2000,7 @@ getRelayPublishableGroups db User {userId, userContactId} = db [sql| SELECT g.group_id, gp.public_group_id, - gp.group_web_page, gp.group_domain, gp.domain_web_page, gp.allow_embedding + gp.group_web_page, gp.group_domain, gp.domain_web_page, gp.allow_embedding, gp.group_domain_proof FROM groups g JOIN group_profiles gp ON gp.group_profile_id = g.group_profile_id JOIN group_members mu ON mu.group_id = g.group_id AND mu.contact_id = ? @@ -2432,7 +2503,7 @@ createNewMember_ invitedBy, invitedByGroupMemberId = memInvitedByGroupMemberId, localDisplayName, - memberProfile = toLocalProfile memberContactProfileId memberProfile "" createdAt badgeVerified, + memberProfile = toLocalProfile memberContactProfileId memberProfile "" createdAt badgeVerified Nothing, memberContactId, memberContactProfileId, activeConn, @@ -2619,19 +2690,27 @@ createMemberConnection_ db userId groupMemberId agentConnId chatV peerChatVRange createConnection_ db userId ConnMember (Just groupMemberId) agentConnId ConnNew chatV peerChatVRange viaContact Nothing Nothing connLevel currentTs subMode PQSupportOff updateGroupProfile :: DB.Connection -> User -> GroupInfo -> GroupProfile -> ExceptT StoreError IO GroupInfo -updateGroupProfile db user@User {userId} g@GroupInfo {groupId, localDisplayName, groupProfile = GroupProfile {displayName}} p'@GroupProfile {displayName = newName, fullName, shortDescr, description, image, publicGroup, groupPreferences, memberAdmission} +updateGroupProfile db user@User {userId} g@GroupInfo {groupId, localDisplayName, groupProfile = GroupProfile {displayName, publicGroup = oldPublicGroup}} p'@GroupProfile {displayName = newName, fullName, shortDescr, description, image, publicGroup, groupPreferences, memberAdmission} | displayName == newName = liftIO $ do currentTs <- getCurrentTime updateGroupProfile_ currentTs - pure (g :: GroupInfo) {groupProfile = p', fullGroupPreferences} + clearVerificationIfClaimChanged + pure $ (g' :: GroupInfo) {groupProfile = p', fullGroupPreferences} | otherwise = ExceptT . withLocalDisplayName db userId newName $ \ldn -> do currentTs <- getCurrentTime updateGroupProfile_ currentTs updateGroup_ ldn currentTs - pure $ Right (g :: GroupInfo) {localDisplayName = ldn, groupProfile = p', fullGroupPreferences} + clearVerificationIfClaimChanged + pure $ Right $ (g' :: GroupInfo) {localDisplayName = ldn, groupProfile = p', fullGroupPreferences} where fullGroupPreferences = mergeGroupPreferences groupPreferences + groupClaim pg = domain <$> (pg >>= publicGroupAccess >>= groupDomainClaim) + claimChanged = groupClaim oldPublicGroup /= groupClaim publicGroup + g' = if claimChanged then (g :: GroupInfo) {groupDomainVerified = Nothing} else g + clearVerificationIfClaimChanged = + when claimChanged $ + DB.execute db "UPDATE groups SET group_domain_verified = NULL WHERE user_id = ? AND group_id = ?" (userId, groupId) (groupType_, groupLink_) = case publicGroup of Just PublicGroupProfile {groupType, groupLink} -> (Just groupType, Just groupLink) Nothing -> (Nothing, Nothing) @@ -2642,7 +2721,7 @@ updateGroupProfile db user@User {userId} g@GroupInfo {groupId, localDisplayName, UPDATE group_profiles SET display_name = ?, full_name = ?, short_descr = ?, description = ?, image = ?, group_type = ?, group_link = ?, - group_web_page = ?, group_domain = ?, domain_web_page = ?, allow_embedding = ?, + group_web_page = ?, group_domain = ?, domain_web_page = ?, allow_embedding = ?, group_domain_proof = ?, preferences = ?, member_admission = ?, updated_at = ? WHERE group_profile_id IN ( SELECT group_profile_id @@ -2658,6 +2737,14 @@ updateGroupProfile db user@User {userId} g@GroupInfo {groupId, localDisplayName, (ldn, currentTs, userId, groupId) safeDeleteLDN db user localDisplayName +setGroupDomainVerified :: DB.Connection -> User -> GroupInfo -> Bool -> IO GroupInfo +setGroupDomainVerified db User {userId} g@GroupInfo {groupId} verified = do + DB.execute + db + "UPDATE groups SET group_domain_verified = ? WHERE user_id = ? AND group_id = ?" + (BI verified, userId, groupId) + pure g {groupDomainVerified = Just verified} + updateGroupPreferences :: DB.Connection -> User -> GroupInfo -> GroupPreferences -> IO GroupInfo updateGroupPreferences db User {userId} g@GroupInfo {groupId, groupProfile = p} ps = do currentTs <- getCurrentTime @@ -2690,7 +2777,7 @@ updateGroupProfileFromMember db user g@GroupInfo {groupId} Profile {displayName [sql| SELECT gp.display_name, gp.full_name, gp.short_descr, gp.description, gp.image, gp.group_type, gp.group_link, gp.public_group_id, - gp.group_web_page, gp.group_domain, gp.domain_web_page, gp.allow_embedding, + gp.group_web_page, gp.group_domain, gp.domain_web_page, gp.allow_embedding, gp.group_domain_proof, gp.preferences, gp.member_admission FROM group_profiles gp JOIN groups g ON gp.group_profile_id = g.group_profile_id @@ -2716,24 +2803,36 @@ getGroupInfoByUserContactLinkConnReq db cxt user@User {userId} (cReqSchema1, cRe (userId, cReqSchema1, cReqSchema2) maybe (pure Nothing) (fmap eitherToMaybe . runExceptT . getGroupInfo db cxt user) groupId_ -getGroupInfoViaUserShortLink :: DB.Connection -> StoreCxt -> User -> ShortLinkContact -> IO (Maybe (ConnReqContact, GroupInfo)) -getGroupInfoViaUserShortLink db cxt user@User {userId} shortLink = fmap eitherToMaybe $ runExceptT $ do - (cReq, groupId) <- ExceptT getConnReqGroup - (cReq,) <$> getGroupInfo db cxt user groupId +getGroupInfoViaUserTarget :: DB.Connection -> StoreCxt -> User -> ContactNameOrLink -> IO (Maybe (CreatedLinkContact, GroupInfo)) +getGroupInfoViaUserTarget db cxt user@User {userId} target = fmap eitherToMaybe $ runExceptT $ do + (cReq, sLnk, groupId) <- ExceptT getConnReqGroup + (CCLink cReq (Just sLnk),) <$> getGroupInfo db cxt user groupId where getConnReqGroup = - firstRow' toConnReqGroupId (SEInternalError "group link not found") $ - DB.query - db - [sql| - SELECT conn_req_contact, group_id - FROM user_contact_links - WHERE user_id = ? AND short_link_contact = ? - |] - (userId, shortLink) + firstRow' toConnReqGroupId (SEInternalError "group link not found") $ case target of + CTLink shortLink -> + DB.query + db + [sql| + SELECT conn_req_contact, short_link_contact, group_id + FROM user_contact_links + WHERE user_id = ? AND short_link_contact = ? + |] + (userId, shortLink) + CTName ni -> + DB.query + db + [sql| + SELECT ucl.conn_req_contact, ucl.short_link_contact, ucl.group_id + FROM user_contact_links ucl + JOIN groups g ON g.group_id = ucl.group_id + JOIN group_profiles gp ON gp.group_profile_id = g.group_profile_id + WHERE ucl.user_id = ? AND gp.group_domain = ? + |] + (userId, nameDomain ni) toConnReqGroupId = \case -- cReq is "not null", group_id is nullable - (cReq, Just groupId) -> Right (cReq, groupId) + (cReq, Just (sLnk :: ShortLinkContact), Just groupId) -> Right (cReq, sLnk, groupId) _ -> Left $ SEInternalError "no conn req or group ID" getGroupViaShortLinkToConnect :: DB.Connection -> StoreCxt -> User -> ShortLinkContact -> ExceptT StoreError IO (Maybe (ConnReqContact, GroupInfo)) @@ -3286,7 +3385,7 @@ updateMemberProfile :: DB.Connection -> StoreCxt -> User -> GroupMember -> Profi updateMemberProfile db cxt user@User {userId} m p' = do currentTs <- liftIO getCurrentTime badgeVerified <- liftIO $ profileBadgeVerified (badgeKeys cxt) (memberProfile m) p' - let memberProfile = toLocalProfile profileId p' localAlias currentTs badgeVerified + let memberProfile = toLocalProfile profileId p' localAlias currentTs badgeVerified Nothing updateMemberProfile' currentTs badgeVerified memberProfile where GroupMember {groupMemberId, localDisplayName, memberProfile = LocalProfile {profileId, displayName, localAlias}} = m @@ -3309,7 +3408,7 @@ updateContactMemberProfile :: DB.Connection -> StoreCxt -> User -> GroupMember - updateContactMemberProfile db cxt user@User {userId} m ct@Contact {contactId} p' = do currentTs <- liftIO getCurrentTime badgeVerified <- liftIO $ profileBadgeVerified (badgeKeys cxt) (memberProfile m) p' - let profile = toLocalProfile profileId p' localAlias currentTs badgeVerified + let profile = toLocalProfile profileId p' localAlias currentTs badgeVerified Nothing updateContactMemberProfile' currentTs badgeVerified profile where GroupMember {localDisplayName, memberProfile = LocalProfile {profileId, displayName, localAlias}} = m diff --git a/src/Simplex/Chat/Store/Messages.hs b/src/Simplex/Chat/Store/Messages.hs index 644d73137d..3ddc04253a 100644 --- a/src/Simplex/Chat/Store/Messages.hs +++ b/src/Simplex/Chat/Store/Messages.hs @@ -715,7 +715,7 @@ getChatItemQuote_ db User {userId, userContactId} chatDirection QuotedMsg {msgRe m.group_member_id, m.group_id, m.index_in_group, m.member_id, m.peer_chat_min_version, m.peer_chat_max_version, m.member_role, m.member_category, m.member_status, m.show_messages, m.member_restriction, m.invited_by, m.invited_by_group_member_id, m.local_display_name, m.contact_id, m.contact_profile_id, p.contact_profile_id, p.display_name, p.full_name, p.short_descr, p.image, p.contact_link, p.chat_peer_type, p.local_alias, p.preferences, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified, m.created_at, m.updated_at, m.support_chat_ts, m.support_chat_items_unread, m.support_chat_items_member_attention, m.support_chat_items_mentions, m.support_chat_last_msg_from_member_ts, m.member_pub_key, m.relay_link FROM group_members m @@ -1139,7 +1139,7 @@ getContactRequestChatPreviews_ db User {userId} pagination clq = do cr.pq_support, cr.welcome_shared_msg_id, cr.request_shared_msg_id, p.preferences, cr.created_at, cr.updated_at, cr.peer_chat_min_version, cr.peer_chat_max_version, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified FROM contact_requests cr JOIN contact_profiles p ON p.contact_profile_id = cr.contact_profile_id JOIN user_contact_links uc ON uc.user_contact_link_id = cr.user_contact_link_id @@ -3070,7 +3070,7 @@ getGroupChatItem db User {userId, userContactId} groupId itemId = ExceptT $ do m.group_member_id, m.group_id, m.index_in_group, m.member_id, m.peer_chat_min_version, m.peer_chat_max_version, m.member_role, m.member_category, m.member_status, m.show_messages, m.member_restriction, m.invited_by, m.invited_by_group_member_id, m.local_display_name, m.contact_id, m.contact_profile_id, p.contact_profile_id, p.display_name, p.full_name, p.short_descr, p.image, p.contact_link, p.chat_peer_type, p.local_alias, p.preferences, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified, m.created_at, m.updated_at, m.support_chat_ts, m.support_chat_items_unread, m.support_chat_items_member_attention, m.support_chat_items_mentions, m.support_chat_last_msg_from_member_ts, m.member_pub_key, m.relay_link, -- quoted ChatItem @@ -3079,14 +3079,14 @@ getGroupChatItem db User {userId, userContactId} groupId itemId = ExceptT $ do rm.group_member_id, rm.group_id, rm.index_in_group, rm.member_id, rm.peer_chat_min_version, rm.peer_chat_max_version, rm.member_role, rm.member_category, rm.member_status, rm.show_messages, rm.member_restriction, rm.invited_by, rm.invited_by_group_member_id, rm.local_display_name, rm.contact_id, rm.contact_profile_id, rp.contact_profile_id, rp.display_name, rp.full_name, rp.short_descr, rp.image, rp.contact_link, rp.chat_peer_type, rp.local_alias, rp.preferences, - rp.badge_proof, rp.badge_pres_header, rp.badge_expiry, rp.badge_type, rp.badge_verified, rp.badge_extra, rp.badge_master_key, rp.badge_signature, rp.badge_key_idx, + rp.badge_proof, rp.badge_pres_header, rp.badge_expiry, rp.badge_type, rp.badge_verified, rp.badge_extra, rp.badge_master_key, rp.badge_signature, rp.badge_key_idx, rp.contact_domain, rp.contact_domain_proof, rp.contact_domain_verified, rm.created_at, rm.updated_at, rm.support_chat_ts, rm.support_chat_items_unread, rm.support_chat_items_member_attention, rm.support_chat_items_mentions, rm.support_chat_last_msg_from_member_ts, rm.member_pub_key, rm.relay_link, -- deleted by GroupMember dbm.group_member_id, dbm.group_id, dbm.index_in_group, dbm.member_id, dbm.peer_chat_min_version, dbm.peer_chat_max_version, dbm.member_role, dbm.member_category, dbm.member_status, dbm.show_messages, dbm.member_restriction, dbm.invited_by, dbm.invited_by_group_member_id, dbm.local_display_name, dbm.contact_id, dbm.contact_profile_id, dbp.contact_profile_id, dbp.display_name, dbp.full_name, dbp.short_descr, dbp.image, dbp.contact_link, dbp.chat_peer_type, dbp.local_alias, dbp.preferences, - dbp.badge_proof, dbp.badge_pres_header, dbp.badge_expiry, dbp.badge_type, dbp.badge_verified, dbp.badge_extra, dbp.badge_master_key, dbp.badge_signature, dbp.badge_key_idx, + dbp.badge_proof, dbp.badge_pres_header, dbp.badge_expiry, dbp.badge_type, dbp.badge_verified, dbp.badge_extra, dbp.badge_master_key, dbp.badge_signature, dbp.badge_key_idx, dbp.contact_domain, dbp.contact_domain_proof, dbp.contact_domain_verified, dbm.created_at, dbm.updated_at, dbm.support_chat_ts, dbm.support_chat_items_unread, dbm.support_chat_items_member_attention, dbm.support_chat_items_mentions, dbm.support_chat_last_msg_from_member_ts, dbm.member_pub_key, dbm.relay_link FROM chat_items i diff --git a/src/Simplex/Chat/Store/Postgres/Migrations.hs b/src/Simplex/Chat/Store/Postgres/Migrations.hs index 4b814d0434..a3335640a2 100644 --- a/src/Simplex/Chat/Store/Postgres/Migrations.hs +++ b/src/Simplex/Chat/Store/Postgres/Migrations.hs @@ -38,6 +38,8 @@ import Simplex.Chat.Store.Postgres.Migrations.M20260530_client_services import Simplex.Chat.Store.Postgres.Migrations.M20260531_member_removed_at import Simplex.Chat.Store.Postgres.Migrations.M20260601_relay_sent_web_domain import Simplex.Chat.Store.Postgres.Migrations.M20260602_group_roster +import Simplex.Chat.Store.Postgres.Migrations.M20260603_simplex_name +import Simplex.Chat.Store.Postgres.Migrations.M20260629_roster_catchup import Simplex.Messaging.Agent.Store.Shared (Migration (..)) schemaMigrations :: [(String, Text, Maybe Text)] @@ -75,7 +77,9 @@ schemaMigrations = ("20260530_client_services", m20260530_client_services, Just down_m20260530_client_services), ("20260531_member_removed_at", m20260531_member_removed_at, Just down_m20260531_member_removed_at), ("20260601_relay_sent_web_domain", m20260601_relay_sent_web_domain, Just down_m20260601_relay_sent_web_domain), - ("20260602_group_roster", m20260602_group_roster, Just down_m20260602_group_roster) + ("20260602_group_roster", m20260602_group_roster, Just down_m20260602_group_roster), + ("20260603_simplex_name", m20260603_simplex_name, Just down_m20260603_simplex_name), + ("20260629_roster_catchup", m20260629_roster_catchup, Just down_m20260629_roster_catchup) ] -- | The list of migrations in ascending order by date diff --git a/src/Simplex/Chat/Store/Postgres/Migrations/M20260603_simplex_name.hs b/src/Simplex/Chat/Store/Postgres/Migrations/M20260603_simplex_name.hs new file mode 100644 index 0000000000..14a0ae2a05 --- /dev/null +++ b/src/Simplex/Chat/Store/Postgres/Migrations/M20260603_simplex_name.hs @@ -0,0 +1,38 @@ +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE QuasiQuotes #-} + +module Simplex.Chat.Store.Postgres.Migrations.M20260603_simplex_name where + +import Data.Text (Text) +import Text.RawString.QQ (r) + +m20260603_simplex_name :: Text +m20260603_simplex_name = + [r| +ALTER TABLE contact_profiles ADD COLUMN contact_domain TEXT; +ALTER TABLE contact_profiles ADD COLUMN contact_domain_proof TEXT; +ALTER TABLE contact_profiles ADD COLUMN contact_domain_verified SMALLINT; + +ALTER TABLE group_profiles ADD COLUMN group_domain_proof TEXT; +ALTER TABLE groups ADD COLUMN group_domain_verified SMALLINT; + +ALTER TABLE user_contact_links ADD COLUMN link_priv_sig_key BYTEA; + +ALTER TABLE server_operators ADD COLUMN smp_role_names SMALLINT NOT NULL DEFAULT 0; +UPDATE server_operators SET smp_role_names = 1 WHERE server_operator_tag = 'simplex' OR server_operator_tag = 'flux'; +|] + +down_m20260603_simplex_name :: Text +down_m20260603_simplex_name = + [r| +ALTER TABLE contact_profiles DROP COLUMN contact_domain; +ALTER TABLE contact_profiles DROP COLUMN contact_domain_proof; +ALTER TABLE contact_profiles DROP COLUMN contact_domain_verified; + +ALTER TABLE group_profiles DROP COLUMN group_domain_proof; +ALTER TABLE groups DROP COLUMN group_domain_verified; + +ALTER TABLE user_contact_links DROP COLUMN link_priv_sig_key; + +ALTER TABLE server_operators DROP COLUMN smp_role_names; +|] diff --git a/src/Simplex/Chat/Store/Postgres/Migrations/M20260629_roster_catchup.hs b/src/Simplex/Chat/Store/Postgres/Migrations/M20260629_roster_catchup.hs new file mode 100644 index 0000000000..f5b94e7d0b --- /dev/null +++ b/src/Simplex/Chat/Store/Postgres/Migrations/M20260629_roster_catchup.hs @@ -0,0 +1,41 @@ +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE QuasiQuotes #-} + +module Simplex.Chat.Store.Postgres.Migrations.M20260629_roster_catchup where + +import Data.Text (Text) +import Text.RawString.QQ (r) + +-- Roster catch-up bookkeeping. Three monotonic per-group roster versions with distinct roles - normally equal, +-- diverging across gaps and failed transfers (applied_complete <= stored <= roster_version): +-- roster_version (added in M20260602) - the GATE: highest version seen. Advanced by every accepted owner delta +-- and by a roster apply. Revert protection: a completing roster older than this is rejected, since its +-- snapshot would undo a newer applied delta. +-- stored_roster_version - the blob HELD: the version of the roster blob actually stored (written with the blob). +-- What a relay can re-serve; a failed blob receive leaves it behind the gate (which the delta still advances) +-- until a later roster completes. Relay-side; on a member it is set but the blob is unused. +-- applied_complete_roster_version - the COMPLETE frontier: highest version up to which the picture is contiguous. +-- Advances by 1 on a contiguous delta and to the roster's version on apply, but stays put on a gapped delta. +-- The subscriber's "what I have" for gap detection and the catch-up request: a value below the gate means +-- missed versions, so each following delta re-asks the forwarding relay until a roster fills the frontier. +-- Also adds group_members.roster_served_version - the newest version a relay re-served a given member, bounding +-- reflected amplification (a member can't re-trigger a full serve at a version it was already served). +-- Backfill an existing roster's stored and complete versions from roster_version: pre-upgrade the picture is +-- contiguous up to roster_version (no gap detection existed), so a fresh NULL frontier would read every group's +-- next delta as a gap and make every subscriber request a re-serve at once. +m20260629_roster_catchup :: Text +m20260629_roster_catchup = + [r| +ALTER TABLE group_members ADD COLUMN roster_served_version BIGINT; +ALTER TABLE groups ADD COLUMN stored_roster_version BIGINT; +ALTER TABLE groups ADD COLUMN applied_complete_roster_version BIGINT; +UPDATE groups SET stored_roster_version = roster_version, applied_complete_roster_version = roster_version WHERE roster_version IS NOT NULL; +|] + +down_m20260629_roster_catchup :: Text +down_m20260629_roster_catchup = + [r| +ALTER TABLE group_members DROP COLUMN roster_served_version; +ALTER TABLE groups DROP COLUMN stored_roster_version; +ALTER TABLE groups DROP COLUMN applied_complete_roster_version; +|] diff --git a/src/Simplex/Chat/Store/Postgres/Migrations/chat_schema.sql b/src/Simplex/Chat/Store/Postgres/Migrations/chat_schema.sql index 861224ff56..3b8e7530c8 100644 --- a/src/Simplex/Chat/Store/Postgres/Migrations/chat_schema.sql +++ b/src/Simplex/Chat/Store/Postgres/Migrations/chat_schema.sql @@ -540,7 +540,10 @@ CREATE TABLE test_chat_schema.contact_profiles ( badge_extra text, badge_master_key bytea, badge_signature bytea, - badge_key_idx bigint + badge_key_idx bigint, + contact_domain text, + contact_domain_proof text, + contact_domain_verified smallint ); @@ -831,7 +834,8 @@ CREATE TABLE test_chat_schema.group_members ( member_relations_vector bytea, relay_link bytea, member_pub_key bytea, - removed_at timestamp with time zone + removed_at timestamp with time zone, + roster_served_version bigint ); @@ -866,7 +870,8 @@ CREATE TABLE test_chat_schema.group_profiles ( group_web_page text, group_domain text, domain_web_page bigint, - allow_embedding bigint + allow_embedding bigint, + group_domain_proof text ); @@ -980,7 +985,7 @@ CREATE TABLE test_chat_schema.groups ( public_member_count bigint, relay_request_retries bigint DEFAULT 0 NOT NULL, relay_request_delay bigint DEFAULT 0 NOT NULL, - relay_request_execute_at timestamp with time zone DEFAULT '1970-01-01 04:00:00+04'::timestamp with time zone NOT NULL, + relay_request_execute_at timestamp with time zone DEFAULT '1970-01-01 01:00:00+01'::timestamp with time zone NOT NULL, relay_inactive_at timestamp with time zone, relay_sent_web_domain text, roster_version bigint, @@ -989,7 +994,10 @@ CREATE TABLE test_chat_schema.groups ( roster_msg_signatures bytea, roster_sending_owner_gm_id bigint, roster_broker_ts timestamp with time zone, - roster_blob bytea + roster_blob bytea, + group_domain_verified smallint, + stored_roster_version bigint, + applied_complete_roster_version bigint ); @@ -1377,7 +1385,8 @@ CREATE TABLE test_chat_schema.server_operators ( xftp_role_storage smallint DEFAULT 1 NOT NULL, xftp_role_proxy smallint DEFAULT 1 NOT NULL, created_at timestamp with time zone DEFAULT now() NOT NULL, - updated_at timestamp with time zone DEFAULT now() NOT NULL + updated_at timestamp with time zone DEFAULT now() NOT NULL, + smp_role_names smallint DEFAULT 0 NOT NULL ); @@ -1454,7 +1463,8 @@ CREATE TABLE test_chat_schema.user_contact_links ( business_address smallint DEFAULT 0, short_link_contact bytea, short_link_data_set smallint DEFAULT 0 NOT NULL, - short_link_large_data_set smallint DEFAULT 0 NOT NULL + short_link_large_data_set smallint DEFAULT 0 NOT NULL, + link_priv_sig_key bytea ); diff --git a/src/Simplex/Chat/Store/Profiles.hs b/src/Simplex/Chat/Store/Profiles.hs index 043897a995..522f966214 100644 --- a/src/Simplex/Chat/Store/Profiles.hs +++ b/src/Simplex/Chat/Store/Profiles.hs @@ -50,10 +50,11 @@ module Simplex.Chat.Store.Profiles getUserAddressConnection, deleteUserAddress, getUserAddress, + setUserSimplexDomain, getUserContactLinkById, getGroupLinkInfo, getUserContactLinkByConnReq, - getUserContactLinkViaShortLink, + getUserContactLinkViaTarget, setUserContactLinkShortLink, getContactWithoutConnViaAddress, getContactWithoutConnViaShortAddress, @@ -105,12 +106,13 @@ import Simplex.Chat.Operators import Simplex.Chat.Protocol import Simplex.Chat.Store.Direct import Simplex.Chat.Store.Shared +import Simplex.Chat.Names (claimDomain, mkDomainClaim) import Simplex.Chat.Types import Simplex.Chat.Types.Preferences import Simplex.Chat.Types.Shared import Simplex.Chat.Types.UITheme import Simplex.Messaging.Agent.Env.SQLite (ServerRoles (..)) -import Simplex.Messaging.Agent.Protocol (ACorrId, ConnId, ConnectionLink (..), CreatedConnLink (..), UserId) +import Simplex.Messaging.Agent.Protocol (ACorrId, ConnId, ConnectionLink (..), CreatedConnLink (..), SimplexDomain, SimplexNameInfo (..), UserId) import Simplex.Messaging.Agent.Store.AgentStore (firstRow, maybeFirstRow) import Simplex.Messaging.Agent.Store.DB (BoolInt (..)) import qualified Simplex.Messaging.Agent.Store.DB as DB @@ -161,7 +163,7 @@ createUserRecordAt db (AgentUserId auId) userChatRelay clientService Profile {di (profileId, displayName, userId, BI True, currentTs, currentTs, currentTs) contactId <- insertedRowId db DB.execute db "UPDATE users SET contact_id = ? WHERE user_id = ?" (contactId, userId) - pure $ toUser currentTs $ (userId, auId, contactId, profileId, BI activeUser, order) :. (displayName, fullName, shortDescr, image, Nothing, peerType, userPreferences) :. (BI showNtfs, BI sendRcptsContacts, BI sendRcptsSmallGroups, BI autoAcceptMemberContacts, Nothing, Nothing, Nothing, BI userChatRelay, BI clientService, Nothing) :. localBadgeToRow Nothing + pure $ toUser currentTs $ (userId, auId, contactId, profileId, BI activeUser, order) :. (displayName, fullName, shortDescr, image, Nothing, peerType, userPreferences) :. (BI showNtfs, BI sendRcptsContacts, BI sendRcptsSmallGroups, BI autoAcceptMemberContacts, Nothing, Nothing, Nothing, BI userChatRelay, BI clientService, Nothing) :. localBadgeToRow Nothing :. (Nothing, Nothing, Nothing) -- TODO [mentions] getUsersInfo :: DB.Connection -> IO [UserInfo] @@ -332,7 +334,7 @@ updateUserProfile db user p' currentTs <- getCurrentTime updateUserProfileFields_' db userId profileId p' currentTs userMemberProfileUpdatedAt' <- updateUserMemberProfileUpdatedAt_ currentTs - pure user {profile = (toLocalProfile profileId p' localAlias currentTs (Just False)) {localBadge}, fullPreferences, userMemberProfileUpdatedAt = userMemberProfileUpdatedAt'} + pure user {profile = (toLocalProfile profileId p' localAlias currentTs (Just False) Nothing) {localBadge}, fullPreferences, userMemberProfileUpdatedAt = userMemberProfileUpdatedAt'} | otherwise = checkConstraint SEDuplicateName . liftIO $ do currentTs <- getCurrentTime @@ -344,7 +346,7 @@ updateUserProfile db user p' (newName, newName, userId, currentTs, currentTs) updateUserProfileFields_' db userId profileId p' currentTs updateContactLDN_ db user userContactId localDisplayName newName currentTs - pure user {localDisplayName = newName, profile = (toLocalProfile profileId p' localAlias currentTs (Just False)) {localBadge}, fullPreferences, userMemberProfileUpdatedAt = userMemberProfileUpdatedAt'} + pure user {localDisplayName = newName, profile = (toLocalProfile profileId p' localAlias currentTs (Just False) Nothing) {localBadge}, fullPreferences, userMemberProfileUpdatedAt = userMemberProfileUpdatedAt'} where updateUserMemberProfileUpdatedAt_ currentTs | userMemberProfileChanged = do @@ -384,6 +386,15 @@ setUserBadge db user@User {userId, profile = p@LocalProfile {profileId}} localBa DB.execute db "UPDATE users SET user_member_profile_updated_at = ? WHERE user_id = ?" (ts, userId) pure (user :: User) {profile = p {localBadge}, userMemberProfileUpdatedAt = Just ts} +setUserSimplexDomain :: DB.Connection -> User -> Maybe SimplexDomain -> IO User +setUserSimplexDomain db user@User {userId, profile = p@LocalProfile {profileId}} domain_ = do + ts <- getCurrentTime + DB.execute + db + "UPDATE contact_profiles SET contact_domain = ?, updated_at = ? WHERE user_id = ? AND contact_profile_id = ?" + (domain_, ts, userId, profileId) + pure (user :: User) {profile = p {contactDomain = mkDomainClaim <$> domain_}} + setUserProfileContactLink :: DB.Connection -> User -> Maybe UserContactLink -> IO User setUserProfileContactLink db user@User {userId, profile = p@LocalProfile {profileId}} ucl_ = do ts <- getCurrentTime @@ -406,24 +417,24 @@ getUserContactProfiles db User {userId} = <$> DB.query db [sql| - SELECT display_name, full_name, short_descr, image, contact_link, chat_peer_type, preferences + SELECT display_name, full_name, short_descr, image, contact_link, chat_peer_type, contact_domain, preferences FROM contact_profiles WHERE user_id = ? |] (Only userId) where - toContactProfile :: (ContactName, Text, Maybe Text, Maybe ImageData, Maybe ConnLinkContact, Maybe ChatPeerType, Maybe Preferences) -> Profile - toContactProfile (displayName, fullName, shortDescr, image, contactLink, peerType, preferences) = Profile {displayName, fullName, shortDescr, image, contactLink, peerType, preferences, badge = Nothing} + toContactProfile :: (ContactName, Text, Maybe Text, Maybe ImageData, Maybe ConnLinkContact, Maybe ChatPeerType, Maybe SimplexDomain, Maybe Preferences) -> Profile + toContactProfile (displayName, fullName, shortDescr, image, contactLink, peerType, domain_, preferences) = Profile {displayName, fullName, shortDescr, image, contactLink, contactDomain = mkDomainClaim <$> domain_, peerType, preferences, badge = Nothing} -createUserContactLink :: DB.Connection -> User -> ConnId -> CreatedLinkContact -> SubscriptionMode -> ExceptT StoreError IO () -createUserContactLink db User {userId} agentConnId (CCLink cReq shortLink) subMode = +createUserContactLink :: DB.Connection -> User -> ConnId -> CreatedLinkContact -> SubscriptionMode -> C.PrivateKeyEd25519 -> ExceptT StoreError IO () +createUserContactLink db User {userId} agentConnId (CCLink cReq shortLink) subMode linkPrivSigKey = checkConstraint SEDuplicateContactLink . liftIO $ do currentTs <- getCurrentTime let slDataSet = BI (isJust shortLink) DB.execute db - "INSERT INTO user_contact_links (user_id, conn_req_contact, short_link_contact, short_link_data_set, short_link_large_data_set, created_at, updated_at) VALUES (?,?,?,?,?,?,?)" - (userId, cReq, shortLink, slDataSet, slDataSet, currentTs, currentTs) + "INSERT INTO user_contact_links (user_id, conn_req_contact, short_link_contact, short_link_data_set, short_link_large_data_set, link_priv_sig_key, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)" + (userId, cReq, shortLink, slDataSet, slDataSet, linkPrivSigKey, currentTs, currentTs) userContactLinkId <- insertedRowId db void $ createConnection_ db userId ConnUserContact (Just userContactLinkId) agentConnId ConnNew initialChatVersion chatInitialVRange Nothing Nothing Nothing 0 currentTs subMode CR.PQSupportOff @@ -546,10 +557,16 @@ getUserContactLinkByConnReq db User {userId} (cReqSchema1, cReqSchema2) = maybeFirstRow toUserContactLink $ DB.query db (userContactLinkQuery <> " WHERE user_id = ? AND conn_req_contact IN (?,?)") (userId, cReqSchema1, cReqSchema2) -getUserContactLinkViaShortLink :: DB.Connection -> User -> ShortLinkContact -> IO (Maybe UserContactLink) -getUserContactLinkViaShortLink db User {userId} shortLink = - maybeFirstRow toUserContactLink $ - DB.query db (userContactLinkQuery <> " WHERE user_id = ? AND short_link_contact = ?") (userId, shortLink) +getUserContactLinkViaTarget :: DB.Connection -> User -> ContactNameOrLink -> IO (Maybe UserContactLink) +getUserContactLinkViaTarget db User {userId, profile = LocalProfile {contactDomain}} = \case + CTLink shortLink -> + maybeFirstRow toUserContactLink $ + DB.query db (userContactLinkQuery <> " WHERE user_id = ? AND short_link_contact = ?") (userId, shortLink) + CTName ni + | (claimDomain <$> contactDomain) == Just (nameDomain ni) -> + maybeFirstRow toUserContactLink $ + DB.query db (userContactLinkQuery <> " WHERE user_id = ? AND group_id IS NULL AND short_link_contact IS NOT NULL") (Only userId) + | otherwise -> pure Nothing userContactLinkQuery :: Query userContactLinkQuery = @@ -752,10 +769,10 @@ updateServerOperator db currentTs ServerOperator {operatorId, enabled, smpRoles, db [sql| UPDATE server_operators - SET enabled = ?, smp_role_storage = ?, smp_role_proxy = ?, xftp_role_storage = ?, xftp_role_proxy = ?, updated_at = ? + SET enabled = ?, smp_role_storage = ?, smp_role_proxy = ?, smp_role_names = ?, xftp_role_storage = ?, xftp_role_proxy = ?, updated_at = ? WHERE server_operator_id = ? |] - (BI enabled, BI (storage smpRoles), BI (proxy smpRoles), BI (storage xftpRoles), BI (proxy xftpRoles), currentTs, operatorId) + (BI enabled, BI (storage smpRoles), BI (proxy smpRoles), BI (names smpRoles), BI (storage xftpRoles), BI (proxy xftpRoles), currentTs, operatorId) getUpdateServerOperators :: DB.Connection -> NonEmpty PresetOperator -> Bool -> IO [(Maybe PresetOperator, Maybe ServerOperator)] getUpdateServerOperators db presetOps newUser = do @@ -790,20 +807,20 @@ getUpdateServerOperators db presetOps newUser = do db [sql| UPDATE server_operators - SET trade_name = ?, legal_name = ?, server_domains = ?, enabled = ?, smp_role_storage = ?, smp_role_proxy = ?, xftp_role_storage = ?, xftp_role_proxy = ? + SET trade_name = ?, legal_name = ?, server_domains = ?, enabled = ?, smp_role_storage = ?, smp_role_proxy = ?, smp_role_names = ?, xftp_role_storage = ?, xftp_role_proxy = ? WHERE server_operator_id = ? |] - (tradeName, legalName, T.intercalate "," serverDomains, BI enabled, BI (storage smpRoles), BI (proxy smpRoles), BI (storage xftpRoles), BI (proxy xftpRoles), operatorId) + (tradeName, legalName, T.intercalate "," serverDomains, BI enabled, BI (storage smpRoles), BI (proxy smpRoles), BI (names smpRoles), BI (storage xftpRoles), BI (proxy xftpRoles), operatorId) insertOperator :: NewServerOperator -> IO ServerOperator insertOperator op@ServerOperator {operatorTag, tradeName, legalName, serverDomains, enabled, smpRoles, xftpRoles} = do DB.execute db [sql| INSERT INTO server_operators - (server_operator_tag, trade_name, legal_name, server_domains, enabled, smp_role_storage, smp_role_proxy, xftp_role_storage, xftp_role_proxy) - VALUES (?,?,?,?,?,?,?,?,?) + (server_operator_tag, trade_name, legal_name, server_domains, enabled, smp_role_storage, smp_role_proxy, smp_role_names, xftp_role_storage, xftp_role_proxy) + VALUES (?,?,?,?,?,?,?,?,?,?) |] - (operatorTag, tradeName, legalName, T.intercalate "," serverDomains, BI enabled, BI (storage smpRoles), BI (proxy smpRoles), BI (storage xftpRoles), BI (proxy xftpRoles)) + (operatorTag, tradeName, legalName, T.intercalate "," serverDomains, BI enabled, BI (storage smpRoles), BI (proxy smpRoles), BI (names smpRoles), BI (storage xftpRoles), BI (proxy xftpRoles)) opId <- insertedRowId db pure op {operatorId = DBEntityId opId} autoAcceptConditions op UsageConditions {conditionsCommit} now = @@ -814,14 +831,14 @@ serverOperatorQuery :: Query serverOperatorQuery = [sql| SELECT server_operator_id, server_operator_tag, trade_name, legal_name, - server_domains, enabled, smp_role_storage, smp_role_proxy, xftp_role_storage, xftp_role_proxy + server_domains, enabled, smp_role_storage, smp_role_proxy, smp_role_names, xftp_role_storage, xftp_role_proxy FROM server_operators |] getServerOperators_ :: DB.Connection -> IO [ServerOperator] getServerOperators_ db = map toServerOperator <$> DB.query_ db serverOperatorQuery -toServerOperator :: (DBEntityId, Maybe OperatorTag, Text, Maybe Text, Text, BoolInt) :. (BoolInt, BoolInt) :. (BoolInt, BoolInt) -> ServerOperator +toServerOperator :: (DBEntityId, Maybe OperatorTag, Text, Maybe Text, Text, BoolInt) :. (BoolInt, BoolInt, BoolInt) :. (BoolInt, BoolInt) -> ServerOperator toServerOperator ((operatorId, operatorTag, tradeName, legalName, domains, BI enabled) :. smpRoles' :. xftpRoles') = ServerOperator { operatorId, @@ -831,11 +848,12 @@ toServerOperator ((operatorId, operatorTag, tradeName, legalName, domains, BI en serverDomains = T.splitOn "," domains, conditionsAcceptance = CARequired Nothing, enabled, - smpRoles = serverRoles smpRoles', - xftpRoles = serverRoles xftpRoles' + smpRoles = serverRolesSMP smpRoles', + xftpRoles = serverRolesXFTP xftpRoles' } where - serverRoles (BI storage, BI proxy) = ServerRoles {storage, proxy} + serverRolesSMP (BI storage, BI proxy, BI names) = ServerRoles {storage, proxy, names} + serverRolesXFTP (BI storage, BI proxy) = ServerRoles {storage, proxy, names = False} getOperatorConditions_ :: DB.Connection -> ServerOperator -> UsageConditions -> Maybe UsageConditions -> UTCTime -> IO ConditionsAcceptance getOperatorConditions_ db ServerOperator {operatorId} UsageConditions {conditionsCommit = currentCommit, createdAt, notifiedAt} latestAcceptedConds_ now = do diff --git a/src/Simplex/Chat/Store/SQLite/Migrations.hs b/src/Simplex/Chat/Store/SQLite/Migrations.hs index c9dd316aee..d135c0f742 100644 --- a/src/Simplex/Chat/Store/SQLite/Migrations.hs +++ b/src/Simplex/Chat/Store/SQLite/Migrations.hs @@ -161,6 +161,8 @@ import Simplex.Chat.Store.SQLite.Migrations.M20260530_client_services import Simplex.Chat.Store.SQLite.Migrations.M20260531_member_removed_at import Simplex.Chat.Store.SQLite.Migrations.M20260601_relay_sent_web_domain import Simplex.Chat.Store.SQLite.Migrations.M20260602_group_roster +import Simplex.Chat.Store.SQLite.Migrations.M20260603_simplex_name +import Simplex.Chat.Store.SQLite.Migrations.M20260629_roster_catchup import Simplex.Messaging.Agent.Store.Shared (Migration (..)) schemaMigrations :: [(String, Query, Maybe Query)] @@ -321,7 +323,9 @@ schemaMigrations = ("20260530_client_services", m20260530_client_services, Just down_m20260530_client_services), ("20260531_member_removed_at", m20260531_member_removed_at, Just down_m20260531_member_removed_at), ("20260601_relay_sent_web_domain", m20260601_relay_sent_web_domain, Just down_m20260601_relay_sent_web_domain), - ("20260602_group_roster", m20260602_group_roster, Just down_m20260602_group_roster) + ("20260602_group_roster", m20260602_group_roster, Just down_m20260602_group_roster), + ("20260603_simplex_name", m20260603_simplex_name, Just down_m20260603_simplex_name), + ("20260629_roster_catchup", m20260629_roster_catchup, Just down_m20260629_roster_catchup) ] -- | The list of migrations in ascending order by date diff --git a/src/Simplex/Chat/Store/SQLite/Migrations/M20260603_simplex_name.hs b/src/Simplex/Chat/Store/SQLite/Migrations/M20260603_simplex_name.hs new file mode 100644 index 0000000000..112f06a0a1 --- /dev/null +++ b/src/Simplex/Chat/Store/SQLite/Migrations/M20260603_simplex_name.hs @@ -0,0 +1,37 @@ +{-# LANGUAGE QuasiQuotes #-} + +module Simplex.Chat.Store.SQLite.Migrations.M20260603_simplex_name where + +import Database.SQLite.Simple (Query) +import Database.SQLite.Simple.QQ (sql) + +m20260603_simplex_name :: Query +m20260603_simplex_name = + [sql| +ALTER TABLE contact_profiles ADD COLUMN contact_domain TEXT; +ALTER TABLE contact_profiles ADD COLUMN contact_domain_proof TEXT; +ALTER TABLE contact_profiles ADD COLUMN contact_domain_verified INTEGER; + +ALTER TABLE group_profiles ADD COLUMN group_domain_proof TEXT; +ALTER TABLE groups ADD COLUMN group_domain_verified INTEGER; + +ALTER TABLE user_contact_links ADD COLUMN link_priv_sig_key BLOB; + +ALTER TABLE server_operators ADD COLUMN smp_role_names INTEGER NOT NULL DEFAULT 0; +UPDATE server_operators SET smp_role_names = 1 WHERE server_operator_tag = 'simplex' OR server_operator_tag = 'flux'; +|] + +down_m20260603_simplex_name :: Query +down_m20260603_simplex_name = + [sql| +ALTER TABLE contact_profiles DROP COLUMN contact_domain; +ALTER TABLE contact_profiles DROP COLUMN contact_domain_proof; +ALTER TABLE contact_profiles DROP COLUMN contact_domain_verified; + +ALTER TABLE group_profiles DROP COLUMN group_domain_proof; +ALTER TABLE groups DROP COLUMN group_domain_verified; + +ALTER TABLE user_contact_links DROP COLUMN link_priv_sig_key; + +ALTER TABLE server_operators DROP COLUMN smp_role_names; +|] diff --git a/src/Simplex/Chat/Store/SQLite/Migrations/M20260629_roster_catchup.hs b/src/Simplex/Chat/Store/SQLite/Migrations/M20260629_roster_catchup.hs new file mode 100644 index 0000000000..1dacc665ea --- /dev/null +++ b/src/Simplex/Chat/Store/SQLite/Migrations/M20260629_roster_catchup.hs @@ -0,0 +1,40 @@ +{-# LANGUAGE QuasiQuotes #-} + +module Simplex.Chat.Store.SQLite.Migrations.M20260629_roster_catchup where + +import Database.SQLite.Simple (Query) +import Database.SQLite.Simple.QQ (sql) + +-- Roster catch-up bookkeeping. Three monotonic per-group roster versions with distinct roles - normally equal, +-- diverging across gaps and failed transfers (applied_complete <= stored <= roster_version): +-- roster_version (added in M20260602) - the GATE: highest version seen. Advanced by every accepted owner delta +-- and by a roster apply. Revert protection: a completing roster older than this is rejected, since its +-- snapshot would undo a newer applied delta. +-- stored_roster_version - the blob HELD: the version of the roster blob actually stored (written with the blob). +-- What a relay can re-serve; a failed blob receive leaves it behind the gate (which the delta still advances) +-- until a later roster completes. Relay-side; on a member it is set but the blob is unused. +-- applied_complete_roster_version - the COMPLETE frontier: highest version up to which the picture is contiguous. +-- Advances by 1 on a contiguous delta and to the roster's version on apply, but stays put on a gapped delta. +-- The subscriber's "what I have" for gap detection and the catch-up request: a value below the gate means +-- missed versions, so each following delta re-asks the forwarding relay until a roster fills the frontier. +-- Also adds group_members.roster_served_version - the newest version a relay re-served a given member, bounding +-- reflected amplification (a member can't re-trigger a full serve at a version it was already served). +-- Backfill an existing roster's stored and complete versions from roster_version: pre-upgrade the picture is +-- contiguous up to roster_version (no gap detection existed), so a fresh NULL frontier would read every group's +-- next delta as a gap and make every subscriber request a re-serve at once. +m20260629_roster_catchup :: Query +m20260629_roster_catchup = + [sql| +ALTER TABLE group_members ADD COLUMN roster_served_version INTEGER; +ALTER TABLE groups ADD COLUMN stored_roster_version INTEGER; +ALTER TABLE groups ADD COLUMN applied_complete_roster_version INTEGER; +UPDATE groups SET stored_roster_version = roster_version, applied_complete_roster_version = roster_version WHERE roster_version IS NOT NULL; +|] + +down_m20260629_roster_catchup :: Query +down_m20260629_roster_catchup = + [sql| +ALTER TABLE group_members DROP COLUMN roster_served_version; +ALTER TABLE groups DROP COLUMN stored_roster_version; +ALTER TABLE groups DROP COLUMN applied_complete_roster_version; +|] diff --git a/src/Simplex/Chat/Store/SQLite/Migrations/chat_query_plans.txt b/src/Simplex/Chat/Store/SQLite/Migrations/chat_query_plans.txt index eefcb8de57..5d7b56fc8f 100644 --- a/src/Simplex/Chat/Store/SQLite/Migrations/chat_query_plans.txt +++ b/src/Simplex/Chat/Store/SQLite/Migrations/chat_query_plans.txt @@ -125,7 +125,7 @@ Query: cp.preferences, ct.user_preferences, ct.created_at, ct.updated_at, ct.chat_ts, ct.conn_full_link_to_connect, ct.conn_short_link_to_connect, ct.welcome_shared_msg_id, ct.request_shared_msg_id, ct.contact_request_id, ct.contact_group_member_id, ct.contact_grp_inv_sent, ct.grp_direct_inv_link, ct.grp_direct_inv_from_group_id, ct.grp_direct_inv_from_group_member_id, ct.grp_direct_inv_from_member_conn_id, ct.grp_direct_inv_started_connection, ct.ui_themes, ct.chat_deleted, ct.custom_data, ct.chat_item_ttl, - cp.badge_proof, cp.badge_pres_header, cp.badge_expiry, cp.badge_type, cp.badge_verified, cp.badge_extra, cp.badge_master_key, cp.badge_signature, cp.badge_key_idx, + cp.badge_proof, cp.badge_pres_header, cp.badge_expiry, cp.badge_type, cp.badge_verified, cp.badge_extra, cp.badge_master_key, cp.badge_signature, cp.badge_key_idx, cp.contact_domain, cp.contact_domain_proof, cp.contact_domain_verified, -- Connection c.connection_id, c.agent_conn_id, c.conn_level, c.via_contact, c.via_user_contact_link, c.via_group_link, c.group_link_id, c.xcontact_id, c.custom_user_profile_id, c.conn_status, c.conn_type, c.contact_conn_initiated, c.local_alias, c.contact_id, c.group_member_id, c.user_contact_link_id, c.created_at, c.security_code, c.security_code_verified_at, c.pq_support, c.pq_encryption, c.pq_snd_enabled, c.pq_rcv_enabled, c.auth_err_counter, c.quota_err_counter, @@ -144,26 +144,26 @@ Query: SELECT -- GroupInfo g.group_id, g.local_display_name, gp.display_name, gp.full_name, gp.short_descr, g.local_alias, gp.description, gp.image, gp.group_type, gp.group_link, gp.public_group_id, - gp.group_web_page, gp.group_domain, gp.domain_web_page, gp.allow_embedding, + gp.group_web_page, gp.group_domain, gp.domain_web_page, gp.allow_embedding, gp.group_domain_proof, g.enable_ntfs, g.send_rcpts, g.favorite, gp.preferences, gp.member_admission, g.created_at, g.updated_at, g.chat_ts, g.user_member_profile_sent_at, g.conn_full_link_to_connect, g.conn_short_link_to_connect, g.conn_link_prepared_connection, g.conn_link_started_connection, g.welcome_shared_msg_id, g.request_shared_msg_id, g.business_chat, g.business_member_id, g.customer_member_id, g.use_relays, g.relay_own_status, - g.ui_themes, g.summary_current_members_count, g.public_member_count, g.roster_version, g.custom_data, g.chat_item_ttl, g.members_require_attention, g.via_group_link_uri, + g.ui_themes, g.summary_current_members_count, g.public_member_count, g.roster_version, g.custom_data, g.chat_item_ttl, g.members_require_attention, g.via_group_link_uri, g.group_domain_verified, g.root_priv_key, g.root_pub_key, g.member_priv_key, -- GroupInfo {membership} mu.group_member_id, mu.group_id, mu.index_in_group, mu.member_id, mu.peer_chat_min_version, mu.peer_chat_max_version, mu.member_role, mu.member_category, mu.member_status, mu.show_messages, mu.member_restriction, mu.invited_by, mu.invited_by_group_member_id, mu.local_display_name, mu.contact_id, mu.contact_profile_id, pu.contact_profile_id, -- GroupInfo {membership = GroupMember {memberProfile}} pu.display_name, pu.full_name, pu.short_descr, pu.image, pu.contact_link, pu.chat_peer_type, pu.local_alias, pu.preferences, - pu.badge_proof, pu.badge_pres_header, pu.badge_expiry, pu.badge_type, pu.badge_verified, pu.badge_extra, pu.badge_master_key, pu.badge_signature, pu.badge_key_idx, + pu.badge_proof, pu.badge_pres_header, pu.badge_expiry, pu.badge_type, pu.badge_verified, pu.badge_extra, pu.badge_master_key, pu.badge_signature, pu.badge_key_idx, pu.contact_domain, pu.contact_domain_proof, pu.contact_domain_verified, mu.created_at, mu.updated_at, mu.support_chat_ts, mu.support_chat_items_unread, mu.support_chat_items_member_attention, mu.support_chat_items_mentions, mu.support_chat_last_msg_from_member_ts, mu.member_pub_key, mu.relay_link, -- from GroupMember m.group_member_id, m.group_id, m.index_in_group, m.member_id, m.peer_chat_min_version, m.peer_chat_max_version, m.member_role, m.member_category, m.member_status, m.show_messages, m.member_restriction, m.invited_by, m.invited_by_group_member_id, m.local_display_name, m.contact_id, m.contact_profile_id, p.contact_profile_id, p.display_name, p.full_name, p.short_descr, p.image, p.contact_link, p.chat_peer_type, p.local_alias, p.preferences, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified, m.created_at, m.updated_at, m.support_chat_ts, m.support_chat_items_unread, m.support_chat_items_member_attention, m.support_chat_items_mentions, m.support_chat_last_msg_from_member_ts, m.member_pub_key, m.relay_link FROM group_members m @@ -401,7 +401,7 @@ Query: cr.pq_support, cr.welcome_shared_msg_id, cr.request_shared_msg_id, p.preferences, cr.created_at, cr.updated_at, cr.peer_chat_min_version, cr.peer_chat_max_version, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified FROM contact_requests cr JOIN contact_profiles p USING (contact_profile_id) WHERE cr.user_id = ? @@ -443,6 +443,14 @@ Query: Plan: SEARCH operator_usage_conditions USING INDEX idx_operator_usage_conditions_server_operator_id (server_operator_id=?) +Query: + SELECT conn_req_contact, short_link_contact, group_id + FROM user_contact_links + WHERE user_id = ? AND short_link_contact = ? + +Plan: +SEARCH user_contact_links USING INDEX sqlite_autoindex_user_contact_links_1 (user_id=?) + Query: SELECT timed_ttl FROM chat_items @@ -451,6 +459,18 @@ Query: Plan: SEARCH chat_items USING INTEGER PRIMARY KEY (rowid=?) +Query: + SELECT ucl.conn_req_contact, ucl.short_link_contact, ucl.group_id + FROM user_contact_links ucl + JOIN groups g ON g.group_id = ucl.group_id + JOIN group_profiles gp ON gp.group_profile_id = g.group_profile_id + WHERE ucl.user_id = ? AND gp.group_domain = ? + +Plan: +SEARCH ucl USING INDEX sqlite_autoindex_user_contact_links_1 (user_id=?) +SEARCH g USING INTEGER PRIMARY KEY (rowid=?) +SEARCH gp USING INTEGER PRIMARY KEY (rowid=?) + Query: UPDATE chat_items SET user_id = ?, updated_at = ? @@ -687,7 +707,8 @@ Query: p.preferences, c.user_preferences, c.created_at, c.updated_at, c.chat_ts, c.conn_full_link_to_connect, c.conn_short_link_to_connect, c.welcome_shared_msg_id, c.request_shared_msg_id, c.contact_request_id, c.contact_group_member_id, c.contact_grp_inv_sent, c.grp_direct_inv_link, c.grp_direct_inv_from_group_id, c.grp_direct_inv_from_group_member_id, c.grp_direct_inv_from_member_conn_id, c.grp_direct_inv_started_connection, c.ui_themes, c.chat_deleted, c.custom_data, c.chat_item_ttl, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.contact_domain, p.contact_domain_proof, p.contact_domain_verified FROM contacts c JOIN contact_profiles p ON c.contact_profile_id = p.contact_profile_id WHERE c.user_id = ? AND c.contact_id = ? AND c.contact_status = ? AND c.deleted = 0 @@ -907,14 +928,6 @@ Plan: SEARCH chat_items USING INDEX idx_chat_items_groups_item_viewed (user_id=?) USE TEMP B-TREE FOR ORDER BY -Query: - SELECT conn_req_contact, group_id - FROM user_contact_links - WHERE user_id = ? AND short_link_contact = ? - -Plan: -SEARCH user_contact_links USING INDEX sqlite_autoindex_user_contact_links_1 (user_id=?) - Query: SELECT conn_req_contact, group_id FROM user_contact_links @@ -994,7 +1007,7 @@ SEARCH delivery_tasks USING COVERING INDEX idx_delivery_tasks_next (group_id=? A Query: SELECT gp.display_name, gp.full_name, gp.short_descr, gp.description, gp.image, gp.group_type, gp.group_link, gp.public_group_id, - gp.group_web_page, gp.group_domain, gp.domain_web_page, gp.allow_embedding, + gp.group_web_page, gp.group_domain, gp.domain_web_page, gp.allow_embedding, gp.group_domain_proof, gp.preferences, gp.member_admission FROM group_profiles gp JOIN groups g ON gp.group_profile_id = g.group_profile_id @@ -1038,7 +1051,7 @@ Query: m.group_member_id, m.group_id, m.index_in_group, m.member_id, m.peer_chat_min_version, m.peer_chat_max_version, m.member_role, m.member_category, m.member_status, m.show_messages, m.member_restriction, m.invited_by, m.invited_by_group_member_id, m.local_display_name, m.contact_id, m.contact_profile_id, p.contact_profile_id, p.display_name, p.full_name, p.short_descr, p.image, p.contact_link, p.chat_peer_type, p.local_alias, p.preferences, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified, m.created_at, m.updated_at, m.support_chat_ts, m.support_chat_items_unread, m.support_chat_items_member_attention, m.support_chat_items_mentions, m.support_chat_last_msg_from_member_ts, m.member_pub_key, m.relay_link FROM group_members m @@ -1269,9 +1282,9 @@ Query: INSERT INTO group_profiles (display_name, full_name, short_descr, description, image, group_type, group_link, public_group_id, - group_web_page, group_domain, domain_web_page, allow_embedding, + group_web_page, group_domain, domain_web_page, allow_embedding, group_domain_proof, user_id, preferences, member_admission, created_at, updated_at) - VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) Plan: @@ -1303,8 +1316,8 @@ Plan: Query: INSERT INTO server_operators - (server_operator_tag, trade_name, legal_name, server_domains, enabled, smp_role_storage, smp_role_proxy, xftp_role_storage, xftp_role_proxy) - VALUES (?,?,?,?,?,?,?,?,?) + (server_operator_tag, trade_name, legal_name, server_domains, enabled, smp_role_storage, smp_role_proxy, smp_role_names, xftp_role_storage, xftp_role_proxy) + VALUES (?,?,?,?,?,?,?,?,?,?) Plan: @@ -1347,7 +1360,7 @@ Query: m.group_member_id, m.group_id, m.index_in_group, m.member_id, m.peer_chat_min_version, m.peer_chat_max_version, m.member_role, m.member_category, m.member_status, m.show_messages, m.member_restriction, m.invited_by, m.invited_by_group_member_id, m.local_display_name, m.contact_id, m.contact_profile_id, p.contact_profile_id, p.display_name, p.full_name, p.short_descr, p.image, p.contact_link, p.chat_peer_type, p.local_alias, p.preferences, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified, m.created_at, m.updated_at, m.support_chat_ts, m.support_chat_items_unread, m.support_chat_items_member_attention, m.support_chat_items_mentions, m.support_chat_last_msg_from_member_ts, m.member_pub_key, m.relay_link, -- quoted ChatItem @@ -1356,14 +1369,14 @@ Query: rm.group_member_id, rm.group_id, rm.index_in_group, rm.member_id, rm.peer_chat_min_version, rm.peer_chat_max_version, rm.member_role, rm.member_category, rm.member_status, rm.show_messages, rm.member_restriction, rm.invited_by, rm.invited_by_group_member_id, rm.local_display_name, rm.contact_id, rm.contact_profile_id, rp.contact_profile_id, rp.display_name, rp.full_name, rp.short_descr, rp.image, rp.contact_link, rp.chat_peer_type, rp.local_alias, rp.preferences, - rp.badge_proof, rp.badge_pres_header, rp.badge_expiry, rp.badge_type, rp.badge_verified, rp.badge_extra, rp.badge_master_key, rp.badge_signature, rp.badge_key_idx, + rp.badge_proof, rp.badge_pres_header, rp.badge_expiry, rp.badge_type, rp.badge_verified, rp.badge_extra, rp.badge_master_key, rp.badge_signature, rp.badge_key_idx, rp.contact_domain, rp.contact_domain_proof, rp.contact_domain_verified, rm.created_at, rm.updated_at, rm.support_chat_ts, rm.support_chat_items_unread, rm.support_chat_items_member_attention, rm.support_chat_items_mentions, rm.support_chat_last_msg_from_member_ts, rm.member_pub_key, rm.relay_link, -- deleted by GroupMember dbm.group_member_id, dbm.group_id, dbm.index_in_group, dbm.member_id, dbm.peer_chat_min_version, dbm.peer_chat_max_version, dbm.member_role, dbm.member_category, dbm.member_status, dbm.show_messages, dbm.member_restriction, dbm.invited_by, dbm.invited_by_group_member_id, dbm.local_display_name, dbm.contact_id, dbm.contact_profile_id, dbp.contact_profile_id, dbp.display_name, dbp.full_name, dbp.short_descr, dbp.image, dbp.contact_link, dbp.chat_peer_type, dbp.local_alias, dbp.preferences, - dbp.badge_proof, dbp.badge_pres_header, dbp.badge_expiry, dbp.badge_type, dbp.badge_verified, dbp.badge_extra, dbp.badge_master_key, dbp.badge_signature, dbp.badge_key_idx, + dbp.badge_proof, dbp.badge_pres_header, dbp.badge_expiry, dbp.badge_type, dbp.badge_verified, dbp.badge_extra, dbp.badge_master_key, dbp.badge_signature, dbp.badge_key_idx, dbp.contact_domain, dbp.contact_domain_proof, dbp.contact_domain_verified, dbm.created_at, dbm.updated_at, dbm.support_chat_ts, dbm.support_chat_items_unread, dbm.support_chat_items_member_attention, dbm.support_chat_items_mentions, dbm.support_chat_last_msg_from_member_ts, dbm.member_pub_key, dbm.relay_link FROM chat_items i @@ -1417,6 +1430,7 @@ Query: ct.contact_group_member_id, ct.contact_grp_inv_sent, ct.grp_direct_inv_link, ct.grp_direct_inv_from_group_id, ct.grp_direct_inv_from_group_member_id, ct.grp_direct_inv_from_member_conn_id, ct.grp_direct_inv_started_connection, ct.ui_themes, ct.chat_deleted, ct.custom_data, ct.chat_item_ttl, cp.badge_proof, cp.badge_pres_header, cp.badge_expiry, cp.badge_type, cp.badge_verified, cp.badge_extra, cp.badge_master_key, cp.badge_signature, cp.badge_key_idx, + cp.contact_domain, cp.contact_domain_proof, cp.contact_domain_verified, -- Connection c.connection_id, c.agent_conn_id, c.conn_level, c.via_contact, c.via_user_contact_link, c.via_group_link, c.group_link_id, c.xcontact_id, c.custom_user_profile_id, c.conn_status, c.conn_type, c.contact_conn_initiated, c.local_alias, c.contact_id, c.group_member_id, c.user_contact_link_id, c.created_at, c.security_code, c.security_code_verified_at, c.pq_support, c.pq_encryption, c.pq_snd_enabled, c.pq_rcv_enabled, c.auth_err_counter, c.quota_err_counter, @@ -1810,7 +1824,7 @@ Query: UPDATE group_profiles SET display_name = ?, full_name = ?, short_descr = ?, description = ?, image = ?, group_type = ?, group_link = ?, - group_web_page = ?, group_domain = ?, domain_web_page = ?, allow_embedding = ?, + group_web_page = ?, group_domain = ?, domain_web_page = ?, allow_embedding = ?, group_domain_proof = ?, preferences = ?, member_admission = ?, updated_at = ? WHERE group_profile_id IN ( SELECT group_profile_id @@ -1997,6 +2011,7 @@ Query: ct.contact_group_member_id, ct.contact_grp_inv_sent, ct.grp_direct_inv_link, ct.grp_direct_inv_from_group_id, ct.grp_direct_inv_from_group_member_id, ct.grp_direct_inv_from_member_conn_id, ct.grp_direct_inv_started_connection, ct.ui_themes, ct.chat_deleted, ct.custom_data, ct.chat_item_ttl, cp.badge_proof, cp.badge_pres_header, cp.badge_expiry, cp.badge_type, cp.badge_verified, cp.badge_extra, cp.badge_master_key, cp.badge_signature, cp.badge_key_idx, + cp.contact_domain, cp.contact_domain_proof, cp.contact_domain_verified, -- Connection c.connection_id, c.agent_conn_id, c.conn_level, c.via_contact, c.via_user_contact_link, c.via_group_link, c.group_link_id, c.xcontact_id, c.custom_user_profile_id, c.conn_status, c.conn_type, c.contact_conn_initiated, c.local_alias, c.contact_id, c.group_member_id, c.user_contact_link_id, c.created_at, c.security_code, c.security_code_verified_at, c.pq_support, c.pq_encryption, c.pq_snd_enabled, c.pq_rcv_enabled, c.auth_err_counter, c.quota_err_counter, @@ -2082,7 +2097,7 @@ Query: cr.pq_support, cr.welcome_shared_msg_id, cr.request_shared_msg_id, p.preferences, cr.created_at, cr.updated_at, cr.peer_chat_min_version, cr.peer_chat_max_version, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified FROM contact_requests cr JOIN contact_profiles p ON p.contact_profile_id = cr.contact_profile_id JOIN user_contact_links uc ON uc.user_contact_link_id = cr.user_contact_link_id @@ -2112,7 +2127,7 @@ Query: cr.pq_support, cr.welcome_shared_msg_id, cr.request_shared_msg_id, p.preferences, cr.created_at, cr.updated_at, cr.peer_chat_min_version, cr.peer_chat_max_version, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified FROM contact_requests cr JOIN contact_profiles p ON p.contact_profile_id = cr.contact_profile_id JOIN user_contact_links uc ON uc.user_contact_link_id = cr.user_contact_link_id @@ -2142,7 +2157,7 @@ Query: cr.pq_support, cr.welcome_shared_msg_id, cr.request_shared_msg_id, p.preferences, cr.created_at, cr.updated_at, cr.peer_chat_min_version, cr.peer_chat_max_version, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified FROM contact_requests cr JOIN contact_profiles p ON p.contact_profile_id = cr.contact_profile_id JOIN user_contact_links uc ON uc.user_contact_link_id = cr.user_contact_link_id @@ -3672,8 +3687,8 @@ Plan: SEARCH connections USING INTEGER PRIMARY KEY (rowid=?) Query: - SELECT cp.contact_profile_id, cp.display_name, cp.full_name, cp.short_descr, cp.image, cp.contact_link, cp.chat_peer_type, cp.local_alias, cp.preferences, - cp.badge_proof, cp.badge_pres_header, cp.badge_expiry, cp.badge_type, cp.badge_verified, cp.badge_extra, cp.badge_master_key, cp.badge_signature, cp.badge_key_idx + SELECT cp.contact_profile_id, cp.display_name, cp.full_name, cp.short_descr, cp.image, cp.contact_link, cp.chat_peer_type, cp.local_alias, cp.preferences, -- , ct.user_preferences + cp.badge_proof, cp.badge_pres_header, cp.badge_expiry, cp.badge_type, cp.badge_verified, cp.badge_extra, cp.badge_master_key, cp.badge_signature, cp.badge_key_idx, cp.contact_domain, cp.contact_domain_proof, cp.contact_domain_verified FROM contact_profiles cp WHERE cp.user_id = ? AND cp.contact_profile_id = ? @@ -3693,6 +3708,15 @@ Plan: SEARCH ct USING INDEX idx_contacts_chat_ts (user_id=?) SEARCH p USING INTEGER PRIMARY KEY (rowid=?) +Query: + SELECT ct.contact_id, ct.conn_full_link_to_connect, ct.conn_short_link_to_connect FROM contacts ct + JOIN contact_profiles cp ON cp.contact_profile_id = ct.contact_profile_id + WHERE ct.user_id = ? AND cp.contact_domain = ? AND cp.contact_domain_verified = 1 AND ct.deleted = 0 + +Plan: +SEARCH ct USING INDEX idx_contacts_chat_ts (user_id=?) +SEARCH cp USING INTEGER PRIMARY KEY (rowid=?) + Query: SELECT d.file_descr_id, d.file_descr_text, d.file_descr_part_no, d.file_descr_complete FROM xftp_file_descriptions d @@ -3716,7 +3740,7 @@ SEARCH f USING PRIMARY KEY (file_id=?) SEARCH d USING INTEGER PRIMARY KEY (rowid=?) Query: - SELECT display_name, full_name, short_descr, image, contact_link, chat_peer_type, preferences + SELECT display_name, full_name, short_descr, image, contact_link, chat_peer_type, contact_domain, preferences FROM contact_profiles WHERE user_id = ? @@ -3768,9 +3792,18 @@ Query: Plan: SEARCH files USING INTEGER PRIMARY KEY (rowid=?) +Query: + SELECT g.group_id, g.conn_full_link_to_connect, g.conn_short_link_to_connect FROM groups g + JOIN group_profiles gp ON gp.group_profile_id = g.group_profile_id + WHERE g.user_id = ? AND gp.group_domain = ? AND g.group_domain_verified = 1 + +Plan: +SEARCH g USING INDEX sqlite_autoindex_groups_2 (user_id=?) +SEARCH gp USING INTEGER PRIMARY KEY (rowid=?) + Query: SELECT g.group_id, gp.public_group_id, - gp.group_web_page, gp.group_domain, gp.domain_web_page, gp.allow_embedding + gp.group_web_page, gp.group_domain, gp.domain_web_page, gp.allow_embedding, gp.group_domain_proof FROM groups g JOIN group_profiles gp ON gp.group_profile_id = g.group_profile_id JOIN group_members mu ON mu.group_id = g.group_id AND mu.contact_id = ? @@ -5110,7 +5143,8 @@ SEARCH contact_profiles USING INTEGER PRIMARY KEY (rowid=?) Query: UPDATE contact_profiles SET display_name = ?, full_name = ?, short_descr = ?, image = ?, contact_link = ?, preferences = ?, chat_peer_type = ?, updated_at = ?, - badge_proof = ?, badge_pres_header = ?, badge_expiry = ?, badge_type = ?, badge_verified = ?, badge_extra = ?, badge_master_key = ?, badge_signature = ?, badge_key_idx = ? + badge_proof = ?, badge_pres_header = ?, badge_expiry = ?, badge_type = ?, badge_verified = ?, badge_extra = ?, badge_master_key = ?, badge_signature = ?, badge_key_idx = ?, + contact_domain = ?, contact_domain_proof = ? WHERE user_id = ? AND contact_profile_id = ? Plan: @@ -5119,7 +5153,8 @@ SEARCH contact_profiles USING INTEGER PRIMARY KEY (rowid=?) Query: UPDATE contact_profiles SET display_name = ?, full_name = ?, short_descr = ?, image = ?, contact_link = NULL, preferences = NULL, updated_at = ?, - badge_proof = ?, badge_pres_header = ?, badge_expiry = ?, badge_type = ?, badge_verified = ?, badge_extra = ?, badge_master_key = ?, badge_signature = ?, badge_key_idx = ? + badge_proof = ?, badge_pres_header = ?, badge_expiry = ?, badge_type = ?, badge_verified = ?, badge_extra = ?, badge_master_key = ?, badge_signature = ?, badge_key_idx = ?, + contact_domain = ?, contact_domain_proof = ? WHERE user_id = ? AND contact_profile_id = ? Plan: @@ -5128,7 +5163,8 @@ SEARCH contact_profiles USING INTEGER PRIMARY KEY (rowid=?) Query: UPDATE contact_profiles SET display_name = ?, full_name = ?, short_descr = ?, image = ?, updated_at = ?, - badge_proof = ?, badge_pres_header = ?, badge_expiry = ?, badge_type = ?, badge_verified = ?, badge_extra = ?, badge_master_key = ?, badge_signature = ?, badge_key_idx = ? + badge_proof = ?, badge_pres_header = ?, badge_expiry = ?, badge_type = ?, badge_verified = ?, badge_extra = ?, badge_master_key = ?, badge_signature = ?, badge_key_idx = ?, + contact_domain = ?, contact_domain_proof = ? WHERE user_id = ? AND contact_profile_id = ? Plan: @@ -5142,6 +5178,15 @@ Query: Plan: SEARCH contact_profiles USING INTEGER PRIMARY KEY (rowid=?) +Query: + UPDATE contact_profiles SET contact_domain_verified = ? + WHERE contact_profile_id IN (SELECT contact_profile_id FROM contacts WHERE user_id = ? AND contact_id = ?) + +Plan: +SEARCH contact_profiles USING INTEGER PRIMARY KEY (rowid=?) +LIST SUBQUERY 1 +SEARCH contacts USING INTEGER PRIMARY KEY (rowid=?) + Query: UPDATE contacts SET contact_group_member_id = NULL, contact_grp_inv_sent = 0, updated_at = ? @@ -5325,7 +5370,7 @@ SEARCH groups USING INTEGER PRIMARY KEY (rowid=?) Query: UPDATE groups SET - roster_version = ?, roster_blob = ?, + roster_version = ?, stored_roster_version = ?, applied_complete_roster_version = ?, roster_blob = ?, roster_sending_owner_gm_id = ?, roster_broker_ts = ?, roster_msg_chat_binding = ?, roster_msg_signatures = ?, roster_msg_body = ?, updated_at = ? @@ -5385,7 +5430,7 @@ SEARCH remote_hosts USING INTEGER PRIMARY KEY (rowid=?) Query: UPDATE server_operators - SET enabled = ?, smp_role_storage = ?, smp_role_proxy = ?, xftp_role_storage = ?, xftp_role_proxy = ?, updated_at = ? + SET enabled = ?, smp_role_storage = ?, smp_role_proxy = ?, smp_role_names = ?, xftp_role_storage = ?, xftp_role_proxy = ?, updated_at = ? WHERE server_operator_id = ? Plan: @@ -5468,19 +5513,19 @@ Query: SELECT -- GroupInfo g.group_id, g.local_display_name, gp.display_name, gp.full_name, gp.short_descr, g.local_alias, gp.description, gp.image, gp.group_type, gp.group_link, gp.public_group_id, - gp.group_web_page, gp.group_domain, gp.domain_web_page, gp.allow_embedding, + gp.group_web_page, gp.group_domain, gp.domain_web_page, gp.allow_embedding, gp.group_domain_proof, g.enable_ntfs, g.send_rcpts, g.favorite, gp.preferences, gp.member_admission, g.created_at, g.updated_at, g.chat_ts, g.user_member_profile_sent_at, g.conn_full_link_to_connect, g.conn_short_link_to_connect, g.conn_link_prepared_connection, g.conn_link_started_connection, g.welcome_shared_msg_id, g.request_shared_msg_id, g.business_chat, g.business_member_id, g.customer_member_id, g.use_relays, g.relay_own_status, - g.ui_themes, g.summary_current_members_count, g.public_member_count, g.roster_version, g.custom_data, g.chat_item_ttl, g.members_require_attention, g.via_group_link_uri, + g.ui_themes, g.summary_current_members_count, g.public_member_count, g.roster_version, g.custom_data, g.chat_item_ttl, g.members_require_attention, g.via_group_link_uri, g.group_domain_verified, g.root_priv_key, g.root_pub_key, g.member_priv_key, -- GroupMember - membership mu.group_member_id, mu.group_id, mu.index_in_group, mu.member_id, mu.peer_chat_min_version, mu.peer_chat_max_version, mu.member_role, mu.member_category, mu.member_status, mu.show_messages, mu.member_restriction, mu.invited_by, mu.invited_by_group_member_id, mu.local_display_name, mu.contact_id, mu.contact_profile_id, pu.contact_profile_id, pu.display_name, pu.full_name, pu.short_descr, pu.image, pu.contact_link, pu.chat_peer_type, pu.local_alias, pu.preferences, - pu.badge_proof, pu.badge_pres_header, pu.badge_expiry, pu.badge_type, pu.badge_verified, pu.badge_extra, pu.badge_master_key, pu.badge_signature, pu.badge_key_idx, + pu.badge_proof, pu.badge_pres_header, pu.badge_expiry, pu.badge_type, pu.badge_verified, pu.badge_extra, pu.badge_master_key, pu.badge_signature, pu.badge_key_idx, pu.contact_domain, pu.contact_domain_proof, pu.contact_domain_verified, mu.created_at, mu.updated_at, mu.support_chat_ts, mu.support_chat_items_unread, mu.support_chat_items_member_attention, mu.support_chat_items_mentions, mu.support_chat_last_msg_from_member_ts, mu.member_pub_key, mu.relay_link @@ -5506,19 +5551,19 @@ Query: SELECT -- GroupInfo g.group_id, g.local_display_name, gp.display_name, gp.full_name, gp.short_descr, g.local_alias, gp.description, gp.image, gp.group_type, gp.group_link, gp.public_group_id, - gp.group_web_page, gp.group_domain, gp.domain_web_page, gp.allow_embedding, + gp.group_web_page, gp.group_domain, gp.domain_web_page, gp.allow_embedding, gp.group_domain_proof, g.enable_ntfs, g.send_rcpts, g.favorite, gp.preferences, gp.member_admission, g.created_at, g.updated_at, g.chat_ts, g.user_member_profile_sent_at, g.conn_full_link_to_connect, g.conn_short_link_to_connect, g.conn_link_prepared_connection, g.conn_link_started_connection, g.welcome_shared_msg_id, g.request_shared_msg_id, g.business_chat, g.business_member_id, g.customer_member_id, g.use_relays, g.relay_own_status, - g.ui_themes, g.summary_current_members_count, g.public_member_count, g.roster_version, g.custom_data, g.chat_item_ttl, g.members_require_attention, g.via_group_link_uri, + g.ui_themes, g.summary_current_members_count, g.public_member_count, g.roster_version, g.custom_data, g.chat_item_ttl, g.members_require_attention, g.via_group_link_uri, g.group_domain_verified, g.root_priv_key, g.root_pub_key, g.member_priv_key, -- GroupMember - membership mu.group_member_id, mu.group_id, mu.index_in_group, mu.member_id, mu.peer_chat_min_version, mu.peer_chat_max_version, mu.member_role, mu.member_category, mu.member_status, mu.show_messages, mu.member_restriction, mu.invited_by, mu.invited_by_group_member_id, mu.local_display_name, mu.contact_id, mu.contact_profile_id, pu.contact_profile_id, pu.display_name, pu.full_name, pu.short_descr, pu.image, pu.contact_link, pu.chat_peer_type, pu.local_alias, pu.preferences, - pu.badge_proof, pu.badge_pres_header, pu.badge_expiry, pu.badge_type, pu.badge_verified, pu.badge_extra, pu.badge_master_key, pu.badge_signature, pu.badge_key_idx, + pu.badge_proof, pu.badge_pres_header, pu.badge_expiry, pu.badge_type, pu.badge_verified, pu.badge_extra, pu.badge_master_key, pu.badge_signature, pu.badge_key_idx, pu.contact_domain, pu.contact_domain_proof, pu.contact_domain_verified, mu.created_at, mu.updated_at, mu.support_chat_ts, mu.support_chat_items_unread, mu.support_chat_items_member_attention, mu.support_chat_items_mentions, mu.support_chat_last_msg_from_member_ts, mu.member_pub_key, mu.relay_link @@ -5537,19 +5582,19 @@ Query: SELECT -- GroupInfo g.group_id, g.local_display_name, gp.display_name, gp.full_name, gp.short_descr, g.local_alias, gp.description, gp.image, gp.group_type, gp.group_link, gp.public_group_id, - gp.group_web_page, gp.group_domain, gp.domain_web_page, gp.allow_embedding, + gp.group_web_page, gp.group_domain, gp.domain_web_page, gp.allow_embedding, gp.group_domain_proof, g.enable_ntfs, g.send_rcpts, g.favorite, gp.preferences, gp.member_admission, g.created_at, g.updated_at, g.chat_ts, g.user_member_profile_sent_at, g.conn_full_link_to_connect, g.conn_short_link_to_connect, g.conn_link_prepared_connection, g.conn_link_started_connection, g.welcome_shared_msg_id, g.request_shared_msg_id, g.business_chat, g.business_member_id, g.customer_member_id, g.use_relays, g.relay_own_status, - g.ui_themes, g.summary_current_members_count, g.public_member_count, g.roster_version, g.custom_data, g.chat_item_ttl, g.members_require_attention, g.via_group_link_uri, + g.ui_themes, g.summary_current_members_count, g.public_member_count, g.roster_version, g.custom_data, g.chat_item_ttl, g.members_require_attention, g.via_group_link_uri, g.group_domain_verified, g.root_priv_key, g.root_pub_key, g.member_priv_key, -- GroupMember - membership mu.group_member_id, mu.group_id, mu.index_in_group, mu.member_id, mu.peer_chat_min_version, mu.peer_chat_max_version, mu.member_role, mu.member_category, mu.member_status, mu.show_messages, mu.member_restriction, mu.invited_by, mu.invited_by_group_member_id, mu.local_display_name, mu.contact_id, mu.contact_profile_id, pu.contact_profile_id, pu.display_name, pu.full_name, pu.short_descr, pu.image, pu.contact_link, pu.chat_peer_type, pu.local_alias, pu.preferences, - pu.badge_proof, pu.badge_pres_header, pu.badge_expiry, pu.badge_type, pu.badge_verified, pu.badge_extra, pu.badge_master_key, pu.badge_signature, pu.badge_key_idx, + pu.badge_proof, pu.badge_pres_header, pu.badge_expiry, pu.badge_type, pu.badge_verified, pu.badge_extra, pu.badge_master_key, pu.badge_signature, pu.badge_key_idx, pu.contact_domain, pu.contact_domain_proof, pu.contact_domain_verified, mu.created_at, mu.updated_at, mu.support_chat_ts, mu.support_chat_items_unread, mu.support_chat_items_member_attention, mu.support_chat_items_mentions, mu.support_chat_last_msg_from_member_ts, mu.member_pub_key, mu.relay_link @@ -5572,7 +5617,8 @@ Query: cr.pq_support, cr.welcome_shared_msg_id, cr.request_shared_msg_id, p.preferences, cr.created_at, cr.updated_at, cr.peer_chat_min_version, cr.peer_chat_max_version, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.contact_domain, p.contact_domain_proof, p.contact_domain_verified FROM contact_requests cr JOIN contact_profiles p USING (contact_profile_id) WHERE cr.business_group_id = ? @@ -5588,7 +5634,8 @@ Query: cr.pq_support, cr.welcome_shared_msg_id, cr.request_shared_msg_id, p.preferences, cr.created_at, cr.updated_at, cr.peer_chat_min_version, cr.peer_chat_max_version, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.contact_domain, p.contact_domain_proof, p.contact_domain_verified FROM contact_requests cr JOIN contact_profiles p USING (contact_profile_id) WHERE cr.user_id = ? AND cr.contact_request_id = ? @@ -5600,7 +5647,7 @@ Query: SELECT m.group_member_id, m.group_id, m.index_in_group, m.member_id, m.peer_chat_min_version, m.peer_chat_max_version, m.member_role, m.member_category, m.member_status, m.show_messages, m.member_restriction, m.invited_by, m.invited_by_group_member_id, m.local_display_name, m.contact_id, m.contact_profile_id, p.contact_profile_id, p.display_name, p.full_name, p.short_descr, p.image, p.contact_link, p.chat_peer_type, p.local_alias, p.preferences, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified, m.created_at, m.updated_at, m.support_chat_ts, m.support_chat_items_unread, m.support_chat_items_member_attention, m.support_chat_items_mentions, m.support_chat_last_msg_from_member_ts, m.member_pub_key, m.relay_link, c.connection_id, c.agent_conn_id, c.conn_level, c.via_contact, c.via_user_contact_link, c.via_group_link, c.group_link_id, c.xcontact_id, c.custom_user_profile_id, @@ -5628,7 +5675,7 @@ Query: SELECT m.group_member_id, m.group_id, m.index_in_group, m.member_id, m.peer_chat_min_version, m.peer_chat_max_version, m.member_role, m.member_category, m.member_status, m.show_messages, m.member_restriction, m.invited_by, m.invited_by_group_member_id, m.local_display_name, m.contact_id, m.contact_profile_id, p.contact_profile_id, p.display_name, p.full_name, p.short_descr, p.image, p.contact_link, p.chat_peer_type, p.local_alias, p.preferences, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified, m.created_at, m.updated_at, m.support_chat_ts, m.support_chat_items_unread, m.support_chat_items_member_attention, m.support_chat_items_mentions, m.support_chat_last_msg_from_member_ts, m.member_pub_key, m.relay_link, c.connection_id, c.agent_conn_id, c.conn_level, c.via_contact, c.via_user_contact_link, c.via_group_link, c.group_link_id, c.xcontact_id, c.custom_user_profile_id, @@ -5649,7 +5696,7 @@ Query: SELECT m.group_member_id, m.group_id, m.index_in_group, m.member_id, m.peer_chat_min_version, m.peer_chat_max_version, m.member_role, m.member_category, m.member_status, m.show_messages, m.member_restriction, m.invited_by, m.invited_by_group_member_id, m.local_display_name, m.contact_id, m.contact_profile_id, p.contact_profile_id, p.display_name, p.full_name, p.short_descr, p.image, p.contact_link, p.chat_peer_type, p.local_alias, p.preferences, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified, m.created_at, m.updated_at, m.support_chat_ts, m.support_chat_items_unread, m.support_chat_items_member_attention, m.support_chat_items_mentions, m.support_chat_last_msg_from_member_ts, m.member_pub_key, m.relay_link, c.connection_id, c.agent_conn_id, c.conn_level, c.via_contact, c.via_user_contact_link, c.via_group_link, c.group_link_id, c.xcontact_id, c.custom_user_profile_id, @@ -5669,7 +5716,7 @@ Query: SELECT m.group_member_id, m.group_id, m.index_in_group, m.member_id, m.peer_chat_min_version, m.peer_chat_max_version, m.member_role, m.member_category, m.member_status, m.show_messages, m.member_restriction, m.invited_by, m.invited_by_group_member_id, m.local_display_name, m.contact_id, m.contact_profile_id, p.contact_profile_id, p.display_name, p.full_name, p.short_descr, p.image, p.contact_link, p.chat_peer_type, p.local_alias, p.preferences, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified, m.created_at, m.updated_at, m.support_chat_ts, m.support_chat_items_unread, m.support_chat_items_member_attention, m.support_chat_items_mentions, m.support_chat_last_msg_from_member_ts, m.member_pub_key, m.relay_link, c.connection_id, c.agent_conn_id, c.conn_level, c.via_contact, c.via_user_contact_link, c.via_group_link, c.group_link_id, c.xcontact_id, c.custom_user_profile_id, @@ -5689,7 +5736,7 @@ Query: SELECT m.group_member_id, m.group_id, m.index_in_group, m.member_id, m.peer_chat_min_version, m.peer_chat_max_version, m.member_role, m.member_category, m.member_status, m.show_messages, m.member_restriction, m.invited_by, m.invited_by_group_member_id, m.local_display_name, m.contact_id, m.contact_profile_id, p.contact_profile_id, p.display_name, p.full_name, p.short_descr, p.image, p.contact_link, p.chat_peer_type, p.local_alias, p.preferences, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified, m.created_at, m.updated_at, m.support_chat_ts, m.support_chat_items_unread, m.support_chat_items_member_attention, m.support_chat_items_mentions, m.support_chat_last_msg_from_member_ts, m.member_pub_key, m.relay_link, c.connection_id, c.agent_conn_id, c.conn_level, c.via_contact, c.via_user_contact_link, c.via_group_link, c.group_link_id, c.xcontact_id, c.custom_user_profile_id, @@ -5709,7 +5756,7 @@ Query: SELECT m.group_member_id, m.group_id, m.index_in_group, m.member_id, m.peer_chat_min_version, m.peer_chat_max_version, m.member_role, m.member_category, m.member_status, m.show_messages, m.member_restriction, m.invited_by, m.invited_by_group_member_id, m.local_display_name, m.contact_id, m.contact_profile_id, p.contact_profile_id, p.display_name, p.full_name, p.short_descr, p.image, p.contact_link, p.chat_peer_type, p.local_alias, p.preferences, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified, m.created_at, m.updated_at, m.support_chat_ts, m.support_chat_items_unread, m.support_chat_items_member_attention, m.support_chat_items_mentions, m.support_chat_last_msg_from_member_ts, m.member_pub_key, m.relay_link, c.connection_id, c.agent_conn_id, c.conn_level, c.via_contact, c.via_user_contact_link, c.via_group_link, c.group_link_id, c.xcontact_id, c.custom_user_profile_id, @@ -5729,7 +5776,7 @@ Query: SELECT m.group_member_id, m.group_id, m.index_in_group, m.member_id, m.peer_chat_min_version, m.peer_chat_max_version, m.member_role, m.member_category, m.member_status, m.show_messages, m.member_restriction, m.invited_by, m.invited_by_group_member_id, m.local_display_name, m.contact_id, m.contact_profile_id, p.contact_profile_id, p.display_name, p.full_name, p.short_descr, p.image, p.contact_link, p.chat_peer_type, p.local_alias, p.preferences, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified, m.created_at, m.updated_at, m.support_chat_ts, m.support_chat_items_unread, m.support_chat_items_member_attention, m.support_chat_items_mentions, m.support_chat_last_msg_from_member_ts, m.member_pub_key, m.relay_link, c.connection_id, c.agent_conn_id, c.conn_level, c.via_contact, c.via_user_contact_link, c.via_group_link, c.group_link_id, c.xcontact_id, c.custom_user_profile_id, @@ -5749,7 +5796,7 @@ Query: SELECT m.group_member_id, m.group_id, m.index_in_group, m.member_id, m.peer_chat_min_version, m.peer_chat_max_version, m.member_role, m.member_category, m.member_status, m.show_messages, m.member_restriction, m.invited_by, m.invited_by_group_member_id, m.local_display_name, m.contact_id, m.contact_profile_id, p.contact_profile_id, p.display_name, p.full_name, p.short_descr, p.image, p.contact_link, p.chat_peer_type, p.local_alias, p.preferences, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified, m.created_at, m.updated_at, m.support_chat_ts, m.support_chat_items_unread, m.support_chat_items_member_attention, m.support_chat_items_mentions, m.support_chat_last_msg_from_member_ts, m.member_pub_key, m.relay_link, c.connection_id, c.agent_conn_id, c.conn_level, c.via_contact, c.via_user_contact_link, c.via_group_link, c.group_link_id, c.xcontact_id, c.custom_user_profile_id, @@ -5769,7 +5816,7 @@ Query: SELECT m.group_member_id, m.group_id, m.index_in_group, m.member_id, m.peer_chat_min_version, m.peer_chat_max_version, m.member_role, m.member_category, m.member_status, m.show_messages, m.member_restriction, m.invited_by, m.invited_by_group_member_id, m.local_display_name, m.contact_id, m.contact_profile_id, p.contact_profile_id, p.display_name, p.full_name, p.short_descr, p.image, p.contact_link, p.chat_peer_type, p.local_alias, p.preferences, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified, m.created_at, m.updated_at, m.support_chat_ts, m.support_chat_items_unread, m.support_chat_items_member_attention, m.support_chat_items_mentions, m.support_chat_last_msg_from_member_ts, m.member_pub_key, m.relay_link, c.connection_id, c.agent_conn_id, c.conn_level, c.via_contact, c.via_user_contact_link, c.via_group_link, c.group_link_id, c.xcontact_id, c.custom_user_profile_id, @@ -5789,7 +5836,7 @@ Query: SELECT m.group_member_id, m.group_id, m.index_in_group, m.member_id, m.peer_chat_min_version, m.peer_chat_max_version, m.member_role, m.member_category, m.member_status, m.show_messages, m.member_restriction, m.invited_by, m.invited_by_group_member_id, m.local_display_name, m.contact_id, m.contact_profile_id, p.contact_profile_id, p.display_name, p.full_name, p.short_descr, p.image, p.contact_link, p.chat_peer_type, p.local_alias, p.preferences, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified, m.created_at, m.updated_at, m.support_chat_ts, m.support_chat_items_unread, m.support_chat_items_member_attention, m.support_chat_items_mentions, m.support_chat_last_msg_from_member_ts, m.member_pub_key, m.relay_link, c.connection_id, c.agent_conn_id, c.conn_level, c.via_contact, c.via_user_contact_link, c.via_group_link, c.group_link_id, c.xcontact_id, c.custom_user_profile_id, @@ -5809,7 +5856,7 @@ Query: SELECT m.group_member_id, m.group_id, m.index_in_group, m.member_id, m.peer_chat_min_version, m.peer_chat_max_version, m.member_role, m.member_category, m.member_status, m.show_messages, m.member_restriction, m.invited_by, m.invited_by_group_member_id, m.local_display_name, m.contact_id, m.contact_profile_id, p.contact_profile_id, p.display_name, p.full_name, p.short_descr, p.image, p.contact_link, p.chat_peer_type, p.local_alias, p.preferences, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified, m.created_at, m.updated_at, m.support_chat_ts, m.support_chat_items_unread, m.support_chat_items_member_attention, m.support_chat_items_mentions, m.support_chat_last_msg_from_member_ts, m.member_pub_key, m.relay_link, c.connection_id, c.agent_conn_id, c.conn_level, c.via_contact, c.via_user_contact_link, c.via_group_link, c.group_link_id, c.xcontact_id, c.custom_user_profile_id, @@ -5829,7 +5876,7 @@ Query: SELECT m.group_member_id, m.group_id, m.index_in_group, m.member_id, m.peer_chat_min_version, m.peer_chat_max_version, m.member_role, m.member_category, m.member_status, m.show_messages, m.member_restriction, m.invited_by, m.invited_by_group_member_id, m.local_display_name, m.contact_id, m.contact_profile_id, p.contact_profile_id, p.display_name, p.full_name, p.short_descr, p.image, p.contact_link, p.chat_peer_type, p.local_alias, p.preferences, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified, m.created_at, m.updated_at, m.support_chat_ts, m.support_chat_items_unread, m.support_chat_items_member_attention, m.support_chat_items_mentions, m.support_chat_last_msg_from_member_ts, m.member_pub_key, m.relay_link, c.connection_id, c.agent_conn_id, c.conn_level, c.via_contact, c.via_user_contact_link, c.via_group_link, c.group_link_id, c.xcontact_id, c.custom_user_profile_id, @@ -5849,7 +5896,7 @@ Query: SELECT m.group_member_id, m.group_id, m.index_in_group, m.member_id, m.peer_chat_min_version, m.peer_chat_max_version, m.member_role, m.member_category, m.member_status, m.show_messages, m.member_restriction, m.invited_by, m.invited_by_group_member_id, m.local_display_name, m.contact_id, m.contact_profile_id, p.contact_profile_id, p.display_name, p.full_name, p.short_descr, p.image, p.contact_link, p.chat_peer_type, p.local_alias, p.preferences, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified, m.created_at, m.updated_at, m.support_chat_ts, m.support_chat_items_unread, m.support_chat_items_member_attention, m.support_chat_items_mentions, m.support_chat_last_msg_from_member_ts, m.member_pub_key, m.relay_link, c.connection_id, c.agent_conn_id, c.conn_level, c.via_contact, c.via_user_contact_link, c.via_group_link, c.group_link_id, c.xcontact_id, c.custom_user_profile_id, @@ -5869,7 +5916,7 @@ Query: SELECT m.group_member_id, m.group_id, m.index_in_group, m.member_id, m.peer_chat_min_version, m.peer_chat_max_version, m.member_role, m.member_category, m.member_status, m.show_messages, m.member_restriction, m.invited_by, m.invited_by_group_member_id, m.local_display_name, m.contact_id, m.contact_profile_id, p.contact_profile_id, p.display_name, p.full_name, p.short_descr, p.image, p.contact_link, p.chat_peer_type, p.local_alias, p.preferences, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified, m.created_at, m.updated_at, m.support_chat_ts, m.support_chat_items_unread, m.support_chat_items_member_attention, m.support_chat_items_mentions, m.support_chat_last_msg_from_member_ts, m.member_pub_key, m.relay_link, c.connection_id, c.agent_conn_id, c.conn_level, c.via_contact, c.via_user_contact_link, c.via_group_link, c.group_link_id, c.xcontact_id, c.custom_user_profile_id, @@ -5889,7 +5936,7 @@ Query: SELECT m.group_member_id, m.group_id, m.index_in_group, m.member_id, m.peer_chat_min_version, m.peer_chat_max_version, m.member_role, m.member_category, m.member_status, m.show_messages, m.member_restriction, m.invited_by, m.invited_by_group_member_id, m.local_display_name, m.contact_id, m.contact_profile_id, p.contact_profile_id, p.display_name, p.full_name, p.short_descr, p.image, p.contact_link, p.chat_peer_type, p.local_alias, p.preferences, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified, m.created_at, m.updated_at, m.support_chat_ts, m.support_chat_items_unread, m.support_chat_items_member_attention, m.support_chat_items_mentions, m.support_chat_last_msg_from_member_ts, m.member_pub_key, m.relay_link, c.connection_id, c.agent_conn_id, c.conn_level, c.via_contact, c.via_user_contact_link, c.via_group_link, c.group_link_id, c.xcontact_id, c.custom_user_profile_id, @@ -6073,7 +6120,7 @@ SEARCH remote_hosts USING INTEGER PRIMARY KEY (rowid=?) Query: SELECT server_operator_id, server_operator_tag, trade_name, legal_name, - server_domains, enabled, smp_role_storage, smp_role_proxy, xftp_role_storage, xftp_role_proxy + server_domains, enabled, smp_role_storage, smp_role_proxy, smp_role_names, xftp_role_storage, xftp_role_proxy FROM server_operators Plan: @@ -6081,7 +6128,7 @@ SCAN server_operators Query: SELECT server_operator_id, server_operator_tag, trade_name, legal_name, - server_domains, enabled, smp_role_storage, smp_role_proxy, xftp_role_storage, xftp_role_proxy + server_domains, enabled, smp_role_storage, smp_role_proxy, smp_role_names, xftp_role_storage, xftp_role_proxy FROM server_operators WHERE server_operator_id = ? Plan: @@ -6090,7 +6137,7 @@ SEARCH server_operators USING INTEGER PRIMARY KEY (rowid=?) Query: SELECT u.user_id, u.agent_user_id, u.contact_id, ucp.contact_profile_id, u.active_user, u.active_order, u.local_display_name, ucp.full_name, ucp.short_descr, ucp.image, ucp.contact_link, ucp.chat_peer_type, ucp.preferences, u.show_ntfs, u.send_rcpts_contacts, u.send_rcpts_small_groups, u.auto_accept_member_contacts, u.view_pwd_hash, u.view_pwd_salt, u.user_member_profile_updated_at, u.is_user_chat_relay, u.client_service, u.ui_themes, - ucp.badge_proof, ucp.badge_pres_header, ucp.badge_expiry, ucp.badge_type, ucp.badge_verified, ucp.badge_extra, ucp.badge_master_key, ucp.badge_signature, ucp.badge_key_idx + ucp.badge_proof, ucp.badge_pres_header, ucp.badge_expiry, ucp.badge_type, ucp.badge_verified, ucp.badge_extra, ucp.badge_master_key, ucp.badge_signature, ucp.badge_key_idx, ucp.contact_domain, ucp.contact_domain_proof, ucp.contact_domain_verified FROM users u JOIN contacts uct ON uct.contact_id = u.contact_id JOIN contact_profiles ucp ON ucp.contact_profile_id = uct.contact_profile_id @@ -6103,7 +6150,7 @@ SEARCH ucp USING INTEGER PRIMARY KEY (rowid=?) Query: SELECT u.user_id, u.agent_user_id, u.contact_id, ucp.contact_profile_id, u.active_user, u.active_order, u.local_display_name, ucp.full_name, ucp.short_descr, ucp.image, ucp.contact_link, ucp.chat_peer_type, ucp.preferences, u.show_ntfs, u.send_rcpts_contacts, u.send_rcpts_small_groups, u.auto_accept_member_contacts, u.view_pwd_hash, u.view_pwd_salt, u.user_member_profile_updated_at, u.is_user_chat_relay, u.client_service, u.ui_themes, - ucp.badge_proof, ucp.badge_pres_header, ucp.badge_expiry, ucp.badge_type, ucp.badge_verified, ucp.badge_extra, ucp.badge_master_key, ucp.badge_signature, ucp.badge_key_idx + ucp.badge_proof, ucp.badge_pres_header, ucp.badge_expiry, ucp.badge_type, ucp.badge_verified, ucp.badge_extra, ucp.badge_master_key, ucp.badge_signature, ucp.badge_key_idx, ucp.contact_domain, ucp.contact_domain_proof, ucp.contact_domain_verified FROM users u JOIN contacts uct ON uct.contact_id = u.contact_id JOIN contact_profiles ucp ON ucp.contact_profile_id = uct.contact_profile_id @@ -6117,7 +6164,7 @@ SEARCH ucp USING INTEGER PRIMARY KEY (rowid=?) Query: SELECT u.user_id, u.agent_user_id, u.contact_id, ucp.contact_profile_id, u.active_user, u.active_order, u.local_display_name, ucp.full_name, ucp.short_descr, ucp.image, ucp.contact_link, ucp.chat_peer_type, ucp.preferences, u.show_ntfs, u.send_rcpts_contacts, u.send_rcpts_small_groups, u.auto_accept_member_contacts, u.view_pwd_hash, u.view_pwd_salt, u.user_member_profile_updated_at, u.is_user_chat_relay, u.client_service, u.ui_themes, - ucp.badge_proof, ucp.badge_pres_header, ucp.badge_expiry, ucp.badge_type, ucp.badge_verified, ucp.badge_extra, ucp.badge_master_key, ucp.badge_signature, ucp.badge_key_idx + ucp.badge_proof, ucp.badge_pres_header, ucp.badge_expiry, ucp.badge_type, ucp.badge_verified, ucp.badge_extra, ucp.badge_master_key, ucp.badge_signature, ucp.badge_key_idx, ucp.contact_domain, ucp.contact_domain_proof, ucp.contact_domain_verified FROM users u JOIN contacts uct ON uct.contact_id = u.contact_id JOIN contact_profiles ucp ON ucp.contact_profile_id = uct.contact_profile_id @@ -6131,7 +6178,7 @@ SEARCH ucp USING INTEGER PRIMARY KEY (rowid=?) Query: SELECT u.user_id, u.agent_user_id, u.contact_id, ucp.contact_profile_id, u.active_user, u.active_order, u.local_display_name, ucp.full_name, ucp.short_descr, ucp.image, ucp.contact_link, ucp.chat_peer_type, ucp.preferences, u.show_ntfs, u.send_rcpts_contacts, u.send_rcpts_small_groups, u.auto_accept_member_contacts, u.view_pwd_hash, u.view_pwd_salt, u.user_member_profile_updated_at, u.is_user_chat_relay, u.client_service, u.ui_themes, - ucp.badge_proof, ucp.badge_pres_header, ucp.badge_expiry, ucp.badge_type, ucp.badge_verified, ucp.badge_extra, ucp.badge_master_key, ucp.badge_signature, ucp.badge_key_idx + ucp.badge_proof, ucp.badge_pres_header, ucp.badge_expiry, ucp.badge_type, ucp.badge_verified, ucp.badge_extra, ucp.badge_master_key, ucp.badge_signature, ucp.badge_key_idx, ucp.contact_domain, ucp.contact_domain_proof, ucp.contact_domain_verified FROM users u JOIN contacts uct ON uct.contact_id = u.contact_id JOIN contact_profiles ucp ON ucp.contact_profile_id = uct.contact_profile_id @@ -6146,7 +6193,7 @@ SEARCH ucp USING INTEGER PRIMARY KEY (rowid=?) Query: SELECT u.user_id, u.agent_user_id, u.contact_id, ucp.contact_profile_id, u.active_user, u.active_order, u.local_display_name, ucp.full_name, ucp.short_descr, ucp.image, ucp.contact_link, ucp.chat_peer_type, ucp.preferences, u.show_ntfs, u.send_rcpts_contacts, u.send_rcpts_small_groups, u.auto_accept_member_contacts, u.view_pwd_hash, u.view_pwd_salt, u.user_member_profile_updated_at, u.is_user_chat_relay, u.client_service, u.ui_themes, - ucp.badge_proof, ucp.badge_pres_header, ucp.badge_expiry, ucp.badge_type, ucp.badge_verified, ucp.badge_extra, ucp.badge_master_key, ucp.badge_signature, ucp.badge_key_idx + ucp.badge_proof, ucp.badge_pres_header, ucp.badge_expiry, ucp.badge_type, ucp.badge_verified, ucp.badge_extra, ucp.badge_master_key, ucp.badge_signature, ucp.badge_key_idx, ucp.contact_domain, ucp.contact_domain_proof, ucp.contact_domain_verified FROM users u JOIN contacts uct ON uct.contact_id = u.contact_id JOIN contact_profiles ucp ON ucp.contact_profile_id = uct.contact_profile_id @@ -6160,7 +6207,7 @@ SEARCH ucp USING INTEGER PRIMARY KEY (rowid=?) Query: SELECT u.user_id, u.agent_user_id, u.contact_id, ucp.contact_profile_id, u.active_user, u.active_order, u.local_display_name, ucp.full_name, ucp.short_descr, ucp.image, ucp.contact_link, ucp.chat_peer_type, ucp.preferences, u.show_ntfs, u.send_rcpts_contacts, u.send_rcpts_small_groups, u.auto_accept_member_contacts, u.view_pwd_hash, u.view_pwd_salt, u.user_member_profile_updated_at, u.is_user_chat_relay, u.client_service, u.ui_themes, - ucp.badge_proof, ucp.badge_pres_header, ucp.badge_expiry, ucp.badge_type, ucp.badge_verified, ucp.badge_extra, ucp.badge_master_key, ucp.badge_signature, ucp.badge_key_idx + ucp.badge_proof, ucp.badge_pres_header, ucp.badge_expiry, ucp.badge_type, ucp.badge_verified, ucp.badge_extra, ucp.badge_master_key, ucp.badge_signature, ucp.badge_key_idx, ucp.contact_domain, ucp.contact_domain_proof, ucp.contact_domain_verified FROM users u JOIN contacts uct ON uct.contact_id = u.contact_id JOIN contact_profiles ucp ON ucp.contact_profile_id = uct.contact_profile_id @@ -6174,7 +6221,7 @@ SEARCH ucp USING INTEGER PRIMARY KEY (rowid=?) Query: SELECT u.user_id, u.agent_user_id, u.contact_id, ucp.contact_profile_id, u.active_user, u.active_order, u.local_display_name, ucp.full_name, ucp.short_descr, ucp.image, ucp.contact_link, ucp.chat_peer_type, ucp.preferences, u.show_ntfs, u.send_rcpts_contacts, u.send_rcpts_small_groups, u.auto_accept_member_contacts, u.view_pwd_hash, u.view_pwd_salt, u.user_member_profile_updated_at, u.is_user_chat_relay, u.client_service, u.ui_themes, - ucp.badge_proof, ucp.badge_pres_header, ucp.badge_expiry, ucp.badge_type, ucp.badge_verified, ucp.badge_extra, ucp.badge_master_key, ucp.badge_signature, ucp.badge_key_idx + ucp.badge_proof, ucp.badge_pres_header, ucp.badge_expiry, ucp.badge_type, ucp.badge_verified, ucp.badge_extra, ucp.badge_master_key, ucp.badge_signature, ucp.badge_key_idx, ucp.contact_domain, ucp.contact_domain_proof, ucp.contact_domain_verified FROM users u JOIN contacts uct ON uct.contact_id = u.contact_id JOIN contact_profiles ucp ON ucp.contact_profile_id = uct.contact_profile_id @@ -6188,7 +6235,7 @@ SEARCH ucp USING INTEGER PRIMARY KEY (rowid=?) Query: SELECT u.user_id, u.agent_user_id, u.contact_id, ucp.contact_profile_id, u.active_user, u.active_order, u.local_display_name, ucp.full_name, ucp.short_descr, ucp.image, ucp.contact_link, ucp.chat_peer_type, ucp.preferences, u.show_ntfs, u.send_rcpts_contacts, u.send_rcpts_small_groups, u.auto_accept_member_contacts, u.view_pwd_hash, u.view_pwd_salt, u.user_member_profile_updated_at, u.is_user_chat_relay, u.client_service, u.ui_themes, - ucp.badge_proof, ucp.badge_pres_header, ucp.badge_expiry, ucp.badge_type, ucp.badge_verified, ucp.badge_extra, ucp.badge_master_key, ucp.badge_signature, ucp.badge_key_idx + ucp.badge_proof, ucp.badge_pres_header, ucp.badge_expiry, ucp.badge_type, ucp.badge_verified, ucp.badge_extra, ucp.badge_master_key, ucp.badge_signature, ucp.badge_key_idx, ucp.contact_domain, ucp.contact_domain_proof, ucp.contact_domain_verified FROM users u JOIN contacts uct ON uct.contact_id = u.contact_id JOIN contact_profiles ucp ON ucp.contact_profile_id = uct.contact_profile_id @@ -6202,7 +6249,7 @@ SEARCH ucp USING INTEGER PRIMARY KEY (rowid=?) Query: SELECT u.user_id, u.agent_user_id, u.contact_id, ucp.contact_profile_id, u.active_user, u.active_order, u.local_display_name, ucp.full_name, ucp.short_descr, ucp.image, ucp.contact_link, ucp.chat_peer_type, ucp.preferences, u.show_ntfs, u.send_rcpts_contacts, u.send_rcpts_small_groups, u.auto_accept_member_contacts, u.view_pwd_hash, u.view_pwd_salt, u.user_member_profile_updated_at, u.is_user_chat_relay, u.client_service, u.ui_themes, - ucp.badge_proof, ucp.badge_pres_header, ucp.badge_expiry, ucp.badge_type, ucp.badge_verified, ucp.badge_extra, ucp.badge_master_key, ucp.badge_signature, ucp.badge_key_idx + ucp.badge_proof, ucp.badge_pres_header, ucp.badge_expiry, ucp.badge_type, ucp.badge_verified, ucp.badge_extra, ucp.badge_master_key, ucp.badge_signature, ucp.badge_key_idx, ucp.contact_domain, ucp.contact_domain_proof, ucp.contact_domain_verified FROM users u JOIN contacts uct ON uct.contact_id = u.contact_id JOIN contact_profiles ucp ON ucp.contact_profile_id = uct.contact_profile_id @@ -6215,7 +6262,7 @@ SEARCH ucp USING INTEGER PRIMARY KEY (rowid=?) Query: SELECT u.user_id, u.agent_user_id, u.contact_id, ucp.contact_profile_id, u.active_user, u.active_order, u.local_display_name, ucp.full_name, ucp.short_descr, ucp.image, ucp.contact_link, ucp.chat_peer_type, ucp.preferences, u.show_ntfs, u.send_rcpts_contacts, u.send_rcpts_small_groups, u.auto_accept_member_contacts, u.view_pwd_hash, u.view_pwd_salt, u.user_member_profile_updated_at, u.is_user_chat_relay, u.client_service, u.ui_themes, - ucp.badge_proof, ucp.badge_pres_header, ucp.badge_expiry, ucp.badge_type, ucp.badge_verified, ucp.badge_extra, ucp.badge_master_key, ucp.badge_signature, ucp.badge_key_idx + ucp.badge_proof, ucp.badge_pres_header, ucp.badge_expiry, ucp.badge_type, ucp.badge_verified, ucp.badge_extra, ucp.badge_master_key, ucp.badge_signature, ucp.badge_key_idx, ucp.contact_domain, ucp.contact_domain_proof, ucp.contact_domain_verified FROM users u JOIN contacts uct ON uct.contact_id = u.contact_id JOIN contact_profiles ucp ON ucp.contact_profile_id = uct.contact_profile_id @@ -6618,6 +6665,36 @@ SEARCH rcv_files USING INTEGER PRIMARY KEY (rowid=?) SEARCH snd_files USING COVERING INDEX idx_snd_files_file_id (file_id=?) SEARCH files USING COVERING INDEX idx_files_redirect_file_id (redirect_file_id=?) +Query: DELETE FROM group_members WHERE member_id = ? +Plan: +SCAN group_members +SEARCH rcv_roster_transfers USING COVERING INDEX idx_rcv_roster_transfers_from_member_id (from_member_id=?) +SEARCH group_relays USING COVERING INDEX idx_group_relays_group_member_id (group_member_id=?) +SEARCH delivery_jobs USING COVERING INDEX idx_delivery_jobs_job_scope_support_gm_id (job_scope_support_gm_id=?) +SEARCH delivery_tasks USING COVERING INDEX idx_delivery_tasks_sender_group_member_id (sender_group_member_id=?) +SEARCH delivery_tasks USING COVERING INDEX idx_delivery_tasks_job_scope_support_gm_id (job_scope_support_gm_id=?) +SEARCH received_probes USING COVERING INDEX idx_received_probes_group_member_id (group_member_id=?) +SEARCH sent_probe_hashes USING COVERING INDEX idx_sent_probe_hashes_group_member_id (group_member_id=?) +SEARCH sent_probes USING COVERING INDEX idx_sent_probes_group_member_id (group_member_id=?) +SEARCH group_snd_item_statuses USING COVERING INDEX idx_group_snd_item_statuses_group_member_id (group_member_id=?) +SEARCH chat_item_moderations USING COVERING INDEX idx_chat_item_moderations_moderator_member_id (moderator_member_id=?) +SEARCH chat_item_reactions USING COVERING INDEX idx_chat_item_reactions_group_member_id (group_member_id=?) +SEARCH chat_items USING COVERING INDEX idx_chat_items_group_scope_group_member_id (group_scope_group_member_id=?) +SEARCH chat_items USING COVERING INDEX idx_chat_items_forwarded_by_group_member_id (forwarded_by_group_member_id=?) +SEARCH chat_items USING COVERING INDEX idx_chat_items_item_deleted_by_group_member_id (item_deleted_by_group_member_id=?) +SEARCH chat_items USING COVERING INDEX idx_chat_items_group_member_id (group_member_id=?) +SEARCH pending_group_messages USING COVERING INDEX idx_pending_group_messages_group_member_id (group_member_id=?) +SEARCH messages USING COVERING INDEX idx_messages_forwarded_by_group_member_id (forwarded_by_group_member_id=?) +SEARCH messages USING COVERING INDEX idx_messages_author_group_member_id (author_group_member_id=?) +SEARCH connections USING COVERING INDEX idx_connections_group_member_id (group_member_id=?) +SEARCH rcv_files USING COVERING INDEX idx_rcv_files_group_member_id (group_member_id=?) +SEARCH snd_files USING COVERING INDEX idx_snd_files_group_member_id (group_member_id=?) +SEARCH group_member_intros USING COVERING INDEX idx_group_member_intros_to_group_member_id (to_group_member_id=?) +SEARCH group_member_intros USING COVERING INDEX idx_group_member_intros_re_group_member_id (re_group_member_id=?) +SEARCH group_members USING COVERING INDEX idx_group_members_invited_by_group_member_id (invited_by_group_member_id=?) +SEARCH contacts USING COVERING INDEX idx_contacts_grp_direct_inv_from_group_member_id (grp_direct_inv_from_group_member_id=?) +SEARCH contacts USING COVERING INDEX idx_contacts_contact_group_member_id (contact_group_member_id=?) + Query: DELETE FROM group_members WHERE user_id = ? AND group_id = ? Plan: SEARCH group_members USING COVERING INDEX idx_group_members_group_id (user_id=? AND group_id=?) @@ -6848,7 +6925,7 @@ Query: INSERT INTO contact_profiles (display_name, full_name, short_descr, image Plan: SEARCH contact_requests USING COVERING INDEX idx_contact_requests_contact_profile_id (contact_profile_id=?) -Query: INSERT INTO contact_profiles (display_name, full_name, short_descr, image, contact_link, chat_peer_type, user_id, local_alias, preferences, created_at, updated_at, badge_proof, badge_pres_header, badge_expiry, badge_type, badge_verified, badge_extra, badge_master_key, badge_signature, badge_key_idx) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) +Query: INSERT INTO contact_profiles (display_name, full_name, short_descr, image, contact_link, chat_peer_type, user_id, local_alias, preferences, created_at, updated_at, badge_proof, badge_pres_header, badge_expiry, badge_type, badge_verified, badge_extra, badge_master_key, badge_signature, badge_key_idx, contact_domain, contact_domain_proof) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) Plan: SEARCH contact_requests USING COVERING INDEX idx_contact_requests_contact_profile_id (contact_profile_id=?) @@ -6938,7 +7015,7 @@ Query: INSERT INTO snd_files (file_id, file_status, file_descr_id, group_member_ Plan: SEARCH connections USING INTEGER PRIMARY KEY (rowid=?) -Query: INSERT INTO user_contact_links (user_id, conn_req_contact, short_link_contact, short_link_data_set, short_link_large_data_set, created_at, updated_at) VALUES (?,?,?,?,?,?,?) +Query: INSERT INTO user_contact_links (user_id, conn_req_contact, short_link_contact, short_link_data_set, short_link_large_data_set, link_priv_sig_key, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?) Plan: Query: INSERT INTO user_contact_links (user_id, group_id, group_link_id, local_display_name, conn_req_contact, short_link_contact, short_link_data_set, short_link_large_data_set, group_link_member_role, auto_accept, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?) @@ -7029,6 +7106,10 @@ Query: SELECT app_settings FROM app_settings Plan: SCAN app_settings +Query: SELECT applied_complete_roster_version FROM groups WHERE group_id = ? +Plan: +SEARCH groups USING INTEGER PRIMARY KEY (rowid=?) + Query: SELECT auth_err_counter FROM connections WHERE user_id = ? AND connection_id = ? Plan: SEARCH connections USING INTEGER PRIMARY KEY (rowid=?) @@ -7238,6 +7319,10 @@ Query: SELECT max(active_order) FROM users Plan: SEARCH users +Query: SELECT member_id FROM group_members WHERE local_display_name = ? +Plan: +SCAN group_members + Query: SELECT member_id FROM group_members WHERE member_role = ? LIMIT 1 Plan: SCAN group_members @@ -7266,6 +7351,10 @@ Query: SELECT member_role, member_pub_key FROM group_members WHERE local_display Plan: SCAN group_members +Query: SELECT member_role, member_pub_key FROM group_members WHERE member_id = ? +Plan: +SCAN group_members + Query: SELECT member_status FROM group_members WHERE local_display_name = ? Plan: SCAN group_members @@ -7314,10 +7403,14 @@ Query: SELECT roster_blob FROM groups WHERE roster_blob IS NOT NULL Plan: SCAN groups -Query: SELECT roster_sending_owner_gm_id, roster_broker_ts, roster_msg_chat_binding, roster_msg_signatures, roster_msg_body, roster_blob FROM groups WHERE group_id = ? +Query: SELECT roster_sending_owner_gm_id, roster_broker_ts, roster_msg_chat_binding, roster_msg_signatures, roster_msg_body, roster_blob, stored_roster_version FROM groups WHERE group_id = ? Plan: SEARCH groups USING INTEGER PRIMARY KEY (rowid=?) +Query: SELECT roster_served_version FROM group_members WHERE group_member_id = ? +Plan: +SEARCH group_members USING INTEGER PRIMARY KEY (rowid=?) + Query: SELECT roster_transfer_id FROM rcv_roster_transfers WHERE group_id = ? AND from_member_id = ? Plan: SEARCH rcv_roster_transfers USING COVERING INDEX idx_rcv_roster_transfers_group_id_from_member_id (group_id=? AND from_member_id=?) @@ -7342,6 +7435,10 @@ Query: SELECT should_sync FROM connections_sync WHERE connections_sync_id = 1 Plan: SEARCH connections_sync USING INTEGER PRIMARY KEY (rowid=?) +Query: SELECT stored_roster_version FROM groups WHERE group_id = ? +Plan: +SEARCH groups USING INTEGER PRIMARY KEY (rowid=?) + Query: SELECT summary_current_members_count FROM groups WHERE group_id = ? Plan: SEARCH groups USING INTEGER PRIMARY KEY (rowid=?) @@ -7426,6 +7523,10 @@ Query: UPDATE connections_sync SET should_sync = 1 WHERE connections_sync_id = 1 Plan: SEARCH connections_sync USING INTEGER PRIMARY KEY (rowid=?) +Query: UPDATE contact_profiles SET contact_domain = ?, updated_at = ? WHERE user_id = ? AND contact_profile_id = ? +Plan: +SEARCH contact_profiles USING INTEGER PRIMARY KEY (rowid=?) + Query: UPDATE contact_profiles SET image = ? WHERE display_name = ? Plan: SEARCH contact_profiles USING INDEX contact_profiles_index (display_name=?) @@ -7582,6 +7683,10 @@ Query: UPDATE group_members SET member_role = ?, member_pub_key = NULL WHERE loc Plan: SCAN group_members +Query: UPDATE group_members SET roster_served_version = ?, updated_at = ? WHERE group_member_id = ? +Plan: +SEARCH group_members USING INTEGER PRIMARY KEY (rowid=?) + Query: UPDATE group_members SET support_chat_items_member_attention = ?, updated_at = ? WHERE group_member_id = ? Plan: SEARCH group_members USING INTEGER PRIMARY KEY (rowid=?) @@ -7602,6 +7707,14 @@ Query: UPDATE group_relays SET relay_status = ?, updated_at = ? WHERE group_rela Plan: SEARCH group_relays USING INTEGER PRIMARY KEY (rowid=?) +Query: UPDATE groups SET applied_complete_roster_version = ? WHERE group_id = ? +Plan: +SEARCH groups USING INTEGER PRIMARY KEY (rowid=?) + +Query: UPDATE groups SET applied_complete_roster_version = ?, updated_at = ? WHERE group_id = ? +Plan: +SEARCH groups USING INTEGER PRIMARY KEY (rowid=?) + Query: UPDATE groups SET business_member_id = ?, customer_member_id = ? WHERE group_id = ? Plan: SEARCH groups USING INTEGER PRIMARY KEY (rowid=?) @@ -7630,6 +7743,14 @@ Query: UPDATE groups SET enable_ntfs = ?, send_rcpts = ?, favorite = ? WHERE use Plan: SEARCH groups USING INTEGER PRIMARY KEY (rowid=?) +Query: UPDATE groups SET group_domain_verified = ? WHERE user_id = ? AND group_id = ? +Plan: +SEARCH groups USING INTEGER PRIMARY KEY (rowid=?) + +Query: UPDATE groups SET group_domain_verified = NULL WHERE user_id = ? AND group_id = ? +Plan: +SEARCH groups USING INTEGER PRIMARY KEY (rowid=?) + Query: UPDATE groups SET local_alias = ?, updated_at = ? WHERE user_id = ? AND group_id = ? Plan: SEARCH groups USING INTEGER PRIMARY KEY (rowid=?) diff --git a/src/Simplex/Chat/Store/SQLite/Migrations/chat_schema.sql b/src/Simplex/Chat/Store/SQLite/Migrations/chat_schema.sql index d4d395c1dc..01d53ad000 100644 --- a/src/Simplex/Chat/Store/SQLite/Migrations/chat_schema.sql +++ b/src/Simplex/Chat/Store/SQLite/Migrations/chat_schema.sql @@ -28,7 +28,10 @@ CREATE TABLE contact_profiles( badge_extra TEXT, badge_master_key BLOB, badge_signature BLOB, - badge_key_idx INTEGER + badge_key_idx INTEGER, + contact_domain TEXT, + contact_domain_proof TEXT, + contact_domain_verified INTEGER ) STRICT; CREATE TABLE users( user_id INTEGER PRIMARY KEY, @@ -139,7 +142,8 @@ CREATE TABLE group_profiles( group_web_page TEXT, group_domain TEXT, domain_web_page INTEGER, - allow_embedding INTEGER + allow_embedding INTEGER, + group_domain_proof TEXT ) STRICT; CREATE TABLE groups( group_id INTEGER PRIMARY KEY, -- local group ID @@ -199,7 +203,10 @@ CREATE TABLE groups( roster_msg_signatures BLOB, roster_sending_owner_gm_id INTEGER, roster_broker_ts TEXT, - roster_blob BLOB, -- received + roster_blob BLOB, + group_domain_verified INTEGER, + stored_roster_version INTEGER, + applied_complete_roster_version INTEGER, -- received FOREIGN KEY(user_id, local_display_name) REFERENCES display_names(user_id, local_display_name) ON DELETE CASCADE @@ -244,6 +251,7 @@ CREATE TABLE group_members( relay_link BLOB, member_pub_key BLOB, removed_at TEXT, + roster_served_version INTEGER, FOREIGN KEY(user_id, local_display_name) REFERENCES display_names(user_id, local_display_name) ON DELETE CASCADE @@ -393,6 +401,7 @@ CREATE TABLE user_contact_links( short_link_contact BLOB, short_link_data_set INTEGER NOT NULL DEFAULT 0, short_link_large_data_set INTEGER NOT NULL DEFAULT 0, + link_priv_sig_key BLOB, UNIQUE(user_id, local_display_name) ) STRICT; CREATE TABLE contact_requests( @@ -700,6 +709,8 @@ CREATE TABLE server_operators( xftp_role_proxy INTEGER NOT NULL DEFAULT 1, created_at TEXT NOT NULL DEFAULT(datetime('now')), updated_at TEXT NOT NULL DEFAULT(datetime('now')) + , + smp_role_names INTEGER NOT NULL DEFAULT 0 ) STRICT; CREATE TABLE usage_conditions( usage_conditions_id INTEGER PRIMARY KEY AUTOINCREMENT, diff --git a/src/Simplex/Chat/Store/Shared.hs b/src/Simplex/Chat/Store/Shared.hs index 9096be3a86..0d01b2ac1d 100644 --- a/src/Simplex/Chat/Store/Shared.hs +++ b/src/Simplex/Chat/Store/Shared.hs @@ -33,13 +33,14 @@ import qualified Data.Text as T import Data.Time.Clock (UTCTime (..), getCurrentTime) import Data.Type.Equality import Simplex.Chat.Badges (BadgeRow, badgeToRow, rowToBadge, verifyBadge_) +import Simplex.Chat.Names (SimplexDomainProof, SimplexDomainClaim (..), claimDomain) import Simplex.Chat.Messages import Simplex.Chat.Remote.Types import Simplex.Chat.Types import Simplex.Chat.Types.Preferences import Simplex.Chat.Types.Shared import Simplex.Chat.Types.UITheme -import Simplex.Messaging.Agent.Protocol (AConnShortLink (..), AConnectionRequestUri (..), ACreatedConnLink (..), ConnId, ConnShortLink, ConnectionRequestUri, CreatedConnLink (..), UserId, connMode) +import Simplex.Messaging.Agent.Protocol (AConnShortLink (..), AConnectionRequestUri (..), ACreatedConnLink (..), ConnId, ConnShortLink, ConnectionRequestUri, CreatedConnLink (..), SimplexDomain, UserId, connMode) import Simplex.Messaging.Agent.Store (AnyStoreError (..)) import Simplex.Messaging.Agent.Store.AgentStore (firstRow, maybeFirstRow) import Simplex.Messaging.Agent.Store.Common (withSavepoint) @@ -48,6 +49,7 @@ import qualified Simplex.Messaging.Agent.Store.DB as DB import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Crypto.Ratchet (PQEncryption (..), PQSupport (..)) import qualified Simplex.Messaging.Crypto.Ratchet as CR +import Simplex.Messaging.Encoding.String (StrJSON (..)) import Simplex.Messaging.Parsers (dropPrefix, sumTypeJSON) import Simplex.Messaging.Protocol (SubscriptionMode (..)) import Simplex.Messaging.Util (AnyError (..)) @@ -413,13 +415,13 @@ createContact db cxt user profile = do void $ createContact_ db cxt user profile emptyChatPrefs Nothing "" currentTs createContact_ :: DB.Connection -> StoreCxt -> User -> Profile -> Preferences -> Maybe (ACreatedConnLink, Maybe SharedMsgId) -> LocalAlias -> UTCTime -> ExceptT StoreError IO ContactId -createContact_ db cxt User {userId} Profile {displayName, fullName, shortDescr, image, contactLink, peerType, badge, preferences} ctUserPreferences prepared localAlias currentTs = +createContact_ db cxt User {userId} Profile {displayName, fullName, shortDescr, image, contactLink, contactDomain, peerType, badge, preferences} ctUserPreferences prepared localAlias currentTs = ExceptT . withLocalDisplayName db userId displayName $ \ldn -> do badgeVerified <- verifyBadge_ (badgeKeys cxt) badge DB.execute db - "INSERT INTO contact_profiles (display_name, full_name, short_descr, image, contact_link, chat_peer_type, user_id, local_alias, preferences, created_at, updated_at, badge_proof, badge_pres_header, badge_expiry, badge_type, badge_verified, badge_extra, badge_master_key, badge_signature, badge_key_idx) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" - ((displayName, fullName, shortDescr, image, contactLink, peerType) :. (userId, localAlias, preferences, currentTs, currentTs) :. badgeToRow badge badgeVerified) + "INSERT INTO contact_profiles (display_name, full_name, short_descr, image, contact_link, chat_peer_type, user_id, local_alias, preferences, created_at, updated_at, badge_proof, badge_pres_header, badge_expiry, badge_type, badge_verified, badge_extra, badge_master_key, badge_signature, badge_key_idx, contact_domain, contact_domain_proof) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" + ((displayName, fullName, shortDescr, image, contactLink, peerType) :. (userId, localAlias, preferences, currentTs, currentTs) :. badgeToRow badge badgeVerified :. contactDomainToRow contactDomain) profileId <- insertedRowId db DB.execute db @@ -486,13 +488,15 @@ type PreparedContactRow = (Maybe AConnectionRequestUri, Maybe AConnShortLink, Ma type GroupDirectInvitationRow = (Maybe ConnReqInvitation, Maybe GroupId, Maybe GroupMemberId, Maybe Int64, BoolInt) -type ContactRow' = (ProfileId, ContactName, ContactName, Text, Maybe Text, Maybe ImageData, Maybe ConnLinkContact, Maybe ChatPeerType, LocalAlias, BoolInt, ContactStatus) :. (Maybe MsgFilter, Maybe BoolInt, BoolInt, Maybe Preferences, Preferences, UTCTime, UTCTime, Maybe UTCTime) :. PreparedContactRow :. (Maybe Int64, Maybe GroupMemberId, BoolInt) :. GroupDirectInvitationRow :. (Maybe UIThemeEntityOverrides, BoolInt, Maybe CustomData, Maybe Int64) :. BadgeRow +type ContactRow' = (ProfileId, ContactName, ContactName, Text, Maybe Text, Maybe ImageData, Maybe ConnLinkContact, Maybe ChatPeerType, LocalAlias, BoolInt, ContactStatus) :. (Maybe MsgFilter, Maybe BoolInt, BoolInt, Maybe Preferences, Preferences, UTCTime, UTCTime, Maybe UTCTime) :. PreparedContactRow :. (Maybe Int64, Maybe GroupMemberId, BoolInt) :. GroupDirectInvitationRow :. (Maybe UIThemeEntityOverrides, BoolInt, Maybe CustomData, Maybe Int64) :. BadgeRow :. ContactDomainRow type ContactRow = Only ContactId :. ContactRow' +type ContactDomainRow = (Maybe SimplexDomain, Maybe SimplexDomainProof, Maybe BoolInt) + toContact :: UTCTime -> StoreCxt -> User -> [ChatTagId] -> ContactRow :. MaybeConnectionRow -> Contact -toContact now cxt user chatTags ((Only contactId :. (profileId, localDisplayName, displayName, fullName, shortDescr, image, contactLink, peerType, localAlias, BI contactUsed, contactStatus) :. (enableNtfs_, sendRcpts, BI favorite, preferences, userPreferences, createdAt, updatedAt, chatTs) :. preparedContactRow :. (contactRequestId, contactGroupMemberId, BI contactGrpInvSent) :. groupDirectInvRow :. (uiThemes, BI chatDeleted, customData, chatItemTTL) :. badgeRow) :. connRow) = - let profile = LocalProfile {profileId, displayName, fullName, shortDescr, image, contactLink, peerType, localBadge = rowToBadge now badgeRow, preferences, localAlias} +toContact now cxt user chatTags ((Only contactId :. (profileId, localDisplayName, displayName, fullName, shortDescr, image, contactLink, peerType, localAlias, BI contactUsed, contactStatus) :. (enableNtfs_, sendRcpts, BI favorite, preferences, userPreferences, createdAt, updatedAt, chatTs) :. preparedContactRow :. (contactRequestId, contactGroupMemberId, BI contactGrpInvSent) :. groupDirectInvRow :. (uiThemes, BI chatDeleted, customData, chatItemTTL) :. badgeRow :. domainRow) :. connRow) = + let profile = LocalProfile {profileId, displayName, fullName, shortDescr, image, contactLink, contactDomain = rowToContactDomain domainRow, contactDomainVerified = rowToDomainVerified domainRow, peerType, localBadge = rowToBadge now badgeRow, preferences, localAlias} activeConn = toMaybeConnection cxt connRow chatSettings = ChatSettings {enableNtfs = fromMaybe MFAll enableNtfs_, sendRcpts = unBI <$> sendRcpts, favorite} incognito = maybe False connIncognito activeConn @@ -501,6 +505,15 @@ toContact now cxt user chatTags ((Only contactId :. (profileId, localDisplayName groupDirectInv = toGroupDirectInvitation groupDirectInvRow in Contact {contactId, localDisplayName, profile, activeConn, contactUsed, contactStatus, chatSettings, userPreferences, mergedPreferences, createdAt, updatedAt, chatTs, preparedContact, contactRequestId, contactGroupMemberId, contactGrpInvSent, groupDirectInv, chatTags, chatItemTTL, uiThemes, chatDeleted, customData} +rowToContactDomain :: ContactDomainRow -> Maybe SimplexDomainClaim +rowToContactDomain (domain_, domainProof_, _) = (`SimplexDomainClaim` domainProof_) . StrJSON <$> domain_ + +rowToDomainVerified :: ContactDomainRow -> Maybe Bool +rowToDomainVerified (_, _, domainVerification_) = unBI <$> domainVerification_ + +contactDomainToRow :: Maybe SimplexDomainClaim -> (Maybe SimplexDomain, Maybe SimplexDomainProof) +contactDomainToRow d = (claimDomain <$> d, proof =<< d) + toPreparedContact :: PreparedContactRow -> Maybe PreparedContact toPreparedContact (connFullLink, connShortLink, welcomeSharedMsgId, requestSharedMsgId) = (\cl@(ACCL m _) -> PreparedContact {connLinkToConnect = cl, uiConnLinkType = connMode m, welcomeSharedMsgId, requestSharedMsgId}) @@ -524,18 +537,18 @@ getProfileById db userId profileId = do DB.query db [sql| - SELECT cp.contact_profile_id, cp.display_name, cp.full_name, cp.short_descr, cp.image, cp.contact_link, cp.chat_peer_type, cp.local_alias, cp.preferences, - cp.badge_proof, cp.badge_pres_header, cp.badge_expiry, cp.badge_type, cp.badge_verified, cp.badge_extra, cp.badge_master_key, cp.badge_signature, cp.badge_key_idx + SELECT cp.contact_profile_id, cp.display_name, cp.full_name, cp.short_descr, cp.image, cp.contact_link, cp.chat_peer_type, cp.local_alias, cp.preferences, -- , ct.user_preferences + cp.badge_proof, cp.badge_pres_header, cp.badge_expiry, cp.badge_type, cp.badge_verified, cp.badge_extra, cp.badge_master_key, cp.badge_signature, cp.badge_key_idx, cp.contact_domain, cp.contact_domain_proof, cp.contact_domain_verified FROM contact_profiles cp WHERE cp.user_id = ? AND cp.contact_profile_id = ? |] (userId, profileId) -type ContactRequestRow = (Int64, ContactName, AgentInvId, Maybe ContactId, Maybe GroupId, Maybe Int64) :. (Int64, ContactName, Text, Maybe Text, Maybe ImageData, Maybe ConnLinkContact, Maybe ChatPeerType, LocalAlias) :. (Maybe XContactId, PQSupport, Maybe SharedMsgId, Maybe SharedMsgId, Maybe Preferences, UTCTime, UTCTime, VersionChat, VersionChat) :. BadgeRow +type ContactRequestRow = (Int64, ContactName, AgentInvId, Maybe ContactId, Maybe GroupId, Maybe Int64) :. (Int64, ContactName, Text, Maybe Text, Maybe ImageData, Maybe ConnLinkContact, Maybe ChatPeerType, LocalAlias) :. (Maybe XContactId, PQSupport, Maybe SharedMsgId, Maybe SharedMsgId, Maybe Preferences, UTCTime, UTCTime, VersionChat, VersionChat) :. BadgeRow :. ContactDomainRow toContactRequest :: UTCTime -> ContactRequestRow -> UserContactRequest -toContactRequest now ((contactRequestId, localDisplayName, agentInvitationId, contactId_, businessGroupId_, userContactLinkId_) :. (profileId, displayName, fullName, shortDescr, image, contactLink, peerType, localAlias) :. (xContactId, pqSupport, welcomeSharedMsgId, requestSharedMsgId, preferences, createdAt, updatedAt, minVer, maxVer) :. badgeRow) = do - let profile = LocalProfile {profileId, displayName, fullName, shortDescr, image, contactLink, peerType, preferences, localBadge = rowToBadge now badgeRow, localAlias} +toContactRequest now ((contactRequestId, localDisplayName, agentInvitationId, contactId_, businessGroupId_, userContactLinkId_) :. (profileId, displayName, fullName, shortDescr, image, contactLink, peerType, localAlias) :. (xContactId, pqSupport, welcomeSharedMsgId, requestSharedMsgId, preferences, createdAt, updatedAt, minVer, maxVer) :. badgeRow :. domainRow) = do + let profile = LocalProfile {profileId, displayName, fullName, shortDescr, image, contactLink, contactDomain = rowToContactDomain domainRow, contactDomainVerified = rowToDomainVerified domainRow, peerType, preferences, localBadge = rowToBadge now badgeRow, localAlias} cReqChatVRange = fromMaybe (versionToRange maxVer) $ safeVersionRange minVer maxVer in UserContactRequest {contactRequestId, agentInvitationId, contactId_, businessGroupId_, userContactLinkId_, cReqChatVRange, localDisplayName, profileId, profile, xContactId, pqSupport, welcomeSharedMsgId, requestSharedMsgId, createdAt, updatedAt} @@ -544,17 +557,17 @@ userQuery = [sql| SELECT u.user_id, u.agent_user_id, u.contact_id, ucp.contact_profile_id, u.active_user, u.active_order, u.local_display_name, ucp.full_name, ucp.short_descr, ucp.image, ucp.contact_link, ucp.chat_peer_type, ucp.preferences, u.show_ntfs, u.send_rcpts_contacts, u.send_rcpts_small_groups, u.auto_accept_member_contacts, u.view_pwd_hash, u.view_pwd_salt, u.user_member_profile_updated_at, u.is_user_chat_relay, u.client_service, u.ui_themes, - ucp.badge_proof, ucp.badge_pres_header, ucp.badge_expiry, ucp.badge_type, ucp.badge_verified, ucp.badge_extra, ucp.badge_master_key, ucp.badge_signature, ucp.badge_key_idx + ucp.badge_proof, ucp.badge_pres_header, ucp.badge_expiry, ucp.badge_type, ucp.badge_verified, ucp.badge_extra, ucp.badge_master_key, ucp.badge_signature, ucp.badge_key_idx, ucp.contact_domain, ucp.contact_domain_proof, ucp.contact_domain_verified FROM users u JOIN contacts uct ON uct.contact_id = u.contact_id JOIN contact_profiles ucp ON ucp.contact_profile_id = uct.contact_profile_id |] -toUser :: UTCTime -> (UserId, UserId, ContactId, ProfileId, BoolInt, Int64) :. (ContactName, Text, Maybe Text, Maybe ImageData, Maybe ConnLinkContact, Maybe ChatPeerType, Maybe Preferences) :. (BoolInt, BoolInt, BoolInt, BoolInt, Maybe B64UrlByteString, Maybe B64UrlByteString, Maybe UTCTime, BoolInt, BoolInt, Maybe UIThemeEntityOverrides) :. BadgeRow -> User -toUser now ((userId, auId, userContactId, profileId, BI activeUser, activeOrder) :. (displayName, fullName, shortDescr, image, contactLink, peerType, userPreferences) :. (BI showNtfs, BI sendRcptsContacts, BI sendRcptsSmallGroups, BI autoAcceptMemberContacts, viewPwdHash_, viewPwdSalt_, userMemberProfileUpdatedAt, BI userChatRelay, BI clientService, uiThemes) :. badgeRow) = +toUser :: UTCTime -> (UserId, UserId, ContactId, ProfileId, BoolInt, Int64) :. (ContactName, Text, Maybe Text, Maybe ImageData, Maybe ConnLinkContact, Maybe ChatPeerType, Maybe Preferences) :. (BoolInt, BoolInt, BoolInt, BoolInt, Maybe B64UrlByteString, Maybe B64UrlByteString, Maybe UTCTime, BoolInt, BoolInt, Maybe UIThemeEntityOverrides) :. BadgeRow :. ContactDomainRow -> User +toUser now ((userId, auId, userContactId, profileId, BI activeUser, activeOrder) :. (displayName, fullName, shortDescr, image, contactLink, peerType, userPreferences) :. (BI showNtfs, BI sendRcptsContacts, BI sendRcptsSmallGroups, BI autoAcceptMemberContacts, viewPwdHash_, viewPwdSalt_, userMemberProfileUpdatedAt, BI userChatRelay, BI clientService, uiThemes) :. badgeRow :. domainRow) = User {userId, agentUserId = AgentUserId auId, userContactId, localDisplayName = displayName, profile, activeUser, activeOrder, fullPreferences, showNtfs, sendRcptsContacts, sendRcptsSmallGroups, autoAcceptMemberContacts, viewPwdHash, userMemberProfileUpdatedAt, userChatRelay = BoolDef userChatRelay, clientService = BoolDef clientService, uiThemes} where - profile = LocalProfile {profileId, displayName, fullName, shortDescr, image, contactLink, peerType, localBadge = rowToBadge now badgeRow, preferences = userPreferences, localAlias = ""} + profile = LocalProfile {profileId, displayName, fullName, shortDescr, image, contactLink, contactDomain = rowToContactDomain domainRow, contactDomainVerified = rowToDomainVerified domainRow, peerType, localBadge = rowToBadge now badgeRow, preferences = userPreferences, localAlias = ""} fullPreferences = fullPreferences' userPreferences viewPwdHash = UserPwdHash <$> viewPwdHash_ <*> viewPwdSalt_ @@ -670,16 +683,16 @@ type BusinessChatInfoRow = (Maybe BusinessChatType, Maybe MemberId, Maybe Member type GroupKeysRow = (Maybe C.PrivateKeyEd25519, Maybe C.PublicKeyEd25519, Maybe C.PrivateKeyEd25519) -type GroupInfoRow = (Int64, GroupName, GroupName, Text, Maybe Text, Text, Maybe Text, Maybe ImageData, Maybe GroupType, Maybe ShortLinkContact, Maybe B64UrlByteString) :. PublicGroupAccessRow :. (Maybe MsgFilter, Maybe BoolInt, BoolInt, Maybe GroupPreferences, Maybe GroupMemberAdmission) :. (UTCTime, UTCTime, Maybe UTCTime, Maybe UTCTime) :. PreparedGroupRow :. BusinessChatInfoRow :. (BoolInt, Maybe RelayStatus, Maybe UIThemeEntityOverrides, Int64, Maybe Int64, Maybe VersionRoster, Maybe CustomData, Maybe Int64, Int, Maybe ConnReqContact) :. GroupKeysRow :. GroupMemberRow +type GroupInfoRow = (Int64, GroupName, GroupName, Text, Maybe Text, Text, Maybe Text, Maybe ImageData, Maybe GroupType, Maybe ShortLinkContact, Maybe B64UrlByteString) :. PublicGroupAccessRow :. (Maybe MsgFilter, Maybe BoolInt, BoolInt, Maybe GroupPreferences, Maybe GroupMemberAdmission) :. (UTCTime, UTCTime, Maybe UTCTime, Maybe UTCTime) :. PreparedGroupRow :. BusinessChatInfoRow :. (BoolInt, Maybe RelayStatus, Maybe UIThemeEntityOverrides, Int64, Maybe Int64, Maybe VersionRoster, Maybe CustomData, Maybe Int64, Int, Maybe ConnReqContact, Maybe BoolInt) :. GroupKeysRow :. GroupMemberRow -type PublicGroupAccessRow = (Maybe Text, Maybe Text, Maybe BoolInt, Maybe BoolInt) +type PublicGroupAccessRow = (Maybe Text, Maybe SimplexDomain, Maybe BoolInt, Maybe BoolInt, Maybe SimplexDomainProof) type GroupMemberRow = (GroupMemberId, GroupId, Int64, MemberId, VersionChat, VersionChat, GroupMemberRole, GroupMemberCategory, GroupMemberStatus, BoolInt, Maybe MemberRestrictionStatus) :. (Maybe Int64, Maybe GroupMemberId, ContactName, Maybe ContactId, ProfileId) :. ProfileRow :. (UTCTime, UTCTime) :. (Maybe UTCTime, Int64, Int64, Int64, Maybe UTCTime, Maybe C.PublicKeyEd25519, Maybe ShortLinkContact) -type ProfileRow = (ProfileId, ContactName, Text, Maybe Text, Maybe ImageData, Maybe ConnLinkContact, Maybe ChatPeerType, LocalAlias, Maybe Preferences) :. BadgeRow +type ProfileRow = (ProfileId, ContactName, Text, Maybe Text, Maybe ImageData, Maybe ConnLinkContact, Maybe ChatPeerType, LocalAlias, Maybe Preferences) :. BadgeRow :. ContactDomainRow toGroupInfo :: UTCTime -> StoreCxt -> Int64 -> [ChatTagId] -> GroupInfoRow -> GroupInfo -toGroupInfo now cxt userContactId chatTags ((groupId, localDisplayName, displayName, fullName, shortDescr, localAlias, description, image, groupType_, groupLink_, publicGroupId_) :. accessRow :. (enableNtfs_, sendRcpts, BI favorite, groupPreferences, memberAdmission) :. (createdAt, updatedAt, chatTs, userMemberProfileSentAt) :. preparedGroupRow :. businessRow :. (BI useRelays, relayOwnStatus, uiThemes, currentMembers, publicMemberCount, rosterVersion, customData, chatItemTTL, membersRequireAttention, viaGroupLinkUri) :. groupKeysRow :. userMemberRow) = +toGroupInfo now cxt userContactId chatTags ((groupId, localDisplayName, displayName, fullName, shortDescr, localAlias, description, image, groupType_, groupLink_, publicGroupId_) :. accessRow :. (enableNtfs_, sendRcpts, BI favorite, groupPreferences, memberAdmission) :. (createdAt, updatedAt, chatTs, userMemberProfileSentAt) :. preparedGroupRow :. businessRow :. (BI useRelays, relayOwnStatus, uiThemes, currentMembers, publicMemberCount, rosterVersion, customData, chatItemTTL, membersRequireAttention, viaGroupLinkUri, groupDomainVerified) :. groupKeysRow :. userMemberRow) = let membership = (toGroupMember now userContactId userMemberRow) {memberChatVRange = vr cxt} chatSettings = ChatSettings {enableNtfs = fromMaybe MFAll enableNtfs_, sendRcpts = unBI <$> sendRcpts, favorite} fullGroupPreferences = mergeGroupPreferences groupPreferences @@ -689,7 +702,7 @@ toGroupInfo now cxt userContactId chatTags ((groupId, localDisplayName, displayN businessChat = toBusinessChatInfo businessRow preparedGroup = toPreparedGroup preparedGroupRow groupSummary = GroupSummary {currentMembers, publicMemberCount} - in GroupInfo {groupId, useRelays = BoolDef useRelays, relayOwnStatus, localDisplayName, groupProfile, localAlias, businessChat, fullGroupPreferences, membership, chatSettings, createdAt, updatedAt, chatTs, userMemberProfileSentAt, preparedGroup, chatTags, chatItemTTL, uiThemes, groupSummary, rosterVersion, customData, membersRequireAttention, viaGroupLinkUri, groupKeys} + in GroupInfo {groupId, useRelays = BoolDef useRelays, relayOwnStatus, localDisplayName, groupProfile, localAlias, businessChat, fullGroupPreferences, membership, chatSettings, createdAt, updatedAt, chatTs, userMemberProfileSentAt, preparedGroup, chatTags, chatItemTTL, uiThemes, groupSummary, rosterVersion, customData, membersRequireAttention, viaGroupLinkUri, groupKeys, groupDomainVerified = unBI <$> groupDomainVerified} toPreparedGroup :: PreparedGroupRow -> Maybe PreparedGroup toPreparedGroup = \case @@ -704,14 +717,14 @@ toPublicGroupProfile _ _ _ _ = Nothing publicGroupAccessRow :: Maybe PublicGroupProfile -> PublicGroupAccessRow publicGroupAccessRow pgp = case pgp >>= publicGroupAccess of - Just PublicGroupAccess {groupWebPage, groupDomain, domainWebPage, allowEmbedding} -> - (groupWebPage, groupDomain, Just (BI domainWebPage), Just (BI allowEmbedding)) - Nothing -> (Nothing, Nothing, Nothing, Nothing) + Just PublicGroupAccess {groupWebPage, groupDomainClaim, domainWebPage, allowEmbedding} -> + (groupWebPage, claimDomain <$> groupDomainClaim, Just (BI domainWebPage), Just (BI allowEmbedding), proof =<< groupDomainClaim) + Nothing -> (Nothing, Nothing, Nothing, Nothing, Nothing) toPublicGroupAccess :: PublicGroupAccessRow -> Maybe PublicGroupAccess -toPublicGroupAccess (groupWebPage, groupDomain, domainWebPage_, allowEmbedding_) - | isJust groupWebPage || isJust groupDomain || domainWebPage || allowEmbedding = - Just PublicGroupAccess {groupWebPage, groupDomain, domainWebPage, allowEmbedding} +toPublicGroupAccess (groupWebPage, groupDomain_, domainWebPage_, allowEmbedding_, groupDomainProof_) + | isJust groupWebPage || isJust groupDomain_ || domainWebPage || allowEmbedding = + Just PublicGroupAccess {groupWebPage, groupDomainClaim = (`SimplexDomainClaim` groupDomainProof_) . StrJSON <$> groupDomain_, domainWebPage, allowEmbedding} | otherwise = Nothing where domainWebPage = maybe False unBI domainWebPage_ @@ -750,7 +763,7 @@ groupMemberQuery = SELECT m.group_member_id, m.group_id, m.index_in_group, m.member_id, m.peer_chat_min_version, m.peer_chat_max_version, m.member_role, m.member_category, m.member_status, m.show_messages, m.member_restriction, m.invited_by, m.invited_by_group_member_id, m.local_display_name, m.contact_id, m.contact_profile_id, p.contact_profile_id, p.display_name, p.full_name, p.short_descr, p.image, p.contact_link, p.chat_peer_type, p.local_alias, p.preferences, - p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, + p.badge_proof, p.badge_pres_header, p.badge_expiry, p.badge_type, p.badge_verified, p.badge_extra, p.badge_master_key, p.badge_signature, p.badge_key_idx, p.contact_domain, p.contact_domain_proof, p.contact_domain_verified, m.created_at, m.updated_at, m.support_chat_ts, m.support_chat_items_unread, m.support_chat_items_member_attention, m.support_chat_items_mentions, m.support_chat_last_msg_from_member_ts, m.member_pub_key, m.relay_link, c.connection_id, c.agent_conn_id, c.conn_level, c.via_contact, c.via_user_contact_link, c.via_group_link, c.group_link_id, c.xcontact_id, c.custom_user_profile_id, @@ -767,8 +780,8 @@ toContactMember now cxt User {userContactId} (memberRow :. connRow) = (toGroupMember now userContactId memberRow) {activeConn = toMaybeConnection cxt connRow} rowToLocalProfile :: UTCTime -> ProfileRow -> LocalProfile -rowToLocalProfile now ((profileId, displayName, fullName, shortDescr, image, contactLink, peerType, localAlias, preferences) :. badgeRow) = - LocalProfile {profileId, displayName, fullName, shortDescr, image, contactLink, peerType, localBadge = rowToBadge now badgeRow, localAlias, preferences} +rowToLocalProfile now ((profileId, displayName, fullName, shortDescr, image, contactLink, peerType, localAlias, preferences) :. badgeRow :. domainRow) = + LocalProfile {profileId, displayName, fullName, shortDescr, image, contactLink, contactDomain = rowToContactDomain domainRow, contactDomainVerified = rowToDomainVerified domainRow, peerType, localBadge = rowToBadge now badgeRow, localAlias, preferences} toBusinessChatInfo :: BusinessChatInfoRow -> Maybe BusinessChatInfo toBusinessChatInfo (Just chatType, Just businessId, Just customerId) = Just BusinessChatInfo {chatType, businessId, customerId} @@ -783,19 +796,19 @@ groupInfoQueryFields = SELECT -- GroupInfo g.group_id, g.local_display_name, gp.display_name, gp.full_name, gp.short_descr, g.local_alias, gp.description, gp.image, gp.group_type, gp.group_link, gp.public_group_id, - gp.group_web_page, gp.group_domain, gp.domain_web_page, gp.allow_embedding, + gp.group_web_page, gp.group_domain, gp.domain_web_page, gp.allow_embedding, gp.group_domain_proof, g.enable_ntfs, g.send_rcpts, g.favorite, gp.preferences, gp.member_admission, g.created_at, g.updated_at, g.chat_ts, g.user_member_profile_sent_at, g.conn_full_link_to_connect, g.conn_short_link_to_connect, g.conn_link_prepared_connection, g.conn_link_started_connection, g.welcome_shared_msg_id, g.request_shared_msg_id, g.business_chat, g.business_member_id, g.customer_member_id, g.use_relays, g.relay_own_status, - g.ui_themes, g.summary_current_members_count, g.public_member_count, g.roster_version, g.custom_data, g.chat_item_ttl, g.members_require_attention, g.via_group_link_uri, + g.ui_themes, g.summary_current_members_count, g.public_member_count, g.roster_version, g.custom_data, g.chat_item_ttl, g.members_require_attention, g.via_group_link_uri, g.group_domain_verified, g.root_priv_key, g.root_pub_key, g.member_priv_key, -- GroupMember - membership mu.group_member_id, mu.group_id, mu.index_in_group, mu.member_id, mu.peer_chat_min_version, mu.peer_chat_max_version, mu.member_role, mu.member_category, mu.member_status, mu.show_messages, mu.member_restriction, mu.invited_by, mu.invited_by_group_member_id, mu.local_display_name, mu.contact_id, mu.contact_profile_id, pu.contact_profile_id, pu.display_name, pu.full_name, pu.short_descr, pu.image, pu.contact_link, pu.chat_peer_type, pu.local_alias, pu.preferences, - pu.badge_proof, pu.badge_pres_header, pu.badge_expiry, pu.badge_type, pu.badge_verified, pu.badge_extra, pu.badge_master_key, pu.badge_signature, pu.badge_key_idx, + pu.badge_proof, pu.badge_pres_header, pu.badge_expiry, pu.badge_type, pu.badge_verified, pu.badge_extra, pu.badge_master_key, pu.badge_signature, pu.badge_key_idx, pu.contact_domain, pu.contact_domain_proof, pu.contact_domain_verified, mu.created_at, mu.updated_at, mu.support_chat_ts, mu.support_chat_items_unread, mu.support_chat_items_member_attention, mu.support_chat_items_mentions, mu.support_chat_last_msg_from_member_ts, mu.member_pub_key, mu.relay_link |] diff --git a/src/Simplex/Chat/Types.hs b/src/Simplex/Chat/Types.hs index 538faf8cac..edf4aab33a 100644 --- a/src/Simplex/Chat/Types.hs +++ b/src/Simplex/Chat/Types.hs @@ -4,6 +4,7 @@ {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DerivingStrategies #-} +{-# LANGUAGE DerivingVia #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} @@ -19,6 +20,7 @@ {-# LANGUAGE StrictData #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilyDependencies #-} +{-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -Wno-unrecognised-pragmas #-} {-# OPTIONS_GHC -fno-warn-ambiguous-fields #-} @@ -34,6 +36,7 @@ import qualified Data.Aeson as J import qualified Data.Aeson.Encoding as JE import qualified Data.Aeson.TH as JQ import qualified Data.Attoparsec.ByteString.Char8 as A +import Data.Attoparsec.Combinator (lookAhead) import qualified Data.ByteString.Base64 as B64 import Data.ByteString.Char8 (ByteString, pack, unpack) import qualified Data.ByteString.Char8 as B @@ -46,16 +49,18 @@ import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import Data.Time.Clock (UTCTime) +import Data.Type.Equality (testEquality, (:~:) (Refl)) import Data.Typeable (Typeable) import Data.Word (Word16) import Simplex.Chat.Badges (BadgeInfo (..), BadgeProof (..), BadgeStatus (..), LocalBadge (..), localBadgeInfo, localBadgeStatus, mkBadgeStatus, verifyBadge) +import Simplex.Chat.Names (SimplexDomainClaim (..)) import Simplex.Messaging.Crypto.BBS (BBSPublicKey) import Simplex.Chat.Types.Preferences import Simplex.Chat.Types.Shared import Simplex.Chat.Types.UITheme import Simplex.FileTransfer.Description (FileDigest) import Simplex.FileTransfer.Types (RcvFileId, SndFileId) -import Simplex.Messaging.Agent.Protocol (ACorrId, ACreatedConnLink, AEventTag (..), AEvtTag (..), ConnId, ConnShortLink (..), ConnectionLink, ConnectionMode (..), ConnectionRequestUri, ContactConnType (..), CreatedConnLink (..), InvitationId, SAEntity (..), UserId) +import Simplex.Messaging.Agent.Protocol (ACorrId, ACreatedConnLink, AConnectionLink (..), AEventTag (..), AEvtTag (..), ConnId, ConnShortLink (..), ConnectionLink (..), ConnectionMode (..), ConnectionModeI, ConnectionRequestUri, ContactConnType (..), CreatedConnLink (..), InvitationId, SAEntity (..), SConnectionMode (..), SimplexDomain, SimplexNameInfo (..), UserId) import Simplex.Messaging.Agent.Store.DB (Binary (..), blobFieldDecoder, fromTextField_) import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Crypto.File (CryptoFileArgs (..)) @@ -493,7 +498,8 @@ data GroupInfo = GroupInfo rosterVersion :: Maybe VersionRoster, membersRequireAttention :: Int, viaGroupLinkUri :: Maybe ConnReqContact, - groupKeys :: Maybe GroupKeys + groupKeys :: Maybe GroupKeys, + groupDomainVerified :: Maybe Bool } deriving (Eq, Show) @@ -641,12 +647,6 @@ groupFeatureUserAllowed :: GroupFeatureRoleI f => SGroupFeature f -> GroupInfo - groupFeatureUserAllowed feature GroupInfo {membership = GroupMember {memberRole}, fullGroupPreferences} = groupFeatureMemberAllowed' feature memberRole fullGroupPreferences --- A connection link in a profile description enables a direct connection, so a description --- keeps its links only when both SimpleX links and direct messages are allowed. -groupUserAllowSimplexLinks :: GroupInfo -> Bool -groupUserAllowSimplexLinks g = - groupFeatureUserAllowed SGFSimplexLinks g && groupFeatureUserAllowed SGFDirectMessages g - mergeUserChatPrefs :: User -> Contact -> FullPreferences mergeUserChatPrefs user ct = mergeUserChatPrefs' user (contactConnIncognito ct) (userPreferences ct) @@ -698,7 +698,8 @@ data Profile = Profile contactLink :: Maybe ConnLinkContact, preferences :: Maybe Preferences, peerType :: Maybe ChatPeerType, - badge :: Maybe BadgeProof + badge :: Maybe BadgeProof, + contactDomain :: Maybe SimplexDomainClaim -- fields that should not be read into this data type to prevent sending them as part of profile to contacts: -- - contact_profile_id -- - incognito @@ -731,21 +732,22 @@ instance TextEncoding ChatPeerType where profileFromName :: ContactName -> Profile profileFromName displayName = - Profile {displayName, fullName = "", shortDescr = Nothing, image = Nothing, contactLink = Nothing, preferences = Nothing, peerType = Nothing, badge = Nothing} + Profile {displayName, fullName = "", shortDescr = Nothing, image = Nothing, contactLink = Nothing, preferences = Nothing, peerType = Nothing, badge = Nothing, contactDomain = Nothing} -- check if profiles match ignoring preferences profilesMatch :: LocalProfile -> LocalProfile -> Bool profilesMatch - LocalProfile {displayName = n1, fullName = fn1, image = i1} - LocalProfile {displayName = n2, fullName = fn2, image = i2} = - n1 == n2 && fn1 == fn2 && i1 == i2 + LocalProfile {displayName = n1, fullName = fn1, image = i1, shortDescr = d1} + LocalProfile {displayName = n2, fullName = fn2, image = i2, shortDescr = d2} = + n1 == n2 && fn1 == fn2 && i1 == i2 && d1 == d2 -- equal for profile-update detection: badge proofs are re-generated for every presentation, -- so compare badges by disclosed info (not proof bytes) - a re-presentation of the same badge is a no-op sameProfileContent :: Profile -> Profile -> Bool sameProfileContent p@Profile {badge = b} p'@Profile {badge = b'} = - p {badge = Nothing} == p' {badge = Nothing} && (proofInfo <$> b) == (proofInfo <$> b') + clearProofs p == clearProofs p' && (proofInfo <$> b) == (proofInfo <$> b') where + clearProofs pr@Profile {contactDomain} = pr {badge = Nothing, contactDomain = (\d -> d {proof = Nothing} :: SimplexDomainClaim) <$> contactDomain} proofInfo :: BadgeProof -> BadgeInfo proofInfo (BadgeProof _ _ _ info) = info @@ -781,29 +783,31 @@ data LocalProfile = LocalProfile preferences :: Maybe Preferences, peerType :: Maybe ChatPeerType, localBadge :: Maybe LocalBadge, - localAlias :: LocalAlias + localAlias :: LocalAlias, + contactDomain :: Maybe SimplexDomainClaim, + contactDomainVerified :: Maybe Bool } deriving (Eq, Show) localProfileId :: LocalProfile -> ProfileId localProfileId LocalProfile {profileId} = profileId -toLocalProfile :: ProfileId -> Profile -> LocalAlias -> UTCTime -> Maybe Bool -> LocalProfile -toLocalProfile profileId Profile {displayName, fullName, shortDescr, image, contactLink, preferences, peerType, badge} localAlias now verified = - LocalProfile {profileId, displayName, fullName, shortDescr, image, contactLink, preferences, peerType, localBadge, localAlias} +toLocalProfile :: ProfileId -> Profile -> LocalAlias -> UTCTime -> Maybe Bool -> Maybe Bool -> LocalProfile +toLocalProfile profileId Profile {displayName, fullName, shortDescr, image, contactLink, preferences, peerType, badge, contactDomain} localAlias now badgeVerified contactDomainVerified = + LocalProfile {profileId, displayName, fullName, shortDescr, image, contactLink, preferences, peerType, localBadge, localAlias, contactDomain, contactDomainVerified} where - localBadge = (\b@(BadgeProof _ _ _ info) -> PeerBadge b (mkBadgeStatus now verified info)) <$> badge + localBadge = (\b@(BadgeProof _ _ _ info) -> PeerBadge b (mkBadgeStatus now badgeVerified info)) <$> badge fromLocalProfile :: LocalProfile -> Profile -fromLocalProfile LocalProfile {displayName, fullName, shortDescr, image, contactLink, preferences, peerType, localBadge} = - Profile {displayName, fullName, shortDescr, image, contactLink, preferences, peerType, badge = localBadge >>= wireBadge} +fromLocalProfile LocalProfile {displayName, fullName, shortDescr, image, contactLink, preferences, peerType, localBadge, contactDomain} = + -- the name proof is re-signed on each send + Profile {displayName, fullName, shortDescr, image, contactLink, preferences, peerType, badge = localBadge >>= wireBadge, contactDomain = (\d -> d {proof = Nothing} :: SimplexDomainClaim) <$> contactDomain} where - -- any stored peer proof rides the wire (receivers verify independently); the own credential is presented fresh, and a display-only badge never sends wireBadge :: LocalBadge -> Maybe BadgeProof wireBadge = \case - PeerBadge b _ -> Just b - OwnBadge _ _ -> Nothing - ShownBadge _ _ -> Nothing + PeerBadge b _ -> Just b -- stored peer proof sent as is + OwnBadge _ _ -> Nothing -- the own credential is not sent, proof is generated on send + ShownBadge _ _ -> Nothing -- a display-only badge is not sent profileBadgeVerified :: Map Int BBSPublicKey -> LocalProfile -> Profile -> IO (Maybe Bool) profileBadgeVerified keys LocalProfile {localBadge} Profile {badge = newBadge} = @@ -842,7 +846,7 @@ instance ToField GroupType where toField = toField . textEncode data PublicGroupAccess = PublicGroupAccess { groupWebPage :: Maybe Text, - groupDomain :: Maybe Text, + groupDomainClaim :: Maybe SimplexDomainClaim, domainWebPage :: Bool, allowEmbedding :: Bool } @@ -1782,6 +1786,49 @@ type ConnReqInvitation = ConnectionRequestUri 'CMInvitation type ConnReqContact = ConnectionRequestUri 'CMContact +data ConnectTarget (m :: ConnectionMode) where + CTFullContact :: ConnectionRequestUri 'CMContact -> ConnectTarget 'CMContact + CTShortContact :: ContactNameOrLink -> ConnectTarget 'CMContact + CTDomain :: SimplexDomain -> ConnectTarget 'CMContact + CTInv :: ConnectionLink 'CMInvitation -> ConnectTarget 'CMInvitation + +data ContactNameOrLink = CTName SimplexNameInfo | CTLink (ConnShortLink 'CMContact) + deriving (Eq, Show) + +deriving instance Eq (ConnectTarget m) + +deriving instance Show (ConnectTarget m) + +data AConnectTarget = forall m. ConnectionModeI m => ACTarget (SConnectionMode m) (ConnectTarget m) + deriving (ToJSON, FromJSON) via (StrJSON "AConnectTarget" AConnectTarget) + +instance Eq AConnectTarget where + ACTarget m t == ACTarget m' t' = case testEquality m m' of + Just Refl -> t == t' + _ -> False + +deriving instance Show AConnectTarget + +instance StrEncoding AConnectTarget where + strEncode (ACTarget _ t) = case t of + CTFullContact cr -> strEncode cr + CTShortContact (CTName n) -> strEncode n + CTShortContact (CTLink sl) -> strEncode sl + CTDomain d -> strEncode d + CTInv l -> strEncode l + strP = + (ACTarget SCMContact . CTShortContact . CTName <$> (lookAhead nameStart *> strP)) + <|> (aConnectTarget <$> strP) + <|> (ACTarget SCMContact . CTDomain <$> strP) + where + nameStart = "@" <|> "#" <|> "simplex:/name" + +aConnectTarget :: AConnectionLink -> AConnectTarget +aConnectTarget (ACL SCMInvitation cl) = ACTarget SCMInvitation (CTInv cl) +aConnectTarget (ACL SCMContact cl) = ACTarget SCMContact $ case cl of + CLFull cr -> CTFullContact cr + CLShort sl -> CTShortContact (CTLink sl) + type CreatedLinkInvitation = CreatedConnLink 'CMInvitation type CreatedLinkContact = CreatedConnLink 'CMContact diff --git a/src/Simplex/Chat/View.hs b/src/Simplex/Chat/View.hs index cd7a5daea9..0edfff6d29 100644 --- a/src/Simplex/Chat/View.hs +++ b/src/Simplex/Chat/View.hs @@ -52,6 +52,7 @@ import Simplex.Chat.Remote.AppVersion (AppVersion (..), pattern AppVersionRange) import Simplex.Chat.Remote.Types import Simplex.Chat.Store (AddressSettings (..), AutoAccept (..), StoreError (..), UserContactLink (..)) import Simplex.Chat.Styled +import Simplex.Chat.Names (SimplexDomainClaim (..), claimDomain) import Simplex.Chat.Types import Simplex.Chat.Types.Preferences import Simplex.Chat.Types.Shared @@ -147,6 +148,8 @@ chatResponseToView hu cfg@ChatConfig {logLevel, showReactions, testView} liveIte CRContactRatchetSyncStarted {} -> ["connection synchronization started"] CRGroupMemberRatchetSyncStarted {} -> ["connection synchronization started"] CRConnectionVerified u verified code -> ttyUser u [plain $ if verified then "connection verified" else "connection not verified, current code is " <> code] + CRContactDomainVerified u (Contact {profile = LocalProfile {contactDomain}}) result -> ttyUser u $ viewDomainVerified NTContact (claimDomain <$> contactDomain) result + CRGroupDomainVerified u g result -> ttyUser u $ viewDomainVerified NTPublicGroup (groupSimplexDomain g) result CRContactCode u ct code -> ttyUser u $ viewContactCode ct code testView CRGroupMemberCode u g m code -> ttyUser u $ viewGroupMemberCode g m code testView CRNewChatItems u chatItems -> viewChatItems ttyUser unmuted u chatItems ts tz testView @@ -201,7 +204,7 @@ chatResponseToView hu cfg@ChatConfig {logLevel, showReactions, testView} liveIte CRInvitation u ccLink _ -> ttyUser u $ viewConnReqInvitation ccLink CRConnectionIncognitoUpdated u c customUserProfile -> ttyUser u $ viewConnectionIncognitoUpdated c customUserProfile testView CRConnectionUserChanged u c c' nu -> ttyUser u $ viewConnectionUserChanged u c nu c' - CRConnectionPlan u connLink connectionPlan -> ttyUser u $ viewConnectionPlan cfg connLink connectionPlan + CRConnectionPlan u connLink _ otherSimplexName connectionPlan -> ttyUser u $ viewConnectionPlan cfg connLink connectionPlan <> otherSimplexNameNote otherSimplexName CRNewPreparedChat u (AChat _ (Chat cInfo _ _)) -> ttyUser u $ case cInfo of DirectChat ct -> [ttyContact' ct <> ": contact is prepared"] GroupChat g _ -> [ttyGroup' g <> ": group is prepared"] @@ -1125,6 +1128,31 @@ simplexChatContact' = \case CLFull (CRContactUri crData) -> CLFull $ CRContactUri crData {crScheme = simplexChat} l@(CLShort _) -> l +groupSimplexDomain :: GroupInfo -> Maybe SimplexDomain +groupSimplexDomain GroupInfo {groupProfile = GroupProfile {publicGroup}} = + claimDomain <$> (publicGroup >>= publicGroupAccess >>= groupDomainClaim) + +viewDomainVerified :: SimplexNameType -> Maybe SimplexDomain -> Maybe Text -> [StyledString] +viewDomainVerified nameType domain_ result = + let nameStr = maybe "name" (\d -> "SimpleX name " <> shortNameInfoStr (SimplexNameInfo nameType d)) domain_ + in case result of + Nothing -> [plain nameStr <> " verified"] + Just reason -> [plain nameStr <> " not verified: " <> plain reason] + +-- §4.7: show a peer's claimed name only with its verification context — "verified" / "verification +-- failed" when a status is recorded, "unverified" when there is a proof but no status yet, and nothing +-- at all when there is neither (an unproven, unverifiable claim is not shown). +simplexDomainLine :: SimplexNameType -> Maybe SimplexDomainClaim -> Maybe Bool -> [StyledString] +simplexDomainLine _ Nothing _ = [] +simplexDomainLine nameType (Just SimplexDomainClaim {domain, proof}) status = case status of + Just True -> [line "verified"] + Just False -> [line "verification failed"] + Nothing + | isJust proof -> [line "unverified"] + | otherwise -> [] + where + line s = plain $ "SimpleX name: " <> shortNameInfoStr (SimplexNameInfo nameType (unStrJSON domain)) <> " (" <> s <> ")" + -- TODO [short links] show all settings viewAddressSettings :: AddressSettings -> [StyledString] viewAddressSettings AddressSettings {businessAddress, autoAccept, autoReply} = case autoAccept of @@ -1142,12 +1170,14 @@ groupLink_ :: StyledString -> GroupInfo -> GroupLink -> [StyledString] groupLink_ intro g GroupLink {connLinkContact = CCLink cReq shortLink, acceptMemberRole} = [ intro, "", - plain $ maybe cReqStr strEncode shortLink, - "", - "Anybody can connect to you and join group as " <> showRole acceptMemberRole <> " with: " <> highlight' "/c ", - "to show it again: " <> highlight ("/show link #" <> viewGroupName g), - "to delete it: " <> highlight ("/delete link #" <> viewGroupName g) <> " (joined members will remain connected to you)" + plain $ maybe cReqStr strEncode shortLink ] + <> [plain ("SimpleX name: " <> shortNameInfoStr (SimplexNameInfo NTPublicGroup d)) | Just d <- [groupSimplexDomain g]] + <> [ "", + "Anybody can connect to you and join group as " <> showRole acceptMemberRole <> " with: " <> highlight' "/c ", + "to show it again: " <> highlight ("/show link #" <> viewGroupName g), + "to delete it: " <> highlight ("/delete link #" <> viewGroupName g) <> " (joined members will remain connected to you)" + ] <> ["The group link for old clients: " <> plain cReqStr | isJust shortLink] where cReqStr = strEncode $ simplexChatContact cReq @@ -1223,6 +1253,7 @@ viewGroupLinkRelaysUpdated g groupLink relays = [ "group link:", plain $ maybe cReqStr strEncode shortLink ] + <> [plain ("SimpleX name: " <> shortNameInfoStr (SimplexNameInfo NTPublicGroup d)) | Just d <- [groupSimplexDomain g]] where GroupLink {connLinkContact = CCLink cReq shortLink} = groupLink cReqStr = strEncode $ simplexChatContact cReq @@ -1778,11 +1809,12 @@ viewContactBadge = maybe [] $ \lb -> in [plain (textEncode badgeType <> " badge - " <> st), plain expiry] viewContactInfo :: Contact -> Maybe ConnectionStats -> Maybe Profile -> [StyledString] -viewContactInfo ct@Contact {contactId, profile = LocalProfile {localAlias, contactLink, localBadge}, activeConn, uiThemes, customData} stats incognitoProfile = +viewContactInfo ct@Contact {contactId, profile = LocalProfile {localAlias, contactLink, localBadge, contactDomain, contactDomainVerified}, activeConn, uiThemes, customData} stats incognitoProfile = ["contact ID: " <> sShow contactId] <> viewContactBadge localBadge <> maybe [] viewConnectionStats stats - <> maybe [] (\l -> ["contact address: " <> (plain . strEncode) (simplexChatContact' l)]) contactLink + <> maybe [] (\l -> ["contact address: " <> plain (strEncode (simplexChatContact' l))]) contactLink + <> simplexDomainLine NTContact contactDomain contactDomainVerified <> maybe ["you've shared main profile with this contact"] (\p -> ["you've shared incognito profile with this contact: " <> incognitoProfile' p]) @@ -2017,9 +2049,9 @@ viewGroupUpdated access = pg >>= publicGroupAccess access' = pg' >>= publicGroupAccess viewAccess Nothing = " removed" - viewAccess (Just PublicGroupAccess {groupWebPage, groupDomain, domainWebPage, allowEmbedding}) = + viewAccess (Just PublicGroupAccess {groupWebPage, groupDomainClaim, domainWebPage, allowEmbedding}) = maybe "" (\u -> " web=" <> plain u) groupWebPage - <> maybe "" (\d -> " domain=" <> plain d) groupDomain + <> maybe "" (\ni -> " domain=" <> plain (strEncode ni)) (claimDomain <$> groupDomainClaim) <> (if domainWebPage then " domain_page=on" else "") <> (if allowEmbedding then " embed=on" else "") @@ -2112,6 +2144,12 @@ viewGroupUserChanged where userChangedStr = "group " <> ttyGroup' g <> " changed from user " <> plain un <> " to user " <> plain un' +otherSimplexNameNote :: Maybe SimplexNameInfo -> [StyledString] +otherSimplexNameNote = \case + Just ni@(SimplexNameInfo NTPublicGroup _) -> [plain $ "You can also join channel " <> shortNameInfoStr ni] + Just ni@(SimplexNameInfo NTContact _) -> [plain $ "You can also connect to " <> shortNameInfoStr ni <> " in direct chat"] + Nothing -> [] + viewConnectionPlan :: ChatConfig -> ACreatedConnLink -> ConnectionPlan -> [StyledString] viewConnectionPlan ChatConfig {logLevel, testView} _connLink = \case CPInvitationLink ilp -> case ilp of @@ -2120,12 +2158,12 @@ viewConnectionPlan ChatConfig {logLevel, testView} _connLink = \case ILPConnecting Nothing -> [invLink "connecting"] ILPConnecting (Just ct) -> [invLink ("connecting to contact " <> ttyContact' ct)] ILPKnown ct - | nextConnectPrepared ct -> [invLink ("known prepared contact " <> ttyContact' ct)] - | contactDeleted ct -> [invLink ("known deleted contact " <> ttyContact' ct)] + | nextConnectPrepared ct -> [invLink ("known prepared contact " <> ttyContact' ct)] <> contactDomainLine ct + | contactDeleted ct -> [invLink ("known deleted contact " <> ttyContact' ct)] <> contactDomainLine ct | otherwise -> - [ invLink ("known contact " <> ttyContact' ct), - "use " <> ttyToContact' ct <> highlight' "" <> " to send messages" - ] + [invLink ("known contact " <> ttyContact' ct)] + <> contactDomainLine ct + <> ["use " <> ttyToContact' ct <> highlight' "" <> " to send messages"] where invLink = ("invitation link: " <>) invOrBiz = \case @@ -2138,12 +2176,12 @@ viewConnectionPlan ChatConfig {logLevel, testView} _connLink = \case CAPConnectingConfirmReconnect -> [ctAddr "connecting, allowed to reconnect"] CAPConnectingProhibit ct -> [ctAddr ("connecting to contact " <> ttyContact' ct)] CAPKnown ct - | nextConnectPrepared ct -> [ctAddr ("known prepared contact " <> ttyContact' ct)] + | nextConnectPrepared ct -> [ctAddr ("known prepared contact " <> ttyContact' ct)] <> contactDomainLine ct | otherwise -> - [ ctAddr ("known contact " <> ttyContact' ct), - "use " <> ttyToContact' ct <> highlight' "" <> " to send messages" - ] - CAPContactViaAddress ct -> [ctAddr ("known contact without connection " <> ttyContact' ct)] + [ctAddr ("known contact " <> ttyContact' ct)] + <> contactDomainLine ct + <> ["use " <> ttyToContact' ct <> highlight' "" <> " to send messages"] + CAPContactViaAddress ct -> [ctAddr ("known contact without connection " <> ttyContact' ct)] <> contactDomainLine ct where ctAddr = ("contact address: " <>) addrOrBiz = \case @@ -2164,17 +2202,17 @@ viewConnectionPlan ChatConfig {logLevel, testView} _connLink = \case Just PreparedGroup {connLinkStartedConnection} -> case memberStatus m of GSMemUnknown | connLinkStartedConnection -> connecting g - | otherwise -> [knownGroup "prepared "] + | otherwise -> [knownGroup "prepared "] <> groupDomainLine g GSMemAccepted -> connecting g _ - | memberRemoved m -> [knownGroup "deleted "] -- it should not get here, as this plan is returned as GLPOk + | memberRemoved m -> [knownGroup "deleted "] <> groupDomainLine g -- it should not get here, as this plan is returned as GLPOk | otherwise -> knownActive _ -> knownActive where knownActive = - [ knownGroup "", - "use " <> ttyToGroup g Nothing <> highlight' "" <> " to send messages" - ] + [knownGroup ""] + <> groupDomainLine g + <> ["use " <> ttyToGroup g Nothing <> highlight' "" <> " to send messages"] knownGroup prepared = grpOrBizLink g <> ": known " <> prepared <> grpOrBiz g <> " " <> ttyGroup' g GLPNoRelays _ -> [grpLink "channel has no active relays, please try to join later"] GLPUpdateRequired _ -> [grpLink "this group requires a newer version of the app, please upgrade"] @@ -2192,6 +2230,13 @@ viewConnectionPlan ChatConfig {logLevel, testView} _connLink = \case nextConnectPrepared Contact {preparedContact, activeConn} = case preparedContact of Just _ -> maybe True (\c -> connStatus c == ConnPrepared) activeConn _ -> False + contactDomainLine :: Contact -> [StyledString] + contactDomainLine Contact {profile = LocalProfile {contactDomain, contactDomainVerified}} = + simplexDomainLine NTContact contactDomain contactDomainVerified + groupDomainLine :: GroupInfo -> [StyledString] + groupDomainLine GroupInfo {groupDomainVerified, groupProfile = GroupProfile {publicGroup}} = do + let domain = publicGroup >>= publicGroupAccess >>= groupDomainClaim + in simplexDomainLine NTPublicGroup domain groupDomainVerified viewSigVerification = \case Just OVVerified -> ["owner signature: verified"] Just (OVFailed r) -> ["owner signature: FAILED (" <> plain r <> ")"] @@ -2643,6 +2688,12 @@ viewChatError isCmd logLevel testView = \case CEChatNotStopped -> ["error: chat not stopped"] CEChatStoreChanged -> ["error: chat store changed, please restart chat"] CEInvalidConnReq -> viewInvalidConnReq + CESimplexDomainNotReady domain domainErr -> + let reason = case domainErr of + SDENoValidLink -> "has no valid connection link" + SDEUnknownDomain -> "is not included in the connection link's profile" + in [plain $ "SimpleX name " <> strEncode domain <> " " <> reason] + CENotResolvedLocally -> ["no matching chat found, name resolution is disabled"] CEUnsupportedConnReq -> [ "", "Connection link is not supported by the your app version, please ugrade it.", plain updateStr] CEInvalidChatMessage Connection {connId} msgMeta_ msg e -> [ plain $ diff --git a/tests/Bots/BroadcastTests.hs b/tests/Bots/BroadcastTests.hs index 051ee6b304..bfe7b96c7d 100644 --- a/tests/Bots/BroadcastTests.hs +++ b/tests/Bots/BroadcastTests.hs @@ -33,7 +33,7 @@ withBroadcastBot opts test = bot = simplexChatCore testCfg (mkChatOpts opts) $ broadcastBot opts broadcastBotProfile :: Profile -broadcastBotProfile = Profile {displayName = "broadcast_bot", fullName = "Broadcast Bot", shortDescr = Nothing, image = Nothing, contactLink = Nothing, peerType = Just CPTBot, preferences = Nothing, badge = Nothing} +broadcastBotProfile = Profile {displayName = "broadcast_bot", fullName = "Broadcast Bot", shortDescr = Nothing, image = Nothing, contactLink = Nothing, peerType = Just CPTBot, preferences = Nothing, badge = Nothing, contactDomain = Nothing} mkBotOpts :: TestParams -> [KnownContact] -> BroadcastBotOpts mkBotOpts ps publishers = diff --git a/tests/Bots/DirectoryTests.hs b/tests/Bots/DirectoryTests.hs index cd6d549581..025bfe4f66 100644 --- a/tests/Bots/DirectoryTests.hs +++ b/tests/Bots/DirectoryTests.hs @@ -74,6 +74,9 @@ directoryServiceTests = do describe "list and promote groups" $ do it "should list and promote user's groups" $ testListUserGroups True describe "member admission" $ do + it "should require captcha by default for new groups" testCaptchaByDefault + it "should require captcha in all groups with --always-captcha" testAlwaysCaptcha + it "should require admin review in all groups with --knocking" testKnocking it "should ask member to pass captcha screen" testCapthaScreening it "should send voice captcha on /audio command" testVoiceCaptchaScreening it "should retry with voice captcha after switching to audio mode" testVoiceCaptchaRetry @@ -98,7 +101,7 @@ directoryServiceTests = do it "should update subscriber count periodically" testLinkCheckUpdatesCount directoryProfile :: Profile -directoryProfile = Profile {displayName = "SimpleX Directory", fullName = "", shortDescr = Nothing, image = Nothing, contactLink = Nothing, peerType = Just CPTBot, preferences = Nothing, badge = Nothing} +directoryProfile = Profile {displayName = "SimpleX Directory", fullName = "", shortDescr = Nothing, image = Nothing, contactLink = Nothing, peerType = Just CPTBot, preferences = Nothing, badge = Nothing, contactDomain = Nothing} mkDirectoryOpts :: TestParams -> [KnownContact] -> Maybe KnownGroup -> Maybe FilePath -> DirectoryOpts mkDirectoryOpts TestParams {tmpPath = ps} superUsers ownersGroup webFolder = @@ -133,6 +136,9 @@ mkDirectoryOpts TestParams {tmpPath = ps} superUsers ownersGroup webFolder = searchResults = 3, webFolder, linkCheckInterval = 0, + prohibitedToObserver = False, + alwaysCaptcha = False, + knocking = False, testing = True } @@ -169,6 +175,8 @@ testDirectoryService ps = bob <## "Please add it to the group welcome message." bob <## "For example, add:" welcomeWithLink <- dropStrPrefix "'SimpleX Directory'> " . dropTime <$> getTermLine bob + bob <# "'SimpleX Directory'> We recommend allowing direct messages, media, voice, and SimpleX links only for group moderators and admins. Use group preferences to set them." + bob <## "Captcha verification is enabled. Use /'filter 1' to change it." -- putStrLn "*** update profile without link" updateGroupProfile bob "Welcome!" bob <# "'SimpleX Directory'> The profile updated for ID 1 (PSA), but the group link is not added to the welcome message." @@ -396,6 +404,14 @@ testSetRole ps = cath ##> ("/c " <> groupLink) cath <## "connection request sent!" cath <## "#privacy: joining the group..." + cath <## "#privacy: you joined the group, pending approval" + cath <# "#privacy (support) 'SimpleX Directory'> Captcha is generated by SimpleX Directory service." + cath <## "" + cath <## "Send captcha text to join the group privacy." + captcha <- dropStrPrefix "#privacy (support) 'SimpleX Directory'> " . dropTime <$> getTermLine cath + cath #> ("#privacy (support) " <> captcha) + cath <# ("#privacy (support) 'SimpleX Directory'!> > cath " <> captcha) + cath <## " Correct, you joined the group privacy" cath <## "#privacy: you joined the group" cath <#. "#privacy 'SimpleX Directory'> Link to join the group privacy: https://localhost/g#" cath <## "#privacy: member bob (Bob) is connected" @@ -428,12 +444,18 @@ testJoinGroup ps = cath ##> ("/c " <> groupLink) cath <## "connection request sent!" cath <## "#privacy: joining the group..." + cath <## "#privacy: you joined the group, pending approval" + cath <# "#privacy (support) 'SimpleX Directory_1'> Captcha is generated by SimpleX Directory service." + cath <## "" + cath <## "Send captcha text to join the group privacy." + captcha <- dropStrPrefix "#privacy (support) 'SimpleX Directory_1'> " . dropTime <$> getTermLine cath + cath <## "contact and member are merged: 'SimpleX Directory', #privacy 'SimpleX Directory_1'" + cath <## "use @'SimpleX Directory' to send messages" + cath #> ("#privacy (support) " <> captcha) + cath <# ("#privacy (support) 'SimpleX Directory'!> > cath " <> captcha) + cath <## " Correct, you joined the group privacy" cath <## "#privacy: you joined the group" - cath - <### [ "contact and member are merged: 'SimpleX Directory', #privacy 'SimpleX Directory_1'", - "use @'SimpleX Directory' to send messages", - Predicate (\l -> l == welcomeMsg || dropTime_ l == Just ("#privacy 'SimpleX Directory'> " <> welcomeMsg) || dropTime_ l == Just ("#privacy 'SimpleX Directory_1'> " <> welcomeMsg)) - ] + cath <#. "#privacy 'SimpleX Directory'> Link to join the group privacy: https://" cath <## "#privacy: member bob (Bob) is connected" bob <## "#privacy: 'SimpleX Directory' added cath (Catherine) to the group (connecting...)" bob <## "#privacy: new member cath is connected" @@ -788,7 +810,7 @@ testNotSentApprovalBadRoles ps = bob `connectVia` dsLink cath `connectVia` dsLink submitGroup bob "privacy" "Privacy" - welcomeWithLink <- groupAccepted bob "privacy" + welcomeWithLink <- groupAccepted bob "privacy" 1 bob ##> "/mr privacy 'SimpleX Directory' member" bob <## "#privacy: you changed the role of 'SimpleX Directory' to member" updateProfileWithLink bob "privacy" welcomeWithLink 1 @@ -811,7 +833,7 @@ testNotApprovedBadRoles ps = bob `connectVia` dsLink cath `connectVia` dsLink submitGroup bob "privacy" "Privacy" - welcomeWithLink <- groupAccepted bob "privacy" + welcomeWithLink <- groupAccepted bob "privacy" 1 updateProfileWithLink bob "privacy" welcomeWithLink 1 notifySuperUser superUser bob "privacy" "Privacy" welcomeWithLink 1 bob ##> "/mr privacy 'SimpleX Directory' member" @@ -1019,14 +1041,14 @@ testDuplicateAskConfirmation ps = withNewTestChat ps "cath" cathProfile $ \cath -> do bob `connectVia` dsLink submitGroup bob "privacy" "Privacy" - _ <- groupAccepted bob "privacy" + _ <- groupAccepted bob "privacy" 1 cath `connectVia` dsLink submitGroup cath "privacy" "Privacy" cath <# "'SimpleX Directory'> The group privacy (Privacy) is already submitted to the directory." cath <## "To confirm the registration, please send:" cath <# "'SimpleX Directory'> /confirm 1:privacy" cath #> "@'SimpleX Directory' /confirm 1:privacy" - welcomeWithLink <- groupAccepted cath "privacy" + welcomeWithLink <- groupAccepted cath "privacy" 1 groupNotFound bob "privacy" completeRegistrationId superUser cath "privacy" "Privacy" welcomeWithLink 2 1 groupFound bob "privacy" @@ -1050,7 +1072,7 @@ testDuplicateProhibitConfirmation ps = withNewTestChat ps "cath" cathProfile $ \cath -> do bob `connectVia` dsLink submitGroup bob "privacy" "Privacy" - welcomeWithLink <- groupAccepted bob "privacy" + welcomeWithLink <- groupAccepted bob "privacy" 1 cath `connectVia` dsLink submitGroup cath "privacy" "Privacy" cath <# "'SimpleX Directory'> The group privacy (Privacy) is already submitted to the directory." @@ -1069,14 +1091,14 @@ testDuplicateProhibitWhenUpdated ps = withNewTestChat ps "cath" cathProfile $ \cath -> do bob `connectVia` dsLink submitGroup bob "privacy" "Privacy" - welcomeWithLink <- groupAccepted bob "privacy" + welcomeWithLink <- groupAccepted bob "privacy" 1 cath `connectVia` dsLink submitGroup cath "privacy" "Privacy" cath <# "'SimpleX Directory'> The group privacy (Privacy) is already submitted to the directory." cath <## "To confirm the registration, please send:" cath <# "'SimpleX Directory'> /confirm 1:privacy" cath #> "@'SimpleX Directory' /confirm 1:privacy" - welcomeWithLink' <- groupAccepted cath "privacy" + welcomeWithLink' <- groupAccepted cath "privacy" 1 groupNotFound cath "privacy" completeRegistration superUser bob "privacy" "Privacy" welcomeWithLink 1 groupFound cath "privacy" @@ -1100,14 +1122,14 @@ testDuplicateProhibitApproval ps = withNewTestChat ps "cath" cathProfile $ \cath -> do bob `connectVia` dsLink submitGroup bob "privacy" "Privacy" - welcomeWithLink <- groupAccepted bob "privacy" + welcomeWithLink <- groupAccepted bob "privacy" 1 cath `connectVia` dsLink submitGroup cath "privacy" "Privacy" cath <# "'SimpleX Directory'> The group privacy (Privacy) is already submitted to the directory." cath <## "To confirm the registration, please send:" cath <# "'SimpleX Directory'> /confirm 1:privacy" cath #> "@'SimpleX Directory' /confirm 1:privacy" - welcomeWithLink' <- groupAccepted cath "privacy" + welcomeWithLink' <- groupAccepted cath "privacy" 1 updateProfileWithLink cath "privacy" welcomeWithLink' 1 notifySuperUser superUser cath "privacy" "Privacy" welcomeWithLink' 2 groupNotFound cath "privacy" @@ -1194,6 +1216,102 @@ checkListings listed promoted = do map groupName gs `shouldBe` expected groupName DirectoryEntry {displayName} = displayName +testAlwaysCaptcha :: HasCallStack => TestParams -> IO () +testAlwaysCaptcha ps = + withDirectoryServiceOpts ps (\o -> o {alwaysCaptcha = True}) $ \superUser dsLink -> + withNewTestChat ps "bob" bobProfile $ \bob -> + withNewTestChat ps "cath" cathProfile $ \cath -> do + bob `connectVia` dsLink + registerGroup superUser bob "privacy" "Privacy" + -- disable the per-group captcha filter; --always-captcha must still force it + bob #> "@'SimpleX Directory' /filter 1 off" + bob <# "'SimpleX Directory'> > /filter 1 off" + bob <## " Spam filter settings for group privacy set to:" + bob <## "- reject long/inappropriate names: disabled" + bob <## "- pass captcha to join: disabled" + bob <## "" + bob <## "/'filter 1 name' - enable name filter" + bob <## "/'filter 1 captcha' - enable captcha challenge" + bob <## "/'filter 1 name captcha' - enable both" + bob #> "@'SimpleX Directory' /role 1" + bob <# "'SimpleX Directory'> > /role 1" + bob <## " The initial member role for the group privacy is set to member" + bob <## "Send /'role 1 observer' to change it." + bob <## "" + note <- getTermLine bob + let groupLink = dropStrPrefix "Please note: it applies only to members joining via this link: " note + cath ##> ("/c " <> groupLink) + cath <## "connection request sent!" + cath <## "#privacy: joining the group..." + cath <## "#privacy: you joined the group, pending approval" + cath <# "#privacy (support) 'SimpleX Directory'> Captcha is generated by SimpleX Directory service." + cath <## "" + cath <## "Send captcha text to join the group privacy." + captcha <- dropStrPrefix "#privacy (support) 'SimpleX Directory'> " . dropTime <$> getTermLine cath + cath #> ("#privacy (support) " <> captcha) + cath <# ("#privacy (support) 'SimpleX Directory'!> > cath " <> captcha) + cath <## " Correct, you joined the group privacy" + cath <## "#privacy: you joined the group" + cath <#. "#privacy 'SimpleX Directory'> Link to join the group privacy: https://" + cath <## "#privacy: member bob (Bob) is connected" + bob <## "#privacy: 'SimpleX Directory' added cath (Catherine) to the group (connecting...)" + bob <## "#privacy: new member cath is connected" + +testKnocking :: HasCallStack => TestParams -> IO () +testKnocking ps = + withDirectoryServiceOpts ps (\o -> o {knocking = True}) $ \superUser dsLink -> + withNewTestChat ps "bob" bobProfile $ \bob -> + withNewTestChat ps "cath" cathProfile $ \cath -> do + bob `connectVia` dsLink + registerGroup superUser bob "privacy" "Privacy" + bob #> "@'SimpleX Directory' /role 1" + bob <# "'SimpleX Directory'> > /role 1" + bob <## " The initial member role for the group privacy is set to member" + bob <## "Send /'role 1 observer' to change it." + bob <## "" + note <- getTermLine bob + let groupLink = dropStrPrefix "Please note: it applies only to members joining via this link: " note + cath ##> ("/c " <> groupLink) + cath <## "connection request sent!" + cath <## "#privacy: joining the group..." + cath <## "#privacy: you joined the group, connecting to group moderators for admission to group" + cath <## "#privacy: 'SimpleX Directory' accepted you to the group, pending review" + bob <## "#privacy: 'SimpleX Directory' added cath (Catherine) to the group (connecting and pending review...), use /_accept member #1 3 to accept member" + cath <## "#privacy: member bob (Bob) is connected" + bob <## "#privacy: new member cath is connected and pending review, use /_accept member #1 3 to accept member" + +testCaptchaByDefault :: HasCallStack => TestParams -> IO () +testCaptchaByDefault ps = + withDirectoryService ps $ \superUser dsLink -> + withNewTestChat ps "bob" bobProfile $ \bob -> + withNewTestChat ps "cath" cathProfile $ \cath -> do + bob `connectVia` dsLink + registerGroup superUser bob "privacy" "Privacy" + -- the owner never ran /filter; captcha is on by default for new groups + bob #> "@'SimpleX Directory' /role 1" + bob <# "'SimpleX Directory'> > /role 1" + bob <## " The initial member role for the group privacy is set to member" + bob <## "Send /'role 1 observer' to change it." + bob <## "" + note <- getTermLine bob + let groupLink = dropStrPrefix "Please note: it applies only to members joining via this link: " note + cath ##> ("/c " <> groupLink) + cath <## "connection request sent!" + cath <## "#privacy: joining the group..." + cath <## "#privacy: you joined the group, pending approval" + cath <# "#privacy (support) 'SimpleX Directory'> Captcha is generated by SimpleX Directory service." + cath <## "" + cath <## "Send captcha text to join the group privacy." + captcha <- dropStrPrefix "#privacy (support) 'SimpleX Directory'> " . dropTime <$> getTermLine cath + cath #> ("#privacy (support) " <> captcha) + cath <# ("#privacy (support) 'SimpleX Directory'!> > cath " <> captcha) + cath <## " Correct, you joined the group privacy" + cath <## "#privacy: you joined the group" + cath <#. "#privacy 'SimpleX Directory'> Link to join the group privacy: https://" + cath <## "#privacy: member bob (Bob) is connected" + bob <## "#privacy: 'SimpleX Directory' added cath (Catherine) to the group (connecting...)" + bob <## "#privacy: new member cath is connected" + testCapthaScreening :: HasCallStack => TestParams -> IO () testCapthaScreening ps = withDirectoryService ps $ \superUser dsLink -> @@ -1209,16 +1327,6 @@ testCapthaScreening ps = bob <## "" note <- getTermLine bob let groupLink = dropStrPrefix "Please note: it applies only to members joining via this link: " note - -- enable captcha - bob #> "@'SimpleX Directory' /filter 1 captcha" - bob <# "'SimpleX Directory'> > /filter 1 captcha" - bob <## " Spam filter settings for group privacy set to:" - bob <## "- reject long/inappropriate names: disabled" - bob <## "- pass captcha to join: enabled" - bob <## "" - bob <## "/'filter 1 name' - enable name filter" - bob <## "/'filter 1 name captcha' - enable both" - bob <## "/'filter 1 off' - disable filter" -- connect with captcha screen _ <- join cath groupLink cath #> "#privacy (support) 123" -- sending incorrect captcha @@ -1307,16 +1415,6 @@ testVoiceCaptchaScreening ps@TestParams {tmpPath} = do bob <## "" note <- getTermLine bob let groupLink = dropStrPrefix "Please note: it applies only to members joining via this link: " note - -- enable captcha - bob #> "@'SimpleX Directory' /filter 1 captcha" - bob <# "'SimpleX Directory'> > /filter 1 captcha" - bob <## " Spam filter settings for group privacy set to:" - bob <## "- reject long/inappropriate names: disabled" - bob <## "- pass captcha to join: enabled" - bob <## "" - bob <## "/'filter 1 name' - enable name filter" - bob <## "/'filter 1 name captcha' - enable both" - bob <## "/'filter 1 off' - disable filter" -- cath joins, receives text captcha with /audio hint cath ##> ("/c " <> groupLink) cath <## "connection request sent!" @@ -1376,15 +1474,6 @@ testVoiceCaptchaRetry ps@TestParams {tmpPath} = do bob <## "" note <- getTermLine bob let groupLink = dropStrPrefix "Please note: it applies only to members joining via this link: " note - bob #> "@'SimpleX Directory' /filter 1 captcha" - bob <# "'SimpleX Directory'> > /filter 1 captcha" - bob <## " Spam filter settings for group privacy set to:" - bob <## "- reject long/inappropriate names: disabled" - bob <## "- pass captcha to join: enabled" - bob <## "" - bob <## "/'filter 1 name' - enable name filter" - bob <## "/'filter 1 name captcha' - enable both" - bob <## "/'filter 1 off' - disable filter" -- cath joins, receives text captcha with /audio hint cath ##> ("/c " <> groupLink) cath <## "connection request sent!" @@ -1437,15 +1526,6 @@ testVoiceCaptchaVoiceDisabled ps@TestParams {tmpPath} = do bob <## "" note <- getTermLine bob let groupLink = dropStrPrefix "Please note: it applies only to members joining via this link: " note - bob #> "@'SimpleX Directory' /filter 1 captcha" - bob <# "'SimpleX Directory'> > /filter 1 captcha" - bob <## " Spam filter settings for group privacy set to:" - bob <## "- reject long/inappropriate names: disabled" - bob <## "- pass captcha to join: enabled" - bob <## "" - bob <## "/'filter 1 name' - enable name filter" - bob <## "/'filter 1 name captcha' - enable both" - bob <## "/'filter 1 off' - disable filter" -- disable voice messages in the group bob ##> "/set voice #privacy off" bob <## "updated group preferences:" @@ -1504,15 +1584,6 @@ testVoiceCaptchaOldClient ps@TestParams {tmpPath} = do bob <## "" note <- getTermLine bob let groupLink = dropStrPrefix "Please note: it applies only to members joining via this link: " note - bob #> "@'SimpleX Directory' /filter 1 captcha" - bob <# "'SimpleX Directory'> > /filter 1 captcha" - bob <## " Spam filter settings for group privacy set to:" - bob <## "- reject long/inappropriate names: disabled" - bob <## "- pass captcha to join: enabled" - bob <## "" - bob <## "/'filter 1 name' - enable name filter" - bob <## "/'filter 1 name captcha' - enable both" - bob <## "/'filter 1 off' - disable filter" -- disable voice messages in the group bob ##> "/set voice #privacy off" bob <## "updated group preferences:" @@ -1543,20 +1614,24 @@ testVoiceCaptchaOldClient ps@TestParams {tmpPath} = do cath <## " Correct, you joined the group privacy" cath <## "#privacy: you joined the group" -withDirectoryServiceVoiceCaptcha :: HasCallStack => TestParams -> FilePath -> (TestCC -> String -> IO ()) -> IO () -withDirectoryServiceVoiceCaptcha ps voiceScript test = do +withDirectoryServiceOpts :: HasCallStack => TestParams -> (DirectoryOpts -> DirectoryOpts) -> (TestCC -> String -> IO ()) -> IO () +withDirectoryServiceOpts ps modOpts test = do dsLink <- withNewTestChatCfg ps testCfg serviceDbPrefix directoryProfile $ \ds -> withNewTestChatCfg ps testCfg "super_user" aliceProfile $ \superUser -> do connectUsers ds superUser ds ##> "/ad" getContactLink ds True - let opts = (mkDirectoryOpts ps [KnownContact 2 "alice"] Nothing Nothing) {voiceCaptchaGenerator = Just voiceScript} + let opts = modOpts $ mkDirectoryOpts ps [KnownContact 2 "alice"] Nothing Nothing runDirectory testCfg opts $ withTestChatCfg ps testCfg "super_user" $ \superUser -> do superUser <## "subscribed 1 connections on server localhost" test superUser dsLink +withDirectoryServiceVoiceCaptcha :: HasCallStack => TestParams -> FilePath -> (TestCC -> String -> IO ()) -> IO () +withDirectoryServiceVoiceCaptcha ps voiceScript = + withDirectoryServiceOpts ps (\o -> o {voiceCaptchaGenerator = Just voiceScript}) + testRestoreDirectory :: HasCallStack => TestParams -> IO () testRestoreDirectory ps = do testListUserGroups False ps @@ -1729,7 +1804,7 @@ registerGroup su u n fn = registerGroupId su u n fn 1 1 registerGroupId :: TestCC -> TestCC -> String -> String -> Int -> Int -> IO () registerGroupId su u n fn gId ugId = do submitGroup u n fn - welcomeWithLink <- groupAccepted u n + welcomeWithLink <- groupAccepted u n ugId completeRegistrationId su u n fn welcomeWithLink gId ugId submitGroup :: TestCC -> String -> String -> IO () @@ -1740,8 +1815,8 @@ submitGroup u n fn = do u ##> ("/a " <> viewName n <> " 'SimpleX Directory' admin") u <## ("invitation to join the group #" <> viewName n <> " sent to 'SimpleX Directory'") -groupAccepted :: TestCC -> String -> IO String -groupAccepted u n = do +groupAccepted :: TestCC -> String -> Int -> IO String +groupAccepted u n ugId = do u <### [ WithTime ("'SimpleX Directory'> Joining the group " <> n <> "…"), ConsoleString ("#" <> viewName n <> ": 'SimpleX Directory' joined the group") @@ -1751,7 +1826,10 @@ groupAccepted u n = do u <## "" u <## "Please add it to the group welcome message." u <## "For example, add:" - dropStrPrefix "'SimpleX Directory'> " . dropTime <$> getTermLine u -- welcome message with link + welcomeWithLink <- dropStrPrefix "'SimpleX Directory'> " . dropTime <$> getTermLine u + u <# "'SimpleX Directory'> We recommend allowing direct messages, media, voice, and SimpleX links only for group moderators and admins. Use group preferences to set them." + u <## ("Captcha verification is enabled. Use /'filter " <> show ugId <> "' to change it.") + pure welcomeWithLink completeRegistration :: TestCC -> TestCC -> String -> String -> String -> Int -> IO () completeRegistration su u n fn welcomeWithLink gId = @@ -1885,15 +1963,6 @@ testCaptchaTooManyAttempts ps = bob <## "" note <- getTermLine bob let groupLink = dropStrPrefix "Please note: it applies only to members joining via this link: " note - bob #> "@'SimpleX Directory' /filter 1 captcha" - bob <# "'SimpleX Directory'> > /filter 1 captcha" - bob <## " Spam filter settings for group privacy set to:" - bob <## "- reject long/inappropriate names: disabled" - bob <## "- pass captcha to join: enabled" - bob <## "" - bob <## "/'filter 1 name' - enable name filter" - bob <## "/'filter 1 name captcha' - enable both" - bob <## "/'filter 1 off' - disable filter" cath ##> ("/c " <> groupLink) cath <## "connection request sent!" cath <## "#privacy: joining the group..." @@ -1932,15 +2001,6 @@ testCaptchaUnknownCommand ps = bob <## "" note <- getTermLine bob let groupLink = dropStrPrefix "Please note: it applies only to members joining via this link: " note - bob #> "@'SimpleX Directory' /filter 1 captcha" - bob <# "'SimpleX Directory'> > /filter 1 captcha" - bob <## " Spam filter settings for group privacy set to:" - bob <## "- reject long/inappropriate names: disabled" - bob <## "- pass captcha to join: enabled" - bob <## "" - bob <## "/'filter 1 name' - enable name filter" - bob <## "/'filter 1 name captcha' - enable both" - bob <## "/'filter 1 off' - disable filter" cath ##> ("/c " <> groupLink) cath <## "connection request sent!" cath <## "#privacy: joining the group..." @@ -2003,6 +2063,8 @@ testRegisterChannelViaCard ps = ] -- owner sends a message to trigger member introduction bob <# "'SimpleX Directory'> Joined the channel news. Registration is pending approval — it may take up to 48 hours." + bob <# "'SimpleX Directory'> We recommend allowing direct messages, media, voice, and SimpleX links only for group moderators and admins. Use group preferences to set them." + bob <## "Captcha verification is enabled. Use /'filter 1' to change it." superUser <# "'SimpleX Directory'> bob submitted the channel ID 1:" superUser <## "news" superUser <##. "Link to join channel: " @@ -2101,6 +2163,8 @@ testDeleteChannelRegistration ps = bob <## "#news: relay introduced 'SimpleX Directory_1' in the channel" ] bob <# "'SimpleX Directory'> Joined the channel news. Registration is pending approval — it may take up to 48 hours." + bob <# "'SimpleX Directory'> We recommend allowing direct messages, media, voice, and SimpleX links only for group moderators and admins. Use group preferences to set them." + bob <## "Captcha verification is enabled. Use /'filter 1' to change it." superUser <# "'SimpleX Directory'> bob submitted the channel ID 1:" superUser <## "news" superUser <##. "Link to join channel: " @@ -2145,6 +2209,8 @@ testReregistrationAlreadyListed ps = bob <## "#news: relay introduced 'SimpleX Directory_1' in the channel" ] bob <# "'SimpleX Directory'> Joined the channel news. Registration is pending approval — it may take up to 48 hours." + bob <# "'SimpleX Directory'> We recommend allowing direct messages, media, voice, and SimpleX links only for group moderators and admins. Use group preferences to set them." + bob <## "Captcha verification is enabled. Use /'filter 1' to change it." superUser <# "'SimpleX Directory'> bob submitted the channel ID 1:" superUser <## "news" superUser <##. "Link to join channel: " @@ -2204,6 +2270,8 @@ testLinkCheckUpdatesCount ps = do bob <## "#news: relay introduced 'SimpleX Directory_1' in the channel" ] bob <# "'SimpleX Directory'> Joined the channel news. Registration is pending approval — it may take up to 48 hours." + bob <# "'SimpleX Directory'> We recommend allowing direct messages, media, voice, and SimpleX links only for group moderators and admins. Use group preferences to set them." + bob <## "Captcha verification is enabled. Use /'filter 1' to change it." superUser <# "'SimpleX Directory'> bob submitted the channel ID 1:" superUser <## "news" superUser <##. "Link to join channel: " diff --git a/tests/ChatClient.hs b/tests/ChatClient.hs index c955ca1353..c803570d99 100644 --- a/tests/ChatClient.hs +++ b/tests/ChatClient.hs @@ -57,9 +57,9 @@ import Simplex.Messaging.Client (ProtocolClientConfig (..)) import Simplex.Messaging.Client.Agent (defaultSMPClientAgentConfig) import Simplex.Messaging.Crypto.Ratchet (supportedE2EEncryptVRange) import qualified Simplex.Messaging.Crypto.Ratchet as CR -import Simplex.Messaging.Protocol (sndAuthKeySMPClientVersion) import Simplex.Messaging.Server (runSMPServerBlocking) import Simplex.Messaging.Server.Env.STM (ServerConfig (..), ServerStoreCfg (..), StartOptions (..), StorePaths (..), defaultMessageExpiration, defaultIdleQueueInterval, defaultNtfExpiration, defaultInactiveClientExpiration) +import NameResolver (NameRegistry, resolverNamesConfig, withNameResolver) import Simplex.Messaging.Server.MsgStore.STM (STMMsgStore) import Simplex.Messaging.Transport import Simplex.Messaging.Transport.Server (ServerCredentials (..), mkTransportServerConfig) @@ -202,13 +202,6 @@ testAgentCfg = where RetryInterval2 {riFast, riSlow} = messageRetryInterval aCfg -testAgentCfgNoShortLinks :: AgentConfig -testAgentCfgNoShortLinks = - testAgentCfg - { smpClientVRange = mkVersionRange (Version 1) sndAuthKeySMPClientVersion, -- v3 - smpCfg = (smpCfg testAgentCfg) {serverVRange = mkVersionRange minClientSMPRelayVersion (Version 14)} -- before shortLinksSMPVersion - } - testCfg :: ChatConfig testCfg = defaultChatConfig @@ -221,9 +214,6 @@ testCfg = confirmMigrations = MCYesUp } -testCfgNoShortLinks :: ChatConfig -testCfgNoShortLinks = testCfg {agentConfig = testAgentCfgNoShortLinks} - testAgentCfgVPrev :: AgentConfig testAgentCfgVPrev = testAgentCfg @@ -586,6 +576,8 @@ smpServerCfg = smpAgentCfg = defaultSMPClientAgentConfig, allowSMPProxy = True, serverClientConcurrency = 16, + serverResolverConcurrency = 1000, + namesConfig = Nothing, information = Nothing, startOptions = StartOptions {maintenance = False, compactLog = False, logLevel = LogError, skipWarnings = False, confirmMigrations = MCYesUp} } @@ -599,6 +591,13 @@ withSmpServer = withSmpServer' smpServerCfg withSmpServer' :: ServerConfig STMMsgStore -> IO a -> IO a withSmpServer' cfg = serverBracket (\started -> runSMPServerBlocking started cfg Nothing) +-- | SMP server with a local names resolver attached; the action gets the resolver +-- registry to map names to the addresses it creates. +withSmpServerAndNames :: (NameRegistry -> IO a) -> IO a +withSmpServerAndNames action = + withNameResolver $ \port reg -> + withSmpServer' smpServerCfg {namesConfig = Just (resolverNamesConfig port)} (action reg) + xftpTestPort :: ServiceName xftpTestPort = "7002" diff --git a/tests/ChatTests/Direct.hs b/tests/ChatTests/Direct.hs index 7acfae1a95..cdc78e2ec8 100644 --- a/tests/ChatTests/Direct.hs +++ b/tests/ChatTests/Direct.hs @@ -1210,20 +1210,20 @@ testOperators = alice <##. "Current conditions: 2." alice ##> "/_operators" alice <##. "1 (simplex). SimpleX Chat (SimpleX Chat Ltd), domains: simplex.im, servers: enabled, conditions: required" - alice <## "2 (flux). Flux (InFlux Technologies Limited), domains: simplexonflux.com, servers: SMP enabled proxy, XFTP enabled proxy, conditions: required" + alice <## "2 (flux). Flux (InFlux Technologies Limited), domains: simplexonflux.com, servers: SMP enabled proxy, XFTP enabled, conditions: required" alice <##. "The new conditions will be accepted for SimpleX Chat Ltd, InFlux Technologies Limited at " -- set conditions notified alice ##> "/_conditions_notified 2" alice <## "ok" alice ##> "/_operators" alice <##. "1 (simplex). SimpleX Chat (SimpleX Chat Ltd), domains: simplex.im, servers: enabled, conditions: required" - alice <## "2 (flux). Flux (InFlux Technologies Limited), domains: simplexonflux.com, servers: SMP enabled proxy, XFTP enabled proxy, conditions: required" + alice <## "2 (flux). Flux (InFlux Technologies Limited), domains: simplexonflux.com, servers: SMP enabled proxy, XFTP enabled, conditions: required" alice ##> "/_conditions" alice <##. "Current conditions: 2 (notified)." -- accept conditions alice ##> "/_accept_conditions 2 1,2" alice <##. "1 (simplex). SimpleX Chat (SimpleX Chat Ltd), domains: simplex.im, servers: enabled, conditions: accepted (" - alice <##. "2 (flux). Flux (InFlux Technologies Limited), domains: simplexonflux.com, servers: SMP enabled proxy, XFTP enabled proxy, conditions: accepted (" + alice <##. "2 (flux). Flux (InFlux Technologies Limited), domains: simplexonflux.com, servers: SMP enabled proxy, XFTP enabled, conditions: accepted (" -- update operators alice ##> "/operators 2:on:smp=proxy:xftp=off" alice <##. "1 (simplex). SimpleX Chat (SimpleX Chat Ltd), domains: simplex.im, servers: enabled, conditions: accepted (" diff --git a/tests/ChatTests/Groups.hs b/tests/ChatTests/Groups.hs index 51fe8c54aa..18023ed12c 100644 --- a/tests/ChatTests/Groups.hs +++ b/tests/ChatTests/Groups.hs @@ -300,6 +300,8 @@ chatGroupTests = do it "concurrent fresh invitations both rejected" testRelayRejectRaceConcurrentInvitations describe "promoted members roster" $ do it "moderator action verifies via owner-signed roster" testChannelModeratorActionViaRoster + it "subscriber recovers a missed roster member after a version gap" testChannelSubscriberRosterCatchUp + it "2 relays: subscriber recovers a missed roster member after a version gap" testChannel2RelaysSubscriberRosterCatchUp it "removed moderator drops from the roster cache" testChannelRemovedModeratorRefreshesRoster it "role transitions update the roster (mod <-> admin, admin -> non-roster)" testChannelRoleTransitionsUpdateRoster it "malicious relay cannot downgrade or re-key a roster-established moderator via XGrpMemNew" testChannelRelayCannotDowngradeRosterMember @@ -9710,6 +9712,24 @@ checkMemberRow cc name expectedRole = do DB.query db "SELECT member_role FROM group_members WHERE local_display_name = ?" (Only name) :: IO [Only T.Text] map (\(Only r) -> r) roles `shouldBe` maybeToList expectedRole +-- The wire member id for a named member (look it up on a client that knows the name, e.g. the owner), used to +-- find a member by id on a subscriber that only knows it by member-id hash (e.g. after roster recovery). +getMemberIdByName :: TestCC -> T.Text -> IO ByteString +getMemberIdByName cc name = do + rows <- withCCTransaction cc $ \db -> + DB.query db "SELECT member_id FROM group_members WHERE local_display_name = ?" (Only name) :: IO [Only ByteString] + case rows of + [Only mid] -> pure mid + _ -> fail $ "expected one group_members row for " <> T.unpack name + +getMemberRoleKey :: TestCC -> ByteString -> IO (T.Text, Maybe ByteString) +getMemberRoleKey cc mid = do + rows <- withCCTransaction cc $ \db -> + DB.query db "SELECT member_role, member_pub_key FROM group_members WHERE member_id = ?" (Only mid) :: IO [(T.Text, Maybe ByteString)] + case rows of + [r] -> pure r + _ -> fail "expected one group_members row by member id" + testChannelModeratorActionViaRoster :: HasCallStack => TestParams -> IO () testChannelModeratorActionViaRoster ps = withNewTestChat ps "alice" aliceProfile $ \alice -> @@ -9780,6 +9800,99 @@ testChannelModeratorActionViaRoster ps = DB.query db "SELECT member_role FROM group_members WHERE local_display_name = ?" (Only name) :: IO [Only T.Text] map (\(Only r) -> r) roles `shouldBe` [expectedRole] +testChannelSubscriberRosterCatchUp :: HasCallStack => TestParams -> IO () +testChannelSubscriberRosterCatchUp ps = + withNewTestChat ps "alice" aliceProfile $ \alice -> + withNewTestChatOpts ps relayTestOpts "bob" bobProfile $ \bob -> + withNewTestChat ps "cath" cathProfile $ \cath -> + withNewTestChat ps "dan" danProfile $ \dan -> + withNewTestChat ps "eve" eveProfile $ \eve -> + withNewTestChat ps "frank" frankProfile $ \frank -> do + (shortLink, fullLink) <- prepareChannel1Relay "team" alice bob + forM_ [cath, dan, eve, frank] $ \member -> + memberJoinChannel "team" [bob] [alice] shortLink fullLink member + -- promote dan (roster v0) then eve (v1) into the owner-signed roster; cath learns both with their keys + threadDelay 1000000 + promoteChannelMember "team" alice bob dan [cath, eve, frank] + threadDelay 1000000 + promoteChannelMember "team" alice bob eve [cath, dan, frank] + threadDelay 1000000 + -- simulate cath having fallen behind and lost dan: capture dan's member id (from the owner, which + -- knows the name) and cath's owner-pinned key for dan, then delete dan's record and rewind cath's + -- applied frontier so the next delta arrives as a gap (v2 > applied 0 + 1) + danId <- getMemberIdByName alice "dan" + (_, danKey) <- getMemberRoleKey cath danId + withCCTransaction cath $ \db -> do + DB.execute db "DELETE FROM group_members WHERE member_id = ?" (Only danId) + DB.execute db "UPDATE groups SET applied_complete_roster_version = ? WHERE group_id = ?" (0 :: Int64, 1 :: Int64) + -- the next privileged change (frank -> v2) reaches cath at a jumped version, triggering catch-up: + -- cath requests the roster from the forwarding relay, which re-serves the current snapshot + promoteChannelMember "team" alice bob frank [cath, dan, eve] + threadDelay 2000000 -- wait for the gap request + relay re-serve to recover dan + -- cath recovered dan from the re-served roster: same member id, role, and owner-pinned key + (recRole, recKey) <- getMemberRoleKey cath danId + recRole `shouldBe` "member" + recKey `shouldBe` danKey + +-- Same recovery, but the subscriber (frank) is connected to two relays: the request goes to whichever relay +-- forwarded the gapping delta, and only an observation that catch-up works in a 2-relay channel (not the race). +testChannel2RelaysSubscriberRosterCatchUp :: HasCallStack => TestParams -> IO () +testChannel2RelaysSubscriberRosterCatchUp ps = + withNewTestChat ps "alice" aliceProfile $ \alice -> + withNewTestChatOpts ps relayTestOpts "bob" bobProfile $ \bob -> + withNewTestChatOpts ps relayTestOpts "cath" cathProfile $ \cath -> + withNewTestChat ps "dan" danProfile $ \dan -> + withNewTestChat ps "eve" eveProfile $ \eve -> + withNewTestChat ps "frank" frankProfile $ \frank -> do + (shortLink, fullLink) <- prepareChannel2Relays "team" alice bob cath + forM_ [dan, eve, frank] $ \member -> + memberJoinChannel "team" [bob, cath] [alice] shortLink fullLink member + -- promote dan (v0) then eve (v1) into the owner-signed roster, forwarded by both relays; frank + -- (the subscriber) learns both with their keys + threadDelay 1000000 + alice ##> "/mr #team dan member" + alice <## "#team: you changed the role of dan to member (signed)" + concurrentlyN_ + [ bob <## "#team: alice changed the role of dan from observer to member (signed)", + cath <## "#team: alice changed the role of dan from observer to member (signed)", + dan <## "#team: alice changed your role from observer to member (signed)", + eve <### [EndsWith "from observer to member (signed)"], + frank <### [EndsWith "from observer to member (signed)"] + ] + threadDelay 1000000 + alice ##> "/mr #team eve member" + alice <## "#team: you changed the role of eve to member (signed)" + concurrentlyN_ + [ bob <## "#team: alice changed the role of eve from observer to member (signed)", + cath <## "#team: alice changed the role of eve from observer to member (signed)", + eve <## "#team: alice changed your role from observer to member (signed)", + dan <### [EndsWith "from observer to member (signed)"], + frank <### [EndsWith "from observer to member (signed)"] + ] + threadDelay 1000000 + -- simulate frank having fallen behind and lost dan: delete dan's record and rewind frank's complete + -- frontier so the next delta (eve -> v2) arrives as a gap (2 > applied 0 + 1) + danId <- getMemberIdByName alice "dan" + (_, danKey) <- getMemberRoleKey frank danId + withCCTransaction frank $ \db -> do + DB.execute db "DELETE FROM group_members WHERE member_id = ?" (Only danId) + DB.execute db "UPDATE groups SET applied_complete_roster_version = ? WHERE group_id = ?" (0 :: Int64, 1 :: Int64) + -- eve -> moderator (v2) reaches frank at a jumped version; it requests the roster from the relay that + -- forwarded the delta, which re-serves the current snapshot (including dan), recovering dan + alice ##> "/mr #team eve moderator" + alice <## "#team: you changed the role of eve to moderator (signed)" + concurrentlyN_ + [ bob <## "#team: alice changed the role of eve from member to moderator (signed)", + cath <## "#team: alice changed the role of eve from member to moderator (signed)", + eve <## "#team: alice changed your role from member to moderator (signed)", + dan <### [EndsWith "from member to moderator (signed)"], + frank <### [EndsWith "from member to moderator (signed)"] + ] + threadDelay 2000000 -- wait for the gap request + relay re-serve to recover dan + (recRole, recKey) <- getMemberRoleKey frank danId + recRole `shouldBe` "member" + recKey `shouldBe` danKey + testChannelRemovedModeratorRefreshesRoster :: HasCallStack => TestParams -> IO () testChannelRemovedModeratorRefreshesRoster ps = withNewTestChat ps "alice" aliceProfile $ \alice -> @@ -9804,6 +9917,8 @@ testChannelRemovedModeratorRefreshesRoster ps = threadDelay 1000000 alice ##> "/rm #team cath" alice <## "#team: you removed cath from the group (signed)" + -- the relay applies the removal via the roster (revert to observer) before the delete delta + bob <## "#team: alice changed the role of cath from moderator to observer (signed)" bob <## "#team: alice removed cath from the group (signed)" cath <## "#team: alice removed you from the group (signed)" cath <## "use /d #team to delete the group" @@ -10024,6 +10139,8 @@ testChannelRemoveMemberSigned ps = threadDelay 1000000 alice ##> "/rm #team eve" alice <## "#team: you removed eve from the group (signed)" + -- the relay applies the removal via the roster (revert to observer) before the delete delta + bob <## "#team: alice changed the role of eve from member to observer (signed)" bob <## "#team: alice removed eve from the group (signed)" concurrentlyN_ [ cath <## "#team: alice removed eve from the group (signed)", diff --git a/tests/ChatTests/Names.hs b/tests/ChatTests/Names.hs new file mode 100644 index 0000000000..cc46a65543 --- /dev/null +++ b/tests/ChatTests/Names.hs @@ -0,0 +1,225 @@ +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE PostfixOperators #-} + +module ChatTests.Names where + +import ChatClient +import ChatTests.DBUtils +import ChatTests.Groups (prepareChannel1Relay) +import ChatTests.Utils +import Control.Concurrent.Async (concurrently_) +import qualified Data.Text as T +import NameResolver +import Simplex.Messaging.SimplexName (SimplexDomain (..), SimplexNameInfo (..), SimplexNameType (..), SimplexTLD (..)) +import Test.Hspec hiding (it) + +chatNamesTests :: SpecWith TestParams +chatNamesTests = do + it "connect by resolved name" testConnectByName + it "connect by name not claimed in link profile is rejected" testConnectByNameNotClaimed + it "connect by name to a known contact not claimed in profile is rejected" testConnectByNameKnownContactNotClaimed + it "connect by unregistered name fails to resolve" testConnectByNameNotFound + it "set name not resolving to own address is rejected" testSetNameNotOwnAddress + it "connect by channel name" testConnectByChannelName + it "connect by name resolving to channel (primary) and direct contact" testConnectByNameChannelAndContact + it "connect by name resolving to direct contact (primary) and channel" testConnectByNameContactAndChannel + it "connect by name resolving to business (primary) and channel" testConnectByNameBusinessAndChannel + +testConnectByName :: HasCallStack => TestParams -> IO () +testConnectByName ps = withSmpServerAndNames $ \reg -> + testChat2 aliceProfile bobProfile (test reg) ps + where + aliceName = SimplexNameInfo NTContact (SimplexDomain TLDSimplex "alice" []) + test reg alice bob = do + alice ##> "/ad" + (shortLink, _) <- getContactLinks alice True + registerName reg aliceName (contactNameRecord "alice" (T.pack shortLink)) + alice ##> "/_set domain 1 alice.simplex" + alice <## "new contact address set" + bob ##> "/c @alice.simplex" + bob <## "alice: connection started" + alice <## "bob (Bob) wants to connect to you!" + alice <## "to accept: /ac bob" + alice <## "to reject: /rc bob (the sender will NOT be notified)" + alice ##> "/ac bob" + alice <## "bob (Bob): accepting contact request, you can send messages to contact" + concurrently_ + (bob <## "alice (Alice): contact is connected") + (alice <## "bob (Bob): contact is connected") + alice <##> bob + bob ##> "/i alice" + bob <## "contact ID: 2" + bob <## "receiving messages via: localhost" + bob <## "sending messages via: localhost" + _ <- getTermLine bob + bob <## "SimpleX name: @alice.simplex (verified)" + bob <## "you've shared main profile with this contact" + bob <## "connection not verified, use /code command to see security code" + bob <## "quantum resistant end-to-end encryption" + _ <- getTermLine bob + pure () + +testConnectByNameNotClaimed :: HasCallStack => TestParams -> IO () +testConnectByNameNotClaimed ps = withSmpServerAndNames $ \reg -> + testChat2 aliceProfile bobProfile (test reg) ps + where + aliceName = SimplexNameInfo NTContact (SimplexDomain TLDSimplex "alice" []) + test reg alice bob = do + alice ##> "/ad" + (shortLink, _) <- getContactLinks alice True + registerName reg aliceName (contactNameRecord "alice" (T.pack shortLink)) + bob ##> "/c @alice.simplex" + bob <## "SimpleX name alice.simplex is not included in the connection link's profile" + +testConnectByNameKnownContactNotClaimed :: HasCallStack => TestParams -> IO () +testConnectByNameKnownContactNotClaimed ps = withSmpServerAndNames $ \reg -> + testChat2 aliceProfile bobProfile (test reg) ps + where + aliceName = SimplexNameInfo NTContact (SimplexDomain TLDSimplex "alice" []) + test reg alice bob = do + alice ##> "/ad" + (shortLink, _) <- getContactLinks alice True + bob ##> ("/c " <> shortLink) + bob <## "connection request sent!" + alice <## "bob (Bob) wants to connect to you!" + alice <## "to accept: /ac bob" + alice <## "to reject: /rc bob (the sender will NOT be notified)" + alice ##> "/ac bob" + alice <## "bob (Bob): accepting contact request, you can send messages to contact" + concurrently_ + (bob <## "alice (Alice): contact is connected") + (alice <## "bob (Bob): contact is connected") + registerName reg aliceName (contactNameRecord "alice" (T.pack shortLink)) + bob ##> "/c @alice.simplex" + bob <## "SimpleX name alice.simplex is not included in the connection link's profile" + +testConnectByNameNotFound :: HasCallStack => TestParams -> IO () +testConnectByNameNotFound ps = withSmpServerAndNames $ \_reg -> + testChat2 aliceProfile bobProfile test ps + where + test _alice bob = do + bob ##> "/c @nobody.simplex" + bob .<## "smpErr = NAME {nameErr = NOT_FOUND}}" + +testSetNameNotOwnAddress :: HasCallStack => TestParams -> IO () +testSetNameNotOwnAddress ps = withSmpServerAndNames $ \reg -> + testChat2 aliceProfile bobProfile (test reg) ps + where + aliceName = SimplexNameInfo NTContact (SimplexDomain TLDSimplex "alice" []) + test reg alice bob = do + bob ##> "/ad" + (bobShortLink, _) <- getContactLinks bob True + registerName reg aliceName (contactNameRecord "alice" (T.pack bobShortLink)) + alice ##> "/ad" + _ <- getContactLinks alice True + alice ##> "/_set domain 1 alice.simplex" + alice <## "SimpleX name alice.simplex has no valid connection link" + +testConnectByChannelName :: HasCallStack => TestParams -> IO () +testConnectByChannelName ps = withSmpServerAndNames $ \reg -> + withNewTestChat ps "alice" aliceProfile $ \alice -> + withNewTestChatOpts ps relayTestOpts "cath" cathProfile $ \cath -> + withNewTestChat ps "bob" bobProfile $ \bob -> do + (shortLink, _) <- prepareChannel1Relay "team" alice cath + registerName reg teamName (channelNameRecord "team" (T.pack shortLink)) + alice ##> "/public group access #team domain=team.simplex" + alice <## "updated public group access: domain=team.simplex" + cath <## "alice updated group #team: (signed)" + cath <## "updated public group access: domain=team.simplex" + bob ##> "/c #team.simplex" + bob <## "#team: connection started" + concurrentlyN_ + [ bob + <### [ "#team: joining the group (connecting to relay cath)...", + "#team: you joined the group (connected to relay cath)" + ] + , do + cath <## "bob (Bob): accepting request to join group #team..." + cath <## "#team: bob joined the group" + , alice <### [EndsWith "introduced bob (Bob) in the channel"] + ] + bob ##> ("/_connect plan 1 " <> shortLink) + bob <## "group link: known group #team" + bob <## "SimpleX name: #team (verified)" + bob <## "use #team to send messages" + where + teamName = SimplexNameInfo NTPublicGroup (SimplexDomain TLDSimplex "team" []) + +-- The bare name "team.simplex" resolves to both a channel and a direct contact. The channel is tried +-- first and succeeds (bob has joined #team), so it is the primary (planSimplexName); otherSimplexName +-- is the direct contact @team.simplex, shown as "You can also connect to @team.simplex in direct chat". +testConnectByNameChannelAndContact :: HasCallStack => TestParams -> IO () +testConnectByNameChannelAndContact ps = withSmpServerAndNames $ \reg -> + withNewTestChat ps "alice" aliceProfile $ \alice -> + withNewTestChatOpts ps relayTestOpts "cath" cathProfile $ \cath -> + withNewTestChat ps "bob" bobProfile $ \bob -> do + (channelLink, _) <- prepareChannel1Relay "team" alice cath + alice ##> "/ad" + (contactLink, _) <- getContactLinks alice True + registerName reg teamName (contactAndChannelNameRecord "team" (T.pack contactLink) (T.pack channelLink)) + alice ##> "/public group access #team domain=team.simplex" + alice <## "updated public group access: domain=team.simplex" + cath <## "alice updated group #team: (signed)" + cath <## "updated public group access: domain=team.simplex" + bob ##> "/c #team.simplex" + bob <## "#team: connection started" + concurrentlyN_ + [ bob + <### [ "#team: joining the group (connecting to relay cath)...", + "#team: you joined the group (connected to relay cath)" + ] + , do + cath <## "bob (Bob): accepting request to join group #team..." + cath <## "#team: bob joined the group" + , alice <### [EndsWith "introduced bob (Bob) in the channel"] + ] + bob ##> "/_connect plan 1 team.simplex" + bob <## "group link: known group #team" + bob <## "SimpleX name: #team (verified)" + bob <## "use #team to send messages" + bob <## "You can also connect to @team.simplex in direct chat" + where + teamName = SimplexNameInfo NTPublicGroup (SimplexDomain TLDSimplex "team" []) + +-- The bare name "acme.simplex" resolves to both a channel and a direct contact. The channel is tried +-- first but its group profile does not claim the domain, so the channel side of the plan fails; the +-- plan falls back to the direct contact as primary (planSimplexName) while otherSimplexName is the +-- channel #acme, shown as "You can also join channel #acme". The channel link is a real, fetchable +-- #acme channel, so the failure is the faithful "channel does not claim this domain" case, not a broken link. +testConnectByNameContactAndChannel :: HasCallStack => TestParams -> IO () +testConnectByNameContactAndChannel ps = withSmpServerAndNames $ \reg -> + withNewTestChat ps "alice" aliceProfile $ \alice -> + withNewTestChatOpts ps relayTestOpts "cath" cathProfile $ \cath -> + withNewTestChat ps "bob" bobProfile $ \bob -> do + (channelLink, _) <- prepareChannel1Relay "acme" alice cath + alice ##> "/ad" + (contactLink, _) <- getContactLinks alice True + registerName reg acmeName (contactAndChannelNameRecord "acme" (T.pack contactLink) (T.pack channelLink)) + alice ##> "/_set domain 1 acme.simplex" + alice <## "new contact address set" + bob ##> "/_connect plan 1 acme.simplex" + bob <## "contact address: ok to connect" + _ <- getTermLine bob -- contact short link data (JSON, printed in test view) + bob <## "You can also join channel #acme" + where + acmeName = SimplexNameInfo NTContact (SimplexDomain TLDSimplex "acme" []) + +testConnectByNameBusinessAndChannel :: HasCallStack => TestParams -> IO () +testConnectByNameBusinessAndChannel ps = withSmpServerAndNames $ \reg -> + withNewTestChat ps "alice" aliceProfile $ \alice -> + withNewTestChatOpts ps relayTestOpts "cath" cathProfile $ \cath -> + withNewTestChat ps "bob" bobProfile $ \bob -> do + (channelLink, _) <- prepareChannel1Relay "biz" alice cath + alice ##> "/ad" + (contactLink, _) <- getContactLinks alice True + registerName reg bizName (contactAndChannelNameRecord "biz" (T.pack contactLink) (T.pack channelLink)) + alice ##> "/auto_accept on business" + alice <## "auto_accept on, business" + alice ##> "/_set domain 1 biz.simplex" + alice <## "new contact address set" + bob ##> "/_connect plan 1 biz.simplex" + bob <## "business address: ok to connect" + _ <- getTermLine bob -- contact short link data (JSON, printed in test view) + bob <## "You can also join channel #biz" + where + bizName = SimplexNameInfo NTContact (SimplexDomain TLDSimplex "biz" []) diff --git a/tests/ChatTests/Profiles.hs b/tests/ChatTests/Profiles.hs index fb56d39aae..581aaec879 100644 --- a/tests/ChatTests/Profiles.hs +++ b/tests/ChatTests/Profiles.hs @@ -65,12 +65,9 @@ chatProfileTests = do it "reject contact and delete contact link" testRejectContactAndDeleteUserContact it "keep connection requests when contact link deleted" testKeepConnectionRequests it "connected contact works when contact link deleted" testContactLinkDeletedConnectedContactWorks - -- TODO [short links] test auto-reply with current version, with connecting client not preparing contact it "auto-reply message" testAutoReplyMessage - it "auto-reply message in incognito" testAutoReplyMessageInIncognito describe "business address" $ do it "create and connect via business address" testBusinessAddress - -- TODO [short links] test business auto-reply with current version, with connecting client not preparing contact it "update profiles with business address" testBusinessUpdateProfiles describe "contact address connection plan" $ do it "contact address ok to connect; known contact" testPlanAddressOkKnown @@ -82,7 +79,6 @@ chatProfileTests = do describe "incognito" $ do it "connect incognito via invitation link" testConnectIncognitoInvitationLink it "connect incognito via contact address" testConnectIncognitoContactAddress - it "accept contact request incognito" testAcceptContactRequestIncognito it "set connection incognito" testSetConnectionIncognito it "reset connection incognito" testResetConnectionIncognito it "set connection incognito prohibited during negotiation" testSetConnectionIncognitoProhibitedDuringNegotiation @@ -501,7 +497,7 @@ testMultiWordProfileNames = aliceProfile' = baseProfile {displayName = "Alice Jones"} bobProfile' = baseProfile {displayName = "Bob James"} cathProfile' = baseProfile {displayName = "Cath Johnson"} - baseProfile = Profile {displayName = "", fullName = "", shortDescr = Nothing, image = Nothing, contactLink = Nothing, peerType = Nothing, preferences = defaultPrefs, badge = Nothing} + baseProfile = Profile {displayName = "", fullName = "", shortDescr = Nothing, image = Nothing, contactLink = Nothing, peerType = Nothing, preferences = defaultPrefs, badge = Nothing, contactDomain = Nothing} testUserContactLink :: HasCallStack => TestParams -> IO () testUserContactLink = @@ -974,10 +970,10 @@ testContactLinkDeletedConnectedContactWorks = testChat2 aliceProfile bobProfile bob @@@ [("@alice", "hey")] testAutoReplyMessage :: HasCallStack => TestParams -> IO () -testAutoReplyMessage = testChatCfg2 testCfgNoShortLinks aliceProfile bobProfile $ +testAutoReplyMessage = testChat2 aliceProfile bobProfile $ \alice bob -> do alice ##> "/ad" - cLink <- getContactLinkNoShortLink alice True + cLink <- getContactLink alice True alice ##> "/auto_accept on incognito=off text hello!" alice <## "auto_accept on" alice <## "auto reply:" @@ -995,31 +991,6 @@ testAutoReplyMessage = testChatCfg2 testCfgNoShortLinks aliceProfile bobProfile alice <## "bob (Bob): contact is connected" ] -testAutoReplyMessageInIncognito :: HasCallStack => TestParams -> IO () -testAutoReplyMessageInIncognito = testChatCfg2 testCfgNoShortLinks aliceProfile bobProfile $ - \alice bob -> do - alice ##> "/ad" - cLink <- getContactLinkNoShortLink alice True - alice ##> "/auto_accept on incognito=on text hello!" - alice <## "auto_accept on, incognito" - alice <## "auto reply:" - alice <## "hello!" - - bob ##> ("/c " <> cLink) - bob <## "connection request sent!" - alice <## "bob (Bob): accepting contact request..." - alice <## "bob (Bob): you can send messages to contact" - alice <# "i @bob hello!" - aliceIncognito <- getTermLine alice - concurrentlyN_ - [ do - bob <# (aliceIncognito <> "> hello!") - bob <## (aliceIncognito <> ": contact is connected"), - do - alice <## ("bob (Bob): contact is connected, your incognito profile for this contact is " <> aliceIncognito) - alice <## "use /i bob to print out this incognito profile again" - ] - testBusinessAddress :: HasCallStack => TestParams -> IO () testBusinessAddress = testChat3 businessProfile aliceProfile {fullName = "Alice @ Biz"} bobProfile $ \biz alice bob -> do @@ -1075,10 +1046,10 @@ testBusinessAddress = testChat3 businessProfile aliceProfile {fullName = "Alice (biz <# "#bob bob_1> hey there") testBusinessUpdateProfiles :: HasCallStack => TestParams -> IO () -testBusinessUpdateProfiles = testChatCfg4 testCfgNoShortLinks businessProfile aliceProfile bobProfile cathProfile $ +testBusinessUpdateProfiles = testChat4 businessProfile aliceProfile bobProfile cathProfile $ \biz alice bob cath -> do biz ##> "/ad" - cLink <- getContactLinkNoShortLink biz True + cLink <- getContactLink biz True biz ##> "/auto_accept on business text Welcome" biz <## "auto_accept on, business" biz <## "auto reply:" @@ -1108,7 +1079,7 @@ testBusinessUpdateProfiles = testChatCfg4 testCfgNoShortLinks businessProfile al biz ##> "/mr alisa alisa_1 admin" biz <## "#alisa: you changed the role of alisa_1 to admin" alice <## "#biz: biz_1 changed your role from member to admin" - connectUsersNoShortLink alice bob + connectUsers alice bob alice ##> "/a #biz bob" alice <## "invitation to join the group #biz sent to bob" bob <## "#biz (Biz Inc): alisa invites you to join the group as member" @@ -1139,7 +1110,7 @@ testBusinessUpdateProfiles = testChatCfg4 testCfgNoShortLinks businessProfile al alice <# "#biz robert> hi there" biz <# "#alisa robert> hi there" -- add business team member - connectUsersNoShortLink biz cath + connectUsers biz cath biz ##> "/a #alisa cath" biz <## "invitation to join the group #alisa sent to cath" cath <## "#alisa: biz invites you to join the group as member" @@ -1628,54 +1599,6 @@ testConnectIncognitoContactAddress = testChat2 aliceProfile bobProfile $ (bob TestParams -> IO () -testAcceptContactRequestIncognito = testChatCfg3 testCfgNoShortLinks aliceProfile bobProfile cathProfile $ - \alice bob cath -> do - alice ##> "/ad" - cLink <- getContactLinkNoShortLink alice True - -- GUI /_accept api - bob ##> ("/c " <> cLink) - alice <#? bob - alice ##> "/_accept incognito=on 1" - alice <## "bob (Bob): accepting contact request, you can send messages to contact" - aliceIncognitoBob <- getTermLine alice - concurrentlyN_ - [ bob <## (aliceIncognitoBob <> ": contact is connected"), - do - alice <## ("bob (Bob): contact is connected, your incognito profile for this contact is " <> aliceIncognitoBob) - alice <## "use /i bob to print out this incognito profile again" - ] - -- conversation is incognito - alice ?#> "@bob my profile is totally inconspicuous" - bob <# (aliceIncognitoBob <> "> my profile is totally inconspicuous") - bob #> ("@" <> aliceIncognitoBob <> " I know!") - alice ?<# "bob> I know!" - -- list contacts - alice ##> "/contacts" - alice <## "i bob (Bob)" - alice `hasContactProfiles` ["alice", "bob", T.pack aliceIncognitoBob] - -- delete contact, incognito profile is deleted - alice ##> "/d bob" - alice <## "bob: contact is deleted" - bob <## (aliceIncognitoBob <> " deleted contact with you") - alice ##> "/contacts" - (alice ("/c " <> cLink) - alice <#? cath - alice ##> "/accept incognito cath" - alice <## "cath (Catherine): accepting contact request, you can send messages to contact" - aliceIncognitoCath <- getTermLine alice - concurrentlyN_ - [ cath <## (aliceIncognitoCath <> ": contact is connected"), - do - alice <## ("cath (Catherine): contact is connected, your incognito profile for this contact is " <> aliceIncognitoCath) - alice <## "use /i cath to print out this incognito profile again" - ] - alice `hasContactProfiles` ["alice", "cath", T.pack aliceIncognitoCath] - cath `hasContactProfiles` ["cath", T.pack aliceIncognitoCath] - testSetConnectionIncognito :: HasCallStack => TestParams -> IO () testSetConnectionIncognito = testChat2 aliceProfile bobProfile $ \alice bob -> do diff --git a/tests/ChatTests/Utils.hs b/tests/ChatTests/Utils.hs index e0e694f0cb..a613a13df6 100644 --- a/tests/ChatTests/Utils.hs +++ b/tests/ChatTests/Utils.hs @@ -88,7 +88,7 @@ serviceProfile :: Profile serviceProfile = mkProfile "service_user" "Service user" Nothing mkProfile :: T.Text -> T.Text -> Maybe ImageData -> Profile -mkProfile displayName descr image = Profile {displayName, fullName = "", shortDescr = Just descr, image, contactLink = Nothing, peerType = Nothing, preferences = defaultPrefs, badge = Nothing} +mkProfile displayName descr image = Profile {displayName, fullName = "", shortDescr = Just descr, image, contactLink = Nothing, peerType = Nothing, preferences = defaultPrefs, badge = Nothing, contactDomain = Nothing} it :: HasCallStack => String -> (ps -> Expectation) -> SpecWith (Arg (ps -> Expectation)) it name test = diff --git a/tests/MarkdownTests.hs b/tests/MarkdownTests.hs index 2a5328ff26..e315b59f5e 100644 --- a/tests/MarkdownTests.hs +++ b/tests/MarkdownTests.hs @@ -10,7 +10,7 @@ import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import Simplex.Chat.Markdown -import Simplex.Messaging.Agent.Protocol (SimplexNameDomain (..), SimplexNameInfo (..), SimplexNameType (..), SimplexTLD (..)) +import Simplex.Messaging.Agent.Protocol (SimplexDomain (..), SimplexNameInfo (..), SimplexNameType (..), SimplexTLD (..)) import Simplex.Messaging.Encoding.String import Simplex.Messaging.Util ((<$$>)) import System.Console.ANSI.Types @@ -400,7 +400,7 @@ command' :: Text -> Text -> FormattedText command' = FormattedText . Just . Command sname :: SimplexNameType -> SimplexTLD -> Text -> [Text] -> Text -> Markdown -sname nt ns dom sub txt = markdown (SimplexName $ SimplexNameInfo nt (SimplexNameDomain ns dom sub)) (pfx <> txt) +sname nt ns dom sub txt = markdown (SimplexName $ SimplexNameInfo nt (SimplexDomain ns dom sub)) (pfx <> txt) where pfx = case nt of NTPublicGroup -> "#"; NTContact -> "@" diff --git a/tests/NameResolver.hs b/tests/NameResolver.hs new file mode 100644 index 0000000000..35f5cd2496 --- /dev/null +++ b/tests/NameResolver.hs @@ -0,0 +1,89 @@ +{-# LANGUAGE NamedFieldPuns #-} +{-# LANGUAGE OverloadedStrings #-} + +-- | Local HTTP names resolver for chat tests, copied from simplexmq's +-- NamesResolverServer and made dynamic: it answers /resolve/ from a +-- mutable name -> NameRecord registry, so a test can resolve a name to the +-- address it just created. +module NameResolver + ( NameRegistry, + withNameResolver, + registerName, + contactNameRecord, + channelNameRecord, + contactAndChannelNameRecord, + resolverNamesConfig, + ) +where + +import Control.Concurrent.STM +import qualified Data.Aeson as J +import Data.Map.Strict (Map) +import qualified Data.Map.Strict as M +import Data.Text (Text) +import Network.HTTP.Types (hContentType, notFound404, ok200) +import Network.Wai (Application, pathInfo, responseLBS) +import qualified Network.Wai.Handler.Warp as Warp +import Simplex.Messaging.Names.Record (NameRecord (..)) +import Simplex.Messaging.Server.Names (NamesConfig (..)) +import Simplex.Messaging.SimplexName (SimplexNameInfo (..), fullDomainName) + +type NameRegistry = TVar (Map Text NameRecord) + +-- | Run an action with a local resolver on a free port and its registry (keyed +-- by full domain name, what the resolver looks the name up by). +withNameResolver :: (Int -> TVar (Map Text NameRecord) -> IO a) -> IO a +withNameResolver action = do + reg <- newTVarIO M.empty + Warp.withApplication (pure (app reg)) $ \port -> action port reg + where + app :: TVar (Map Text NameRecord) -> Application + app reg req send = do + (st, body) <- case pathInfo req of + ["health"] -> pure (ok200, "{}") + ["resolve", d] -> maybe (notFound404, "{}") (\r -> (ok200, J.encode r)) . M.lookup d <$> readTVarIO reg + _ -> pure (notFound404, "{}") + send $ responseLBS st [(hContentType, "application/json")] body + +-- | Register a name's domain to resolve to the given record. +registerName :: TVar (Map Text NameRecord) -> SimplexNameInfo -> NameRecord -> IO () +registerName reg SimplexNameInfo {nameDomain} r = + atomically $ modifyTVar' reg $ M.insert (fullDomainName nameDomain) r + +contactNameRecord :: Text -> Text -> NameRecord +contactNameRecord name link = (emptyRecord name) {nrSimplexContact = [link]} + +channelNameRecord :: Text -> Text -> NameRecord +channelNameRecord name link = (emptyRecord name) {nrSimplexChannel = [link]} + +-- | A record whose domain resolves to both a direct contact link and a channel link. +contactAndChannelNameRecord :: Text -> Text -> Text -> NameRecord +contactAndChannelNameRecord name contactLink channelLink = + (emptyRecord name) {nrSimplexContact = [contactLink], nrSimplexChannel = [channelLink]} + +emptyRecord :: Text -> NameRecord +emptyRecord name = + NameRecord + { nrName = name, + nrNickname = "", + nrWebsite = "", + nrLocation = "", + nrSimplexContact = [], + nrSimplexChannel = [], + nrEth = Nothing, + nrBtc = Nothing, + nrXmr = Nothing, + nrDot = Nothing, + nrOwner = "", + nrResolver = "" + } + +-- | NamesConfig for a chat test SMP server pointing at this resolver. +resolverNamesConfig :: Int -> NamesConfig +resolverNamesConfig port = + NamesConfig + { resolverEndpoint = "http://127.0.0.1:" <> show port, + resolverAuth = Nothing, + resolverTimeoutMs = 1000, + resolverMaxResponseBytes = 65536 + } diff --git a/tests/OperatorTests.hs b/tests/OperatorTests.hs index 5e659dd82c..d0b48a9019 100644 --- a/tests/OperatorTests.hs +++ b/tests/OperatorTests.hs @@ -38,9 +38,9 @@ validateServersTest :: Spec validateServersTest = describe "validate user servers" $ do it "should pass valid user servers" $ validateUserServers [valid] [] `shouldBe` ([], []) it "should fail without servers" $ do - validateUserServers [invalidNoServers] [] `shouldBe` ([USENoServers aSMP Nothing], []) - validateUserServers [invalidDisabled] [] `shouldBe` ([USENoServers aSMP Nothing], []) - validateUserServers [invalidDisabledOp] [] `shouldBe` ([USENoServers aSMP Nothing, USENoServers aXFTP Nothing], [USWNoChatRelays Nothing]) + validateUserServers [invalidNoServers] [] `shouldBe` ([USENoServers aSMP Nothing], [USWNoNamesServers Nothing]) + validateUserServers [invalidDisabled] [] `shouldBe` ([USENoServers aSMP Nothing], [USWNoNamesServers Nothing]) + validateUserServers [invalidDisabledOp] [] `shouldBe` ([USENoServers aSMP Nothing, USENoServers aXFTP Nothing], [USWNoChatRelays Nothing, USWNoNamesServers Nothing]) it "should fail without servers with storage role" $ do validateUserServers [invalidNoStorage] [] `shouldBe` ([USEStorageMissing aSMP Nothing], []) it "should fail with duplicate host" $ do diff --git a/tests/PostgresSchemaDump.hs b/tests/PostgresSchemaDump.hs index 0cd79ac513..b36b7faeaf 100644 --- a/tests/PostgresSchemaDump.hs +++ b/tests/PostgresSchemaDump.hs @@ -80,5 +80,7 @@ skipComparisonForDownMigrations = -- group_member_intro_id field moves "20251128_migrate_member_relations", -- on down migration single_sender_group_member_id column is re-added at the end of the table - "20260529_delivery_job_senders" + "20260529_delivery_job_senders", + -- group_domain is removed + "20260603_simplex_name" ] diff --git a/tests/ProtocolTests.hs b/tests/ProtocolTests.hs index 2592420d01..3cfb367382 100644 --- a/tests/ProtocolTests.hs +++ b/tests/ProtocolTests.hs @@ -3,6 +3,7 @@ {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PatternSynonyms #-} +{-# OPTIONS_GHC -fno-warn-ambiguous-fields #-} module ProtocolTests where @@ -107,7 +108,7 @@ testGroupPreferences :: Maybe GroupPreferences testGroupPreferences = Just GroupPreferences {timedMessages = Nothing, directMessages = Nothing, reactions = Just ReactionsGroupPreference {enable = FEOn}, voice = Just VoiceGroupPreference {enable = FEOn, role = Nothing}, files = Nothing, fullDelete = Nothing, simplexLinks = Nothing, history = Nothing, reports = Nothing, support = Nothing, sessions = Nothing, comments = Nothing, commands = Nothing} testProfile :: Profile -testProfile = Profile {displayName = "alice", fullName = "Alice", shortDescr = Nothing, image = Just (ImageData "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAIAQMAAAD+wSzIAAAABlBMVEX///+/v7+jQ3Y5AAAADklEQVQI12P4AIX8EAgALgAD/aNpbtEAAAAASUVORK5CYII="), peerType = Nothing, contactLink = Nothing, preferences = testChatPreferences, badge = Nothing} +testProfile = Profile {displayName = "alice", fullName = "Alice", shortDescr = Nothing, image = Just (ImageData "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAIAQMAAAD+wSzIAAAABlBMVEX///+/v7+jQ3Y5AAAADklEQVQI12P4AIX8EAgALgAD/aNpbtEAAAAASUVORK5CYII="), peerType = Nothing, contactLink = Nothing, preferences = testChatPreferences, badge = Nothing, contactDomain = Nothing} testGroupProfile :: GroupProfile testGroupProfile = GroupProfile {displayName = "team", fullName = "Team", description = Nothing, shortDescr = Nothing, image = Nothing, publicGroup = Nothing, groupPreferences = testGroupPreferences, memberAdmission = Nothing} @@ -240,7 +241,7 @@ decodeChatMessageTest = describe "Chat message encoding/decoding" $ do #==# XInfo testProfile it "x.info with empty full name" $ "{\"v\":\"1\",\"event\":\"x.info\",\"params\":{\"profile\":{\"fullName\":\"\",\"displayName\":\"alice\",\"preferences\":{\"reactions\":{\"allow\":\"yes\"},\"voice\":{\"allow\":\"yes\"}}}}}" - #==# XInfo Profile {displayName = "alice", fullName = "", shortDescr = Nothing, image = Nothing, contactLink = Nothing, peerType = Nothing, preferences = testChatPreferences, badge = Nothing} + #==# XInfo Profile {displayName = "alice", fullName = "", shortDescr = Nothing, image = Nothing, contactLink = Nothing, peerType = Nothing, preferences = testChatPreferences, badge = Nothing, contactDomain = Nothing} it "x.contact with xContactId" $ "{\"v\":\"1\",\"event\":\"x.contact\",\"params\":{\"contactReqId\":\"AQIDBA==\",\"profile\":{\"fullName\":\"Alice\",\"displayName\":\"alice\",\"image\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAIAQMAAAD+wSzIAAAABlBMVEX///+/v7+jQ3Y5AAAADklEQVQI12P4AIX8EAgALgAD/aNpbtEAAAAASUVORK5CYII=\",\"preferences\":{\"reactions\":{\"allow\":\"yes\"},\"voice\":{\"allow\":\"yes\"}}}}}" #==# XContact testProfile (Just $ XContactId "\1\2\3\4") Nothing Nothing diff --git a/tests/SchemaDump.hs b/tests/SchemaDump.hs index 2336fd56dd..783f6587bf 100644 --- a/tests/SchemaDump.hs +++ b/tests/SchemaDump.hs @@ -145,7 +145,9 @@ skipComparisonForDownMigrations = -- on down migration single_sender_group_member_id column and its index -- are re-added at the end of the table / file (ALTER TABLE ADD COLUMN -- appends; CREATE INDEX appends). - "20260529_delivery_job_senders" + "20260529_delivery_job_senders", + -- group_domain is removed + "20260603_simplex_name" ] getSchema :: FilePath -> FilePath -> IO String diff --git a/tests/Test.hs b/tests/Test.hs index 874428bc1f..515098c5d1 100644 --- a/tests/Test.hs +++ b/tests/Test.hs @@ -8,6 +8,7 @@ import Bots.DirectoryTests import ChatClient import ChatTests import ChatTests.DBUtils +import ChatTests.Names (chatNamesTests) import ChatTests.Utils (xdescribe'') import Control.Logger.Simple import Data.Time.Clock.System @@ -71,6 +72,9 @@ main = do describe "Message batching" batchingTests describe "Operators" operatorTests describe "Random servers" randomServersTests +#if !defined(dbPostgres) + around (tmpTestBracket chatQueryStats agentQueryStats) $ describe "names tests" chatNamesTests +#endif #if defined(dbPostgres) createdDropDb . around testBracket #else @@ -96,6 +100,8 @@ main = do #else testBracket chatQueryStats agentQueryStats test = withSmpServer $ tmpBracket $ \tmpPath -> test TestParams {tmpPath, chatQueryStats, agentQueryStats, printOutput = False} + tmpTestBracket chatQueryStats agentQueryStats test = + tmpBracket $ \tmpPath -> test TestParams {tmpPath, chatQueryStats, agentQueryStats, printOutput = False} #endif tmpBracket test = do t <- getSystemTime