Add some refactoring and first simple test on RoomListPresenter

This commit is contained in:
ganfra 2023-01-18 17:57:34 +01:00
parent aa0d997ec2
commit f7d9665eaf
30 changed files with 520 additions and 140 deletions

View file

@ -0,0 +1,69 @@
/*
* Copyright (c) 2023 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.element.android.x.matrix
import io.element.android.x.matrix.core.RoomId
import io.element.android.x.matrix.core.SessionId
import io.element.android.x.matrix.core.UserId
import io.element.android.x.matrix.media.FakeMediaResolver
import io.element.android.x.matrix.media.MediaResolver
import io.element.android.x.matrix.room.FakeMatrixRoom
import io.element.android.x.matrix.room.InMemoryRoomSummaryDataSource
import io.element.android.x.matrix.room.MatrixRoom
import io.element.android.x.matrix.room.RoomSummaryDataSource
import org.matrix.rustcomponents.sdk.MediaSource
class FakeMatrixClient(override val sessionId: SessionId) : MatrixClient {
override fun getRoom(roomId: RoomId): MatrixRoom? {
return FakeMatrixRoom(roomId)
}
override fun startSync() = Unit
override fun stopSync() = Unit
override fun roomSummaryDataSource(): RoomSummaryDataSource {
return InMemoryRoomSummaryDataSource()
}
override fun mediaResolver(): MediaResolver {
return FakeMediaResolver()
}
override suspend fun logout() = Unit
override fun userId(): UserId = UserId("")
override suspend fun loadUserDisplayName(): Result<String> {
return Result.success("")
}
override suspend fun loadUserAvatarURLString(): Result<String> {
return Result.success("")
}
override suspend fun loadMediaContentForSource(source: MediaSource): Result<ByteArray> {
return Result.success(ByteArray(0))
}
override suspend fun loadMediaThumbnailForSource(source: MediaSource, width: Long, height: Long): Result<ByteArray> {
return Result.success(ByteArray(0))
}
override fun close() = Unit
}

View file

@ -26,6 +26,7 @@ import io.element.android.x.matrix.room.MatrixRoom
import io.element.android.x.matrix.room.RoomSummaryDataSource
import io.element.android.x.matrix.room.RustMatrixRoom
import io.element.android.x.matrix.room.RustRoomSummaryDataSource
import io.element.android.x.matrix.session.PreferencesSessionStore
import io.element.android.x.matrix.session.SessionStore
import io.element.android.x.matrix.session.sessionId
import io.element.android.x.matrix.sync.SlidingSyncObserverProxy

View file

@ -0,0 +1,31 @@
/*
* Copyright (c) 2023 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.element.android.x.matrix.auth
import io.element.android.x.matrix.MatrixClient
import io.element.android.x.matrix.core.SessionId
import kotlinx.coroutines.flow.Flow
interface MatrixAuthenticationService {
fun isLoggedIn(): Flow<Boolean>
suspend fun getLatestSessionId(): SessionId?
suspend fun restoreSession(): MatrixClient?
fun getHomeserver(): String?
fun getHomeserverOrDefault(): String
suspend fun setHomeserver(homeserver: String)
suspend fun login(username: String, password: String): SessionId
}

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2022 New Vector Ltd
* Copyright (c) 2023 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -14,13 +14,13 @@
* limitations under the License.
*/
package io.element.android.x.matrix
package io.element.android.x.matrix.auth
import android.content.Context
import com.squareup.anvil.annotations.ContributesBinding
import io.element.android.x.core.coroutine.CoroutineDispatchers
import io.element.android.x.di.AppScope
import io.element.android.x.di.ApplicationContext
import io.element.android.x.di.SingleIn
import io.element.android.x.matrix.MatrixClient
import io.element.android.x.matrix.RustMatrixClient
import io.element.android.x.matrix.core.SessionId
import io.element.android.x.matrix.session.SessionStore
import io.element.android.x.matrix.session.sessionId
@ -35,26 +35,24 @@ import timber.log.Timber
import java.io.File
import javax.inject.Inject
@SingleIn(AppScope::class)
class Matrix @Inject constructor(
@ContributesBinding(AppScope::class)
class RustMatrixAuthenticationService @Inject constructor(
private val baseDirectory: File,
private val coroutineScope: CoroutineScope,
private val coroutineDispatchers: CoroutineDispatchers,
@ApplicationContext context: Context,
) {
private val sessionStore: SessionStore,
private val authService: AuthenticationService,
) : MatrixAuthenticationService {
private val baseDirectory = File(context.filesDir, "sessions")
private val sessionStore = SessionStore(context)
private val authService = AuthenticationService(baseDirectory.absolutePath)
fun isLoggedIn(): Flow<Boolean> {
override fun isLoggedIn(): Flow<Boolean> {
return sessionStore.isLoggedIn()
}
suspend fun getLatestSessionId(): SessionId? = withContext(coroutineDispatchers.io) {
override suspend fun getLatestSessionId(): SessionId? = withContext(coroutineDispatchers.io) {
sessionStore.getLatestSession()?.sessionId()
}
suspend fun restoreSession() = withContext(coroutineDispatchers.io) {
override suspend fun restoreSession() = withContext(coroutineDispatchers.io) {
sessionStore.getLatestSession()
?.let { session ->
try {
@ -73,17 +71,17 @@ class Matrix @Inject constructor(
}
}
fun getHomeserver(): String? = authService.homeserverDetails()?.url()
override fun getHomeserver(): String? = authService.homeserverDetails()?.url()
fun getHomeserverOrDefault(): String = getHomeserver() ?: "matrix.org"
override fun getHomeserverOrDefault(): String = getHomeserver() ?: "matrix.org"
suspend fun setHomeserver(homeserver: String) {
override suspend fun setHomeserver(homeserver: String) {
withContext(coroutineDispatchers.io) {
authService.configureHomeserver(homeserver)
}
}
suspend fun login(username: String, password: String): SessionId =
override suspend fun login(username: String, password: String): SessionId =
withContext(coroutineDispatchers.io) {
val client = try {
authService.login(username, password, "ElementX Android", null)

View file

@ -0,0 +1,36 @@
/*
* Copyright (c) 2023 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.element.android.x.matrix.di
import com.squareup.anvil.annotations.ContributesTo
import dagger.Module
import dagger.Provides
import io.element.android.x.di.AppScope
import io.element.android.x.di.SingleIn
import org.matrix.rustcomponents.sdk.AuthenticationService
import java.io.File
@Module
@ContributesTo(AppScope::class)
object MatrixModule {
@Provides
@SingleIn(AppScope::class)
fun providesRustAuthenticationService(baseDirectory: File): AuthenticationService {
return AuthenticationService(baseDirectory.absolutePath)
}
}

View file

@ -0,0 +1,27 @@
/*
* Copyright (c) 2023 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.element.android.x.matrix.media
class FakeMediaResolver : MediaResolver {
override suspend fun resolve(url: String?, kind: MediaResolver.Kind): ByteArray? {
return null
}
override suspend fun resolve(meta: MediaResolver.Meta): ByteArray? {
return null
}
}

View file

@ -0,0 +1,66 @@
/*
* Copyright (c) 2023 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.element.android.x.matrix.room
import io.element.android.x.matrix.core.EventId
import io.element.android.x.matrix.core.RoomId
import io.element.android.x.matrix.timeline.FakeMatrixTimeline
import io.element.android.x.matrix.timeline.MatrixTimeline
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
class FakeMatrixRoom(
override val roomId: RoomId,
override val name: String? = null,
override val bestName: String = "",
override val displayName: String = "",
override val topic: String? = null,
override val avatarUrl: String? = null
) : MatrixRoom {
override fun syncUpdateFlow(): Flow<Long> {
return emptyFlow()
}
override fun timeline(): MatrixTimeline {
return FakeMatrixTimeline()
}
override suspend fun userDisplayName(userId: String): Result<String?> {
return Result.success("")
}
override suspend fun userAvatarUrl(userId: String): Result<String?> {
TODO("Not yet implemented")
}
override suspend fun sendMessage(message: String): Result<Unit> {
TODO("Not yet implemented")
}
override suspend fun editMessage(originalEventId: EventId, message: String): Result<Unit> {
TODO("Not yet implemented")
}
override suspend fun replyMessage(eventId: EventId, message: String): Result<Unit> {
TODO("Not yet implemented")
}
override suspend fun redactEvent(eventId: EventId, reason: String?): Result<Unit> {
TODO("Not yet implemented")
}
}

View file

@ -0,0 +1,29 @@
/*
* Copyright (c) 2023 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.element.android.x.matrix.room
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
class InMemoryRoomSummaryDataSource : RoomSummaryDataSource {
override fun roomSummaries(): Flow<List<RoomSummary>> {
return emptyFlow()
}
override fun setSlidingSyncRange(range: IntRange) = Unit
}

View file

@ -0,0 +1,100 @@
/*
* Copyright (c) 2022 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.element.android.x.matrix.session
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.squareup.anvil.annotations.ContributesBinding
import io.element.android.x.di.AppScope
import io.element.android.x.di.ApplicationContext
import io.element.android.x.di.SingleIn
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.map
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.matrix.rustcomponents.sdk.Session
import javax.inject.Inject
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "elementx_sessions")
// TODO It contains the access token, so it has to be stored in a more secured storage.
private val sessionKey = stringPreferencesKey("session")
@SingleIn(AppScope::class)
@ContributesBinding(AppScope::class)
class PreferencesSessionStore @Inject constructor(
@ApplicationContext context: Context
) : SessionStore {
@Serializable
data class SessionData(
val accessToken: String,
val deviceId: String,
val homeserverUrl: String,
val isSoftLogout: Boolean,
val refreshToken: String?,
val userId: String
)
private val store = context.dataStore
override fun isLoggedIn(): Flow<Boolean> {
return store.data.map { prefs ->
prefs[sessionKey] != null
}
}
override suspend fun storeData(session: Session) {
store.edit { prefs ->
val sessionData = SessionData(
accessToken = session.accessToken,
deviceId = session.deviceId,
homeserverUrl = session.homeserverUrl,
isSoftLogout = session.isSoftLogout,
refreshToken = session.refreshToken,
userId = session.userId
)
val encodedSession = Json.encodeToString(sessionData)
prefs[sessionKey] = encodedSession
}
}
override suspend fun getLatestSession(): Session? {
return store.data.firstOrNull()?.let { prefs ->
val encodedSession = prefs[sessionKey] ?: return@let null
val sessionData = Json.decodeFromString<SessionData>(encodedSession)
Session(
accessToken = sessionData.accessToken,
deviceId = sessionData.deviceId,
homeserverUrl = sessionData.homeserverUrl,
isSoftLogout = sessionData.isSoftLogout,
refreshToken = sessionData.refreshToken,
userId = sessionData.userId
)
}
}
override suspend fun reset() {
store.edit { it.clear() }
}
}

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2022 New Vector Ltd
* Copyright (c) 2023 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,78 +16,12 @@
package io.element.android.x.matrix.session
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.map
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.matrix.rustcomponents.sdk.Session
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "elementx_sessions")
// TODO It contains the access token, so it has to be stored in a more secured storage.
private val sessionKey = stringPreferencesKey("session")
internal class SessionStore(
context: Context
) {
@Serializable
data class SessionData(
val accessToken: String,
val deviceId: String,
val homeserverUrl: String,
val isSoftLogout: Boolean,
val refreshToken: String?,
val userId: String
)
private val store = context.dataStore
fun isLoggedIn(): Flow<Boolean> {
return store.data.map { prefs ->
prefs[sessionKey] != null
}
}
suspend fun storeData(session: Session) {
store.edit { prefs ->
val sessionData = SessionData(
accessToken = session.accessToken,
deviceId = session.deviceId,
homeserverUrl = session.homeserverUrl,
isSoftLogout = session.isSoftLogout,
refreshToken = session.refreshToken,
userId = session.userId
)
val encodedSession = Json.encodeToString(sessionData)
prefs[sessionKey] = encodedSession
}
}
suspend fun getLatestSession(): Session? {
return store.data.firstOrNull()?.let { prefs ->
val encodedSession = prefs[sessionKey] ?: return@let null
val sessionData = Json.decodeFromString<SessionData>(encodedSession)
Session(
accessToken = sessionData.accessToken,
deviceId = sessionData.deviceId,
homeserverUrl = sessionData.homeserverUrl,
isSoftLogout = sessionData.isSoftLogout,
refreshToken = sessionData.refreshToken,
userId = sessionData.userId
)
}
}
suspend fun reset() {
store.edit { it.clear() }
}
interface SessionStore {
fun isLoggedIn(): Flow<Boolean>
suspend fun storeData(session: Session)
suspend fun getLatestSession(): Session?
suspend fun reset()
}

View file

@ -0,0 +1,60 @@
/*
* Copyright (c) 2023 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.element.android.x.matrix.timeline
import io.element.android.x.matrix.core.EventId
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
import org.matrix.rustcomponents.sdk.TimelineListener
class FakeMatrixTimeline : MatrixTimeline {
override var callback: MatrixTimeline.Callback?
get() = TODO("Not yet implemented")
set(value) {}
override val hasMoreToLoad: Boolean
get() = true
override fun timelineItems(): Flow<List<MatrixTimelineItem>> {
return emptyFlow()
}
override suspend fun paginateBackwards(count: Int): Result<Unit> {
return Result.success(Unit)
}
override fun addListener(timelineListener: TimelineListener) {
//
}
override fun initialize() = Unit
override fun dispose() = Unit
override suspend fun sendMessage(message: String): Result<Unit> {
return Result.success(Unit)
}
override suspend fun editMessage(originalEventId: EventId, message: String): Result<Unit> {
return Result.success(Unit)
}
override suspend fun replyMessage(inReplyToEventId: EventId, message: String): Result<Unit> {
return Result.success(Unit)
}
}