Skip to content

Commit 38763d0

Browse files
committed
adding function to extract usernames from full matrix ids
1 parent aeb881e commit 38763d0

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixPatterns.kt

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,20 @@ object MatrixPatterns {
156156
return matrixId?.substringAfter(":", missingDelimiterValue = "")?.takeIf { it.isNotEmpty() }
157157
}
158158

159+
/**
160+
* Extract user name from a matrix id.
161+
*
162+
* @param matrixId
163+
* @return null if the input is not a valid matrixId
164+
*/
165+
fun extractUserNameFromId(matrixId: String): String? {
166+
return if (isUserId(matrixId)) {
167+
matrixId.removePrefix("@").substringBefore(":", missingDelimiterValue = "")
168+
} else {
169+
null
170+
}
171+
}
172+
159173
/**
160174
* Orders which are not strings, or do not consist solely of ascii characters in the range \x20 (space) to \x7E (~),
161175
* or consist of more than 50 characters, are forbidden and the field should be ignored if received.

matrix-sdk-android/src/test/java/org/matrix/android/sdk/api/MatrixPatternsTest.kt

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,23 @@ class MatrixPatternsTest {
3535
MatrixPatterns.isUserId(input) shouldBeEqualTo expected
3636
}
3737
}
38+
39+
@Test
40+
fun `given matrix id cases, when extracting userName, then returns expected`() {
41+
val cases = listOf(
42+
MatrixIdCase("foobar", userName = null),
43+
MatrixIdCase("@foobar", userName = null),
44+
MatrixIdCase("[email protected]", userName = null),
45+
MatrixIdCase("@foobar: matrix.org", userName = null),
46+
MatrixIdCase("foobar:matrix.org", userName = null),
47+
MatrixIdCase("@foobar:matrix.org", userName = "foobar"),
48+
)
49+
50+
cases.forEach { (input, expected) ->
51+
MatrixPatterns.extractUserNameFromId(input) shouldBeEqualTo expected
52+
}
53+
}
3854
}
3955

4056
private data class UserIdCase(val input: String, val isUserId: Boolean)
57+
private data class MatrixIdCase(val input: String, val userName: String?)

0 commit comments

Comments
 (0)