From 38763d057559033cddc21a7d2e5617bdc7328dcc Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Wed, 13 Jul 2022 12:04:19 +0100 Subject: [PATCH] adding function to extract usernames from full matrix ids --- .../matrix/android/sdk/api/MatrixPatterns.kt | 14 ++++++++++++++ .../android/sdk/api/MatrixPatternsTest.kt | 17 +++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixPatterns.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixPatterns.kt index 82f39806c0..bae4b06a05 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixPatterns.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixPatterns.kt @@ -156,6 +156,20 @@ object MatrixPatterns { return matrixId?.substringAfter(":", missingDelimiterValue = "")?.takeIf { it.isNotEmpty() } } + /** + * Extract user name from a matrix id. + * + * @param matrixId + * @return null if the input is not a valid matrixId + */ + fun extractUserNameFromId(matrixId: String): String? { + return if (isUserId(matrixId)) { + matrixId.removePrefix("@").substringBefore(":", missingDelimiterValue = "") + } else { + null + } + } + /** * Orders which are not strings, or do not consist solely of ascii characters in the range \x20 (space) to \x7E (~), * or consist of more than 50 characters, are forbidden and the field should be ignored if received. diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/api/MatrixPatternsTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/api/MatrixPatternsTest.kt index 0d0450adc2..ec587e0536 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/api/MatrixPatternsTest.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/api/MatrixPatternsTest.kt @@ -35,6 +35,23 @@ class MatrixPatternsTest { MatrixPatterns.isUserId(input) shouldBeEqualTo expected } } + + @Test + fun `given matrix id cases, when extracting userName, then returns expected`() { + val cases = listOf( + MatrixIdCase("foobar", userName = null), + MatrixIdCase("@foobar", userName = null), + MatrixIdCase("foobar@matrix.org", userName = null), + MatrixIdCase("@foobar: matrix.org", userName = null), + MatrixIdCase("foobar:matrix.org", userName = null), + MatrixIdCase("@foobar:matrix.org", userName = "foobar"), + ) + + cases.forEach { (input, expected) -> + MatrixPatterns.extractUserNameFromId(input) shouldBeEqualTo expected + } + } } private data class UserIdCase(val input: String, val isUserId: Boolean) +private data class MatrixIdCase(val input: String, val userName: String?)