Access the various services with a getter

This commit is contained in:
Benoit Marty 2022-04-21 17:17:32 +02:00 committed by Benoit Marty
parent 016551f79f
commit 0092a7057e
164 changed files with 610 additions and 383 deletions

View File

@ -46,16 +46,16 @@ import org.matrix.android.sdk.api.util.toOptional
class FlowSession(private val session: Session) {
fun liveRoomSummaries(queryParams: RoomSummaryQueryParams, sortOrder: RoomSortOrder = RoomSortOrder.NONE): Flow<List<RoomSummary>> {
return session.getRoomSummariesLive(queryParams, sortOrder).asFlow()
return session.roomService().getRoomSummariesLive(queryParams, sortOrder).asFlow()
.startWith(session.coroutineDispatchers.io) {
session.getRoomSummaries(queryParams, sortOrder)
session.roomService().getRoomSummaries(queryParams, sortOrder)
}
}
fun liveGroupSummaries(queryParams: GroupSummaryQueryParams): Flow<List<GroupSummary>> {
return session.getGroupSummariesLive(queryParams).asFlow()
return session.groupService().getGroupSummariesLive(queryParams).asFlow()
.startWith(session.coroutineDispatchers.io) {
session.getGroupSummaries(queryParams)
session.groupService().getGroupSummaries(queryParams)
}
}
@ -67,9 +67,9 @@ class FlowSession(private val session: Session) {
}
fun liveBreadcrumbs(queryParams: RoomSummaryQueryParams): Flow<List<RoomSummary>> {
return session.getBreadcrumbsLive(queryParams).asFlow()
return session.roomService().getBreadcrumbsLive(queryParams).asFlow()
.startWith(session.coroutineDispatchers.io) {
session.getBreadcrumbs(queryParams)
session.roomService().getBreadcrumbs(queryParams)
}
}
@ -85,43 +85,47 @@ class FlowSession(private val session: Session) {
}
fun livePushers(): Flow<List<Pusher>> {
return session.getPushersLive().asFlow()
return session.pushersService().getPushersLive().asFlow()
}
fun liveUser(userId: String): Flow<Optional<User>> {
return session.getUserLive(userId).asFlow()
return session.userService().getUserLive(userId).asFlow()
.startWith(session.coroutineDispatchers.io) {
session.getUser(userId).toOptional()
session.userService().getUser(userId).toOptional()
}
}
fun liveRoomMember(userId: String, roomId: String): Flow<Optional<RoomMemberSummary>> {
return session.getRoomMemberLive(userId, roomId).asFlow()
return session.roomService().getRoomMemberLive(userId, roomId).asFlow()
.startWith(session.coroutineDispatchers.io) {
session.getRoomMember(userId, roomId).toOptional()
session.roomService().getRoomMember(userId, roomId).toOptional()
}
}
fun liveUsers(): Flow<List<User>> {
return session.getUsersLive().asFlow()
return session.userService().getUsersLive().asFlow()
}
fun liveIgnoredUsers(): Flow<List<User>> {
return session.getIgnoredUsersLive().asFlow()
return session.userService().getIgnoredUsersLive().asFlow()
}
fun livePagedUsers(filter: String? = null, excludedUserIds: Set<String>? = null): Flow<PagedList<User>> {
return session.getPagedUsersLive(filter, excludedUserIds).asFlow()
return session.userService().getPagedUsersLive(filter, excludedUserIds).asFlow()
}
fun liveThreePIds(refreshData: Boolean): Flow<List<ThreePid>> {
return session.getThreePidsLive(refreshData).asFlow()
.startWith(session.coroutineDispatchers.io) { session.getThreePids() }
return session.profileService().getThreePidsLive(refreshData).asFlow()
.startWith(session.coroutineDispatchers.io) {
session.profileService().getThreePids()
}
}
fun livePendingThreePIds(): Flow<List<ThreePid>> {
return session.getPendingThreePidsLive().asFlow()
.startWith(session.coroutineDispatchers.io) { session.getPendingThreePids() }
return session.profileService().getPendingThreePidsLive().asFlow()
.startWith(session.coroutineDispatchers.io) {
session.profileService().getPendingThreePids()
}
}
fun liveUserCryptoDevices(userId: String): Flow<List<CryptoDeviceInfo>> {
@ -179,7 +183,7 @@ class FlowSession(private val session: Session) {
}
fun liveRoomChangeMembershipState(): Flow<Map<String, ChangeMembershipState>> {
return session.getChangeMembershipsLive().asFlow()
return session.roomService().getChangeMembershipsLive().asFlow()
}
}

View File

@ -46,7 +46,7 @@ class ChangePasswordTest : InstrumentedTest {
// Change password
commonTestHelper.runBlockingTest {
session.changePassword(TestConstants.PASSWORD, NEW_PASSWORD)
session.accountService().changePassword(TestConstants.PASSWORD, NEW_PASSWORD)
}
// Try to login with the previous password, it will fail

View File

@ -47,7 +47,7 @@ class DeactivateAccountTest : InstrumentedTest {
// Deactivate the account
commonTestHelper.runBlockingTest {
session.deactivateAccount(
session.accountService().deactivateAccount(
eraseAllData = false,
userInteractiveAuthInterceptor = object : UserInteractiveAuthInterceptor {
override fun performStage(flowResponse: RegistrationFlowResponse, errCode: String?, promise: Continuation<UIABaseAuth>) {

View File

@ -431,7 +431,7 @@ class CommonTestHelper(context: Context) {
fun signOutAndClose(session: Session) {
runBlockingTest(timeout = 60_000) {
session.signOut(true)
session.signOutService().signOut(true)
}
// no need signout will close
// session.close()

View File

@ -40,6 +40,7 @@ import org.matrix.android.sdk.api.session.crypto.verification.VerificationTxStat
import org.matrix.android.sdk.api.session.events.model.Event
import org.matrix.android.sdk.api.session.events.model.EventType
import org.matrix.android.sdk.api.session.events.model.toContent
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.room.Room
import org.matrix.android.sdk.api.session.room.model.Membership
import org.matrix.android.sdk.api.session.room.model.RoomSummary
@ -64,7 +65,7 @@ class CryptoTestHelper(private val testHelper: CommonTestHelper) {
val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, defaultSessionParams)
val roomId = testHelper.runBlockingTest {
aliceSession.createRoom(CreateRoomParams().apply { name = "MyRoom" })
aliceSession.roomService().createRoom(CreateRoomParams().apply { name = "MyRoom" })
}
if (encryptedRoom) {
testHelper.waitWithLatch { latch ->
@ -98,7 +99,7 @@ class CryptoTestHelper(private val testHelper: CommonTestHelper) {
val bobSession = testHelper.createAccount(TestConstants.USER_BOB, defaultSessionParams)
testHelper.waitWithLatch { latch ->
val bobRoomSummariesLive = bobSession.getRoomSummariesLive(roomSummaryQueryParams { })
val bobRoomSummariesLive = bobSession.roomService().getRoomSummariesLive(roomSummaryQueryParams { })
val newRoomObserver = object : Observer<List<RoomSummary>> {
override fun onChanged(t: List<RoomSummary>?) {
if (t?.isNotEmpty() == true) {
@ -112,7 +113,7 @@ class CryptoTestHelper(private val testHelper: CommonTestHelper) {
}
testHelper.waitWithLatch { latch ->
val bobRoomSummariesLive = bobSession.getRoomSummariesLive(roomSummaryQueryParams { })
val bobRoomSummariesLive = bobSession.roomService().getRoomSummariesLive(roomSummaryQueryParams { })
val roomJoinedObserver = object : Observer<List<RoomSummary>> {
override fun onChanged(t: List<RoomSummary>?) {
if (bobSession.getRoom(aliceRoomId)
@ -124,7 +125,7 @@ class CryptoTestHelper(private val testHelper: CommonTestHelper) {
}
}
bobRoomSummariesLive.observeForever(roomJoinedObserver)
bobSession.joinRoom(aliceRoomId)
bobSession.roomService().joinRoom(aliceRoomId)
}
// Ensure bob can send messages to the room
// val roomFromBobPOV = bobSession.getRoom(aliceRoomId)!!
@ -164,7 +165,7 @@ class CryptoTestHelper(private val testHelper: CommonTestHelper) {
}
testHelper.runBlockingTest {
samSession.joinRoom(room.roomId, null, emptyList())
samSession.roomService().joinRoom(room.roomId, null, emptyList())
}
return samSession
@ -242,8 +243,8 @@ class CryptoTestHelper(private val testHelper: CommonTestHelper) {
fun createDM(alice: Session, bob: Session): String {
var roomId: String = ""
testHelper.waitWithLatch { latch ->
roomId = alice.createDirectRoom(bob.myUserId)
val bobRoomSummariesLive = bob.getRoomSummariesLive(roomSummaryQueryParams { })
roomId = alice.roomService().createDirectRoom(bob.myUserId)
val bobRoomSummariesLive = bob.roomService().getRoomSummariesLive(roomSummaryQueryParams { })
val newRoomObserver = object : Observer<List<RoomSummary>> {
override fun onChanged(t: List<RoomSummary>?) {
if (t?.any { it.roomId == roomId }.orFalse()) {
@ -256,7 +257,7 @@ class CryptoTestHelper(private val testHelper: CommonTestHelper) {
}
testHelper.waitWithLatch { latch ->
val bobRoomSummariesLive = bob.getRoomSummariesLive(roomSummaryQueryParams { })
val bobRoomSummariesLive = bob.roomService().getRoomSummariesLive(roomSummaryQueryParams { })
val newRoomObserver = object : Observer<List<RoomSummary>> {
override fun onChanged(t: List<RoomSummary>?) {
if (bob.getRoom(roomId)
@ -268,7 +269,7 @@ class CryptoTestHelper(private val testHelper: CommonTestHelper) {
}
}
bobRoomSummariesLive.observeForever(newRoomObserver)
bob.joinRoom(roomId)
bob.roomService().joinRoom(roomId)
}
return roomId
@ -367,7 +368,7 @@ class CryptoTestHelper(private val testHelper: CommonTestHelper) {
aliceSession.cryptoService().setWarnOnUnknownDevices(false)
val roomId = testHelper.runBlockingTest {
aliceSession.createRoom(CreateRoomParams().apply { name = "MyRoom" })
aliceSession.roomService().createRoom(CreateRoomParams().apply { name = "MyRoom" })
}
val room = aliceSession.getRoom(roomId)!!
@ -380,7 +381,7 @@ class CryptoTestHelper(private val testHelper: CommonTestHelper) {
val session = testHelper.createAccount("User_$index", defaultSessionParams)
testHelper.runBlockingTest(timeout = 600_000) { room.invite(session.myUserId, null) }
println("TEST -> " + session.myUserId + " invited")
testHelper.runBlockingTest { session.joinRoom(room.roomId, null, emptyList()) }
testHelper.runBlockingTest { session.roomService().joinRoom(room.roomId, null, emptyList()) }
println("TEST -> " + session.myUserId + " joined")
sessions.add(session)
}

View File

@ -38,6 +38,8 @@ import org.matrix.android.sdk.api.session.crypto.model.OlmDecryptionResult
import org.matrix.android.sdk.api.session.events.model.EventType
import org.matrix.android.sdk.api.session.events.model.content.EncryptedEventContent
import org.matrix.android.sdk.api.session.events.model.toModel
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.getRoomSummary
import org.matrix.android.sdk.api.session.room.Room
import org.matrix.android.sdk.api.session.room.failure.JoinRoomFailure
import org.matrix.android.sdk.api.session.room.model.Membership
@ -551,7 +553,7 @@ class E2eeSanityTests : InstrumentedTest {
testHelper.waitWithLatch { latch ->
testHelper.retryPeriodicallyWithLatch(latch) {
otherAccounts.map {
aliceSession.getRoomMember(it.myUserId, e2eRoomID)?.membership
aliceSession.roomService().getRoomMember(it.myUserId, e2eRoomID)?.membership
}.all {
it == Membership.JOIN
}
@ -574,7 +576,7 @@ class E2eeSanityTests : InstrumentedTest {
testHelper.runBlockingTest(60_000) {
Log.v("#E2E TEST", "${otherSession.myUserId} tries to join room $e2eRoomID")
try {
otherSession.joinRoom(e2eRoomID)
otherSession.roomService().joinRoom(e2eRoomID)
} catch (ex: JoinRoomFailure.JoinedWithTimeout) {
// it's ok we will wait after
}

View File

@ -29,6 +29,7 @@ import org.matrix.android.sdk.api.session.events.model.EventType
import org.matrix.android.sdk.api.session.events.model.content.EncryptedEventContent
import org.matrix.android.sdk.api.session.events.model.content.RoomKeyContent
import org.matrix.android.sdk.api.session.events.model.toModel
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.common.CommonTestHelper
import org.matrix.android.sdk.common.CryptoTestHelper

View File

@ -34,6 +34,7 @@ import org.matrix.android.sdk.api.session.crypto.MXCryptoError
import org.matrix.android.sdk.api.session.events.model.EventType
import org.matrix.android.sdk.api.session.events.model.content.EncryptedEventContent
import org.matrix.android.sdk.api.session.events.model.toModel
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.room.timeline.Timeline
import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent
import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings

View File

@ -28,6 +28,7 @@ import org.matrix.android.sdk.api.crypto.MXCRYPTO_ALGORITHM_MEGOLM
import org.matrix.android.sdk.api.session.events.model.EventType
import org.matrix.android.sdk.api.session.events.model.content.EncryptionEventContent
import org.matrix.android.sdk.api.session.events.model.toContent
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.room.Room
import org.matrix.android.sdk.api.session.room.send.SendState
import org.matrix.android.sdk.api.session.room.timeline.Timeline

View File

@ -50,6 +50,7 @@ import org.matrix.android.sdk.api.session.crypto.verification.VerificationTransa
import org.matrix.android.sdk.api.session.crypto.verification.VerificationTxState
import org.matrix.android.sdk.api.session.events.model.content.EncryptedEventContent
import org.matrix.android.sdk.api.session.events.model.toModel
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.room.model.RoomDirectoryVisibility
import org.matrix.android.sdk.api.session.room.model.create.CreateRoomParams
import org.matrix.android.sdk.api.session.room.model.message.MessageContent
@ -73,7 +74,7 @@ class KeyShareTests : InstrumentedTest {
// Create an encrypted room and add a message
val roomId = commonTestHelper.runBlockingTest {
aliceSession.createRoom(
aliceSession.roomService().createRoom(
CreateRoomParams().apply {
visibility = RoomDirectoryVisibility.PRIVATE
enableEncryption()
@ -340,7 +341,7 @@ class KeyShareTests : InstrumentedTest {
// Create an encrypted room and send a couple of messages
val roomId = commonTestHelper.runBlockingTest {
aliceSession.createRoom(
aliceSession.roomService().createRoom(
CreateRoomParams().apply {
visibility = RoomDirectoryVisibility.PRIVATE
enableEncryption()
@ -378,7 +379,7 @@ class KeyShareTests : InstrumentedTest {
}
commonTestHelper.runBlockingTest {
bobSession.joinRoom(roomAlicePov.roomId, null, emptyList())
bobSession.roomService().joinRoom(roomAlicePov.roomId, null, emptyList())
}
// we want to discard alice outbound session

View File

@ -33,6 +33,7 @@ import org.matrix.android.sdk.api.session.events.model.EventType
import org.matrix.android.sdk.api.session.events.model.content.EncryptedEventContent
import org.matrix.android.sdk.api.session.events.model.content.WithHeldCode
import org.matrix.android.sdk.api.session.events.model.toModel
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.common.CommonTestHelper
import org.matrix.android.sdk.common.CryptoTestHelper
import org.matrix.android.sdk.common.MockOkHttpInterceptor

View File

@ -41,6 +41,7 @@ import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysVersion
import org.matrix.android.sdk.api.session.crypto.keysbackup.MegolmBackupCreationInfo
import org.matrix.android.sdk.api.session.crypto.keysbackup.toKeysVersionResult
import org.matrix.android.sdk.api.session.crypto.model.ImportRoomKeysResult
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.common.CommonTestHelper
import org.matrix.android.sdk.common.CryptoTestHelper
import org.matrix.android.sdk.common.TestConstants

View File

@ -60,7 +60,7 @@ class QuadSTests : InstrumentedTest {
val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true))
val quadS = aliceSession.sharedSecretStorageService
val quadS = aliceSession.sharedSecretStorageService()
val TEST_KEY_ID = "my.test.Key"
@ -120,7 +120,7 @@ class QuadSTests : InstrumentedTest {
// Store a secret
val clearSecret = "42".toByteArray().toBase64NoPadding()
testHelper.runBlockingTest {
aliceSession.sharedSecretStorageService.storeSecret(
aliceSession.sharedSecretStorageService().storeSecret(
"secret.of.life",
clearSecret,
listOf(SharedSecretStorageService.KeyRef(null, keySpec)) // default key
@ -141,7 +141,7 @@ class QuadSTests : InstrumentedTest {
// Try to decrypt??
val decryptedSecret = testHelper.runBlockingTest {
aliceSession.sharedSecretStorageService.getSecret(
aliceSession.sharedSecretStorageService().getSecret(
"secret.of.life",
null, // default key
keySpec!!
@ -158,7 +158,7 @@ class QuadSTests : InstrumentedTest {
val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true))
val quadS = aliceSession.sharedSecretStorageService
val quadS = aliceSession.sharedSecretStorageService()
val TEST_KEY_ID = "my.test.Key"
@ -187,7 +187,7 @@ class QuadSTests : InstrumentedTest {
val mySecretText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit"
testHelper.runBlockingTest {
aliceSession.sharedSecretStorageService.storeSecret(
aliceSession.sharedSecretStorageService().storeSecret(
"my.secret",
mySecretText.toByteArray().toBase64NoPadding(),
listOf(
@ -207,14 +207,14 @@ class QuadSTests : InstrumentedTest {
// Assert that can decrypt with both keys
testHelper.runBlockingTest {
aliceSession.sharedSecretStorageService.getSecret("my.secret",
aliceSession.sharedSecretStorageService().getSecret("my.secret",
keyId1,
RawBytesKeySpec.fromRecoveryKey(key1Info.recoveryKey)!!
)
}
testHelper.runBlockingTest {
aliceSession.sharedSecretStorageService.getSecret("my.secret",
aliceSession.sharedSecretStorageService().getSecret("my.secret",
keyId2,
RawBytesKeySpec.fromRecoveryKey(key2Info.recoveryKey)!!
)
@ -236,7 +236,7 @@ class QuadSTests : InstrumentedTest {
val mySecretText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit"
testHelper.runBlockingTest {
aliceSession.sharedSecretStorageService.storeSecret(
aliceSession.sharedSecretStorageService().storeSecret(
"my.secret",
mySecretText.toByteArray().toBase64NoPadding(),
listOf(SharedSecretStorageService.KeyRef(keyId1, RawBytesKeySpec.fromRecoveryKey(key1Info.recoveryKey)))
@ -245,7 +245,7 @@ class QuadSTests : InstrumentedTest {
testHelper.runBlockingTest {
try {
aliceSession.sharedSecretStorageService.getSecret("my.secret",
aliceSession.sharedSecretStorageService().getSecret("my.secret",
keyId1,
RawBytesKeySpec.fromPassphrase(
"A bad passphrase",
@ -260,7 +260,7 @@ class QuadSTests : InstrumentedTest {
// Now try with correct key
testHelper.runBlockingTest {
aliceSession.sharedSecretStorageService.getSecret("my.secret",
aliceSession.sharedSecretStorageService().getSecret("my.secret",
keyId1,
RawBytesKeySpec.fromPassphrase(
passphrase,
@ -292,7 +292,7 @@ class QuadSTests : InstrumentedTest {
}
private fun generatedSecret(session: Session, keyId: String, asDefault: Boolean = true): SsssKeyCreationInfo {
val quadS = session.sharedSecretStorageService
val quadS = session.sharedSecretStorageService()
val testHelper = CommonTestHelper(context())
val creationInfo = testHelper.runBlockingTest {
@ -312,7 +312,7 @@ class QuadSTests : InstrumentedTest {
}
private fun generatedSecretFromPassphrase(session: Session, passphrase: String, keyId: String, asDefault: Boolean = true): SsssKeyCreationInfo {
val quadS = session.sharedSecretStorageService
val quadS = session.sharedSecretStorageService()
val testHelper = CommonTestHelper(context())
val creationInfo = testHelper.runBlockingTest {

View File

@ -31,6 +31,7 @@ import org.matrix.android.sdk.InstrumentedTest
import org.matrix.android.sdk.api.session.events.model.getRootThreadEventId
import org.matrix.android.sdk.api.session.events.model.isTextMessage
import org.matrix.android.sdk.api.session.events.model.isThread
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.room.timeline.Timeline
import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings
import org.matrix.android.sdk.common.CommonTestHelper

View File

@ -30,6 +30,7 @@ import org.junit.runners.MethodSorters
import org.matrix.android.sdk.InstrumentedTest
import org.matrix.android.sdk.api.session.events.model.EventType
import org.matrix.android.sdk.api.session.events.model.toModel
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.room.model.PollResponseAggregatedSummary
import org.matrix.android.sdk.api.session.room.model.PollSummaryContent
import org.matrix.android.sdk.api.session.room.model.message.MessagePollContent

View File

@ -30,6 +30,7 @@ import org.matrix.android.sdk.InstrumentedTest
import org.matrix.android.sdk.api.extensions.orFalse
import org.matrix.android.sdk.api.session.events.model.EventType
import org.matrix.android.sdk.api.session.events.model.toModel
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.room.model.message.MessageContent
import org.matrix.android.sdk.api.session.room.timeline.Timeline
import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings

View File

@ -28,6 +28,7 @@ import org.matrix.android.sdk.InstrumentedTest
import org.matrix.android.sdk.api.extensions.orFalse
import org.matrix.android.sdk.api.session.events.model.EventType
import org.matrix.android.sdk.api.session.events.model.toModel
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.room.model.message.MessageContent
import org.matrix.android.sdk.api.session.room.timeline.Timeline
import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings

View File

@ -28,6 +28,7 @@ import org.matrix.android.sdk.InstrumentedTest
import org.matrix.android.sdk.api.extensions.orFalse
import org.matrix.android.sdk.api.session.events.model.isTextMessage
import org.matrix.android.sdk.api.session.events.model.toModel
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.room.model.message.MessageTextContent
import org.matrix.android.sdk.api.session.room.timeline.Timeline
import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings

View File

@ -27,6 +27,7 @@ import org.junit.runners.MethodSorters
import org.matrix.android.sdk.InstrumentedTest
import org.matrix.android.sdk.api.extensions.orFalse
import org.matrix.android.sdk.api.session.events.model.toModel
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.room.model.message.MessageContent
import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings
import org.matrix.android.sdk.common.CommonTestHelper

View File

@ -24,6 +24,7 @@ import org.junit.runners.JUnit4
import org.junit.runners.MethodSorters
import org.matrix.android.sdk.InstrumentedTest
import org.matrix.android.sdk.api.extensions.orFalse
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.search.SearchResult
import org.matrix.android.sdk.common.CommonTestHelper
import org.matrix.android.sdk.common.CryptoTestData

View File

@ -147,7 +147,7 @@ class SpaceCreationTest : InstrumentedTest {
// create a room
var firstChild: String? = null
commonTestHelper.waitWithLatch {
firstChild = aliceSession.createRoom(CreateRoomParams().apply {
firstChild = aliceSession.roomService().createRoom(CreateRoomParams().apply {
this.name = "FirstRoom"
this.topic = "Description of first room"
this.preset = CreateRoomPreset.PRESET_PUBLIC_CHAT
@ -162,7 +162,7 @@ class SpaceCreationTest : InstrumentedTest {
var secondChild: String? = null
commonTestHelper.waitWithLatch {
secondChild = aliceSession.createRoom(CreateRoomParams().apply {
secondChild = aliceSession.roomService().createRoom(CreateRoomParams().apply {
this.name = "SecondRoom"
this.topic = "Description of second room"
this.preset = CreateRoomPreset.PRESET_PUBLIC_CHAT

View File

@ -35,6 +35,8 @@ import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.events.model.EventType
import org.matrix.android.sdk.api.session.events.model.toContent
import org.matrix.android.sdk.api.session.events.model.toModel
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.getRoomSummary
import org.matrix.android.sdk.api.session.room.model.PowerLevelsContent
import org.matrix.android.sdk.api.session.room.model.RoomJoinRulesAllowEntry
import org.matrix.android.sdk.api.session.room.model.RoomSummary
@ -68,7 +70,7 @@ class SpaceHierarchyTest : InstrumentedTest {
var roomId = ""
commonTestHelper.waitWithLatch {
roomId = session.createRoom(CreateRoomParams().apply { name = "General" })
roomId = session.roomService().createRoom(CreateRoomParams().apply { name = "General" })
it.countDown()
}
@ -203,27 +205,27 @@ class SpaceHierarchyTest : InstrumentedTest {
var orphan1 = ""
commonTestHelper.waitWithLatch {
orphan1 = session.createRoom(CreateRoomParams().apply { name = "O1" })
orphan1 = session.roomService().createRoom(CreateRoomParams().apply { name = "O1" })
it.countDown()
}
var orphan2 = ""
commonTestHelper.waitWithLatch {
orphan2 = session.createRoom(CreateRoomParams().apply { name = "O2" })
orphan2 = session.roomService().createRoom(CreateRoomParams().apply { name = "O2" })
it.countDown()
}
val allRooms = session.getRoomSummaries(roomSummaryQueryParams { excludeType = listOf(RoomType.SPACE) })
val allRooms = session.roomService().getRoomSummaries(roomSummaryQueryParams { excludeType = listOf(RoomType.SPACE) })
assertEquals("Unexpected number of rooms", 9, allRooms.size)
val orphans = session.getFlattenRoomSummaryChildrenOf(null)
val orphans = session.roomService().getFlattenRoomSummaryChildrenOf(null)
assertEquals("Unexpected number of orphan rooms", 2, orphans.size)
assertTrue("O1 should be an orphan", orphans.any { it.roomId == orphan1 })
assertTrue("O2 should be an orphan ${orphans.map { it.name }}", orphans.any { it.roomId == orphan2 })
val aChildren = session.getFlattenRoomSummaryChildrenOf(spaceAInfo.spaceId)
val aChildren = session.roomService().getFlattenRoomSummaryChildrenOf(spaceAInfo.spaceId)
assertEquals("Unexpected number of flatten child rooms", 4, aChildren.size)
assertTrue("A1 should be a child of A", aChildren.any { it.name == "A1" })
@ -233,13 +235,13 @@ class SpaceHierarchyTest : InstrumentedTest {
// Add a non canonical child and check that it does not appear as orphan
commonTestHelper.waitWithLatch {
val a3 = session.createRoom(CreateRoomParams().apply { name = "A3" })
val a3 = session.roomService().createRoom(CreateRoomParams().apply { name = "A3" })
spaceA!!.addChildren(a3, viaServers, null, false)
it.countDown()
}
Thread.sleep(6_000)
val orphansUpdate = session.getRoomSummaries(roomSummaryQueryParams {
val orphansUpdate = session.roomService().getRoomSummaries(roomSummaryQueryParams {
activeSpaceFilter = ActiveSpaceFilter.ActiveSpace(null)
})
assertEquals("Unexpected number of orphan rooms ${orphansUpdate.map { it.name }}", 2, orphansUpdate.size)
@ -279,7 +281,7 @@ class SpaceHierarchyTest : InstrumentedTest {
// A -> C -> A
val aChildren = session.getFlattenRoomSummaryChildrenOf(spaceAInfo.spaceId)
val aChildren = session.roomService().getFlattenRoomSummaryChildrenOf(spaceAInfo.spaceId)
assertEquals("Unexpected number of flatten child rooms ${aChildren.map { it.name }}", 4, aChildren.size)
assertTrue("A1 should be a child of A", aChildren.any { it.name == "A1" })
@ -319,7 +321,7 @@ class SpaceHierarchyTest : InstrumentedTest {
commonTestHelper.waitWithLatch { latch ->
val flatAChildren = session.getFlattenRoomSummaryChildrenOfLive(spaceAInfo.spaceId)
val flatAChildren = session.roomService().getFlattenRoomSummaryChildrenOfLive(spaceAInfo.spaceId)
val childObserver = object : Observer<List<RoomSummary>> {
override fun onChanged(children: List<RoomSummary>?) {
// Log.d("## TEST", "Space A flat children update : ${children?.map { it.name }}")
@ -346,7 +348,7 @@ class SpaceHierarchyTest : InstrumentedTest {
val bRoomId = spaceBInfo.roomIds.first()
commonTestHelper.waitWithLatch { latch ->
val flatAChildren = session.getFlattenRoomSummaryChildrenOfLive(spaceAInfo.spaceId)
val flatAChildren = session.roomService().getFlattenRoomSummaryChildrenOfLive(spaceAInfo.spaceId)
val childObserver = object : Observer<List<RoomSummary>> {
override fun onChanged(children: List<RoomSummary>?) {
System.out.println("## TEST | Space A flat children update : ${children?.map { it.name }}")
@ -359,7 +361,7 @@ class SpaceHierarchyTest : InstrumentedTest {
}
// part from b room
session.leaveRoom(bRoomId)
session.roomService().leaveRoom(bRoomId)
// The room should have disapear from flat children
flatAChildren.observeForever(childObserver)
}
@ -385,7 +387,7 @@ class SpaceHierarchyTest : InstrumentedTest {
val viaServers = listOf(session.sessionParams.homeServerHost ?: "")
roomIds = childInfo.map { entry ->
session.createRoom(CreateRoomParams().apply { name = entry.first })
session.roomService().createRoom(CreateRoomParams().apply { name = entry.first })
}
roomIds.forEachIndexed { index, roomId ->
syncedSpace!!.addChildren(roomId, viaServers, null, childInfo[index].second)
@ -414,8 +416,9 @@ class SpaceHierarchyTest : InstrumentedTest {
roomIds =
childInfo.map { entry ->
val homeServerCapabilities = session
.homeServerCapabilitiesService()
.getHomeServerCapabilities()
session.createRoom(CreateRoomParams().apply {
session.roomService().createRoom(CreateRoomParams().apply {
name = entry.first
this.featurePreset = RestrictedRoomPreset(
homeServerCapabilities,
@ -498,18 +501,18 @@ class SpaceHierarchyTest : InstrumentedTest {
}
commonTestHelper.runBlockingTest {
bobSession.joinRoom(spaceAInfo.spaceId, null, emptyList())
bobSession.roomService().joinRoom(spaceAInfo.spaceId, null, emptyList())
}
var bobRoomId = ""
commonTestHelper.waitWithLatch {
bobRoomId = bobSession.createRoom(CreateRoomParams().apply { name = "A Bob Room" })
bobRoomId = bobSession.roomService().createRoom(CreateRoomParams().apply { name = "A Bob Room" })
bobSession.getRoom(bobRoomId)!!.invite(aliceSession.myUserId)
it.countDown()
}
commonTestHelper.runBlockingTest {
aliceSession.joinRoom(bobRoomId)
aliceSession.roomService().joinRoom(bobRoomId)
}
commonTestHelper.waitWithLatch { latch ->

View File

@ -26,7 +26,6 @@ import org.matrix.android.sdk.api.failure.GlobalError
import org.matrix.android.sdk.api.federation.FederationService
import org.matrix.android.sdk.api.session.account.AccountService
import org.matrix.android.sdk.api.session.accountdata.SessionAccountDataService
import org.matrix.android.sdk.api.session.cache.CacheService
import org.matrix.android.sdk.api.session.call.CallSignalingService
import org.matrix.android.sdk.api.session.content.ContentUploadStateTracker
import org.matrix.android.sdk.api.session.content.ContentUrlResolver
@ -68,26 +67,7 @@ import org.matrix.android.sdk.api.session.widgets.WidgetService
* This interface defines interactions with a session.
* An instance of a session will be provided by the SDK.
*/
interface Session :
RoomService,
RoomDirectoryService,
GroupService,
UserService,
CacheService,
SignOutService,
FilterService,
TermsService,
EventService,
ProfileService,
PresenceService,
PushRuleService,
PushersService,
SyncStatusService,
HomeServerCapabilitiesService,
SecureStorageService,
AccountService,
ToDeviceService,
EventStreamService {
interface Session {
val coroutineDispatchers: MatrixCoroutineDispatchers
@ -144,6 +124,11 @@ interface Session :
*/
fun stopSync()
/**
* Clear cache of the session
*/
suspend fun clearCache()
/**
* This method allows to listen the sync state.
* @return a [LiveData] of [SyncState].
@ -206,6 +191,96 @@ interface Session :
*/
fun identityService(): IdentityService
/**
* Returns the HomeServerCapabilities service associated with the session
*/
fun homeServerCapabilitiesService(): HomeServerCapabilitiesService
/**
* Returns the RoomService associated with the session
*/
fun roomService(): RoomService
/**
* Returns the RoomDirectoryService associated with the session
*/
fun roomDirectoryService(): RoomDirectoryService
/**
* Returns the GroupService associated with the session
*/
fun groupService(): GroupService
/**
* Returns the UserService associated with the session
*/
fun userService(): UserService
/**
* Returns the SignOutService associated with the session
*/
fun signOutService(): SignOutService
/**
* Returns the FilterService associated with the session
*/
fun filterService(): FilterService
/**
* Returns the PushRuleService associated with the session
*/
fun pushRuleService(): PushRuleService
/**
* Returns the PushersService associated with the session
*/
fun pushersService(): PushersService
/**
* Returns the EventService associated with the session
*/
fun eventService(): EventService
/**
* Returns the TermsService associated with the session
*/
fun termsService(): TermsService
/**
* Returns the SyncStatusService associated with the session
*/
fun syncStatusService(): SyncStatusService
/**
* Returns the SecureStorageService associated with the session
*/
fun secureStorageService(): SecureStorageService
/**
* Returns the ProfileService associated with the session
*/
fun profileService(): ProfileService
/**
* Returns the PresenceService associated with the session
*/
fun presenceService(): PresenceService
/**
* Returns the AccountService associated with the session
*/
fun accountService(): AccountService
/**
* Returns the ToDeviceService associated with the session
*/
fun toDeviceService(): ToDeviceService
/**
* Returns the EventStreamService associated with the session
*/
fun eventStreamService(): EventStreamService
/**
* Returns the widget service associated with the session
*/
@ -266,6 +341,11 @@ interface Session :
*/
fun accountDataService(): SessionAccountDataService
/**
* Returns the SharedSecretStorageService associated with the session
*/
fun sharedSecretStorageService(): SharedSecretStorageService
/**
* Add a listener to the session.
* @param listener the listener to add.
@ -303,8 +383,6 @@ interface Session :
fun onGlobalError(session: Session, globalError: GlobalError) = Unit
}
val sharedSecretStorageService: SharedSecretStorageService
fun getUiaSsoFallbackUrl(authenticationSessionId: String): String
/**

View File

@ -0,0 +1,36 @@
/*
* Copyright (c) 2022 The Matrix.org Foundation C.I.C.
*
* 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 org.matrix.android.sdk.api.session
import org.matrix.android.sdk.api.session.room.Room
import org.matrix.android.sdk.api.session.room.model.RoomSummary
import org.matrix.android.sdk.api.session.user.model.User
/**
* Get a room using the RoomService of a Session
*/
fun Session.getRoom(roomId: String): Room? = roomService().getRoom(roomId)
/**
* Get a room summary using the RoomService of a Session
*/
fun Session.getRoomSummary(roomIdOrAlias: String): RoomSummary? = roomService().getRoomSummary(roomIdOrAlias)
/**
* Get a user using the UserService of a Session
*/
fun Session.getUser(userId: String): User? = userService().getUser(userId)

View File

@ -124,7 +124,7 @@ internal class DefaultSession @Inject constructor(
private val syncStatusService: Lazy<SyncStatusService>,
private val homeServerCapabilitiesService: Lazy<HomeServerCapabilitiesService>,
private val accountDataService: Lazy<SessionAccountDataService>,
private val _sharedSecretStorageService: Lazy<SharedSecretStorageService>,
private val sharedSecretStorageService: Lazy<SharedSecretStorageService>,
private val accountService: Lazy<AccountService>,
private val eventService: Lazy<EventService>,
private val contentScannerService: Lazy<ContentScannerService>,
@ -140,28 +140,7 @@ internal class DefaultSession @Inject constructor(
@UnauthenticatedWithCertificate
private val unauthenticatedWithCertificateOkHttpClient: Lazy<OkHttpClient>
) : Session,
GlobalErrorHandler.Listener,
RoomService by roomService.get(),
RoomDirectoryService by roomDirectoryService.get(),
GroupService by groupService.get(),
UserService by userService.get(),
SignOutService by signOutService.get(),
FilterService by filterService.get(),
PushRuleService by pushRuleService.get(),
PushersService by pushersService.get(),
EventService by eventService.get(),
TermsService by termsService.get(),
SyncStatusService by syncStatusService.get(),
SecureStorageService by secureStorageService.get(),
HomeServerCapabilitiesService by homeServerCapabilitiesService.get(),
ProfileService by profileService.get(),
PresenceService by presenceService.get(),
AccountService by accountService.get(),
ToDeviceService by toDeviceService.get(),
EventStreamService by eventStreamService.get() {
override val sharedSecretStorageService: SharedSecretStorageService
get() = _sharedSecretStorageService.get()
GlobalErrorHandler.Listener {
private var isOpen = false
@ -274,42 +253,44 @@ internal class DefaultSession @Inject constructor(
}
override fun contentUrlResolver() = contentUrlResolver
override fun contentUploadProgressTracker() = contentUploadProgressTracker
override fun typingUsersTracker() = typingUsersTracker
override fun contentDownloadProgressTracker(): ContentDownloadStateTracker = contentDownloadStateTracker
override fun cryptoService(): CryptoService = cryptoService.get()
override fun contentScannerService(): ContentScannerService = contentScannerService.get()
override fun identityService(): IdentityService = identityService.get()
override fun homeServerCapabilitiesService(): HomeServerCapabilitiesService = homeServerCapabilitiesService.get()
override fun roomService(): RoomService = roomService.get()
override fun roomDirectoryService(): RoomDirectoryService = roomDirectoryService.get()
override fun groupService(): GroupService = groupService.get()
override fun userService(): UserService = userService.get()
override fun signOutService(): SignOutService = signOutService.get()
override fun filterService(): FilterService = filterService.get()
override fun pushRuleService(): PushRuleService = pushRuleService.get()
override fun pushersService(): PushersService = pushersService.get()
override fun eventService(): EventService = eventService.get()
override fun termsService(): TermsService = termsService.get()
override fun syncStatusService(): SyncStatusService = syncStatusService.get()
override fun secureStorageService(): SecureStorageService = secureStorageService.get()
override fun profileService(): ProfileService = profileService.get()
override fun presenceService(): PresenceService = presenceService.get()
override fun accountService(): AccountService = accountService.get()
override fun toDeviceService(): ToDeviceService = toDeviceService.get()
override fun eventStreamService(): EventStreamService = eventStreamService.get()
override fun fileService(): FileService = defaultFileService.get()
override fun permalinkService(): PermalinkService = permalinkService.get()
override fun widgetService(): WidgetService = widgetService.get()
override fun mediaService(): MediaService = mediaService.get()
override fun integrationManagerService(): IntegrationManagerService = integrationManagerService.get()
override fun callSignalingService(): CallSignalingService = callSignalingService.get()
override fun searchService(): SearchService = searchService.get()
override fun federationService(): FederationService = federationService.get()
override fun thirdPartyService(): ThirdPartyService = thirdPartyService.get()
override fun spaceService(): SpaceService = spaceService.get()
override fun openIdService(): OpenIdService = openIdService.get()
override fun accountDataService(): SessionAccountDataService = accountDataService.get()
override fun sharedSecretStorageService(): SharedSecretStorageService = sharedSecretStorageService.get()
override fun getOkHttpClient(): OkHttpClient {
return unauthenticatedWithCertificateOkHttpClient.get()

View File

@ -542,7 +542,7 @@ internal class EventRelationsAggregationProcessor @Inject constructor(
private fun getPollEvent(roomId: String, eventId: String): TimelineEvent? {
val session = sessionManager.getSessionComponent(sessionId)?.session()
return session?.getRoom(roomId)?.getTimelineEvent(eventId) ?: return null.also {
return session?.roomService()?.getRoom(roomId)?.getTimelineEvent(eventId) ?: return null.also {
Timber.v("## POLL target poll event $eventId not found in room $roomId")
}
}

View File

@ -107,7 +107,7 @@ internal class DefaultSyncTask @Inject constructor(
val isInitialSync = token == null
if (isInitialSync) {
// We might want to get the user information in parallel too
val user = tryOrNull { session.getProfileAsUser(userId) }
val user = tryOrNull { session.profileService().getProfileAsUser(userId) }
userStore.createOrUpdate(
userId = userId,
displayName = user?.displayName,

View File

@ -166,7 +166,7 @@ class SecurityBootstrapTest : VerificationTestBase() {
assert(uiSession.cryptoService().crossSigningService().allPrivateKeysKnown())
assert(uiSession.cryptoService().keysBackupService().isEnabled)
assert(uiSession.cryptoService().keysBackupService().currentBackupVersion != null)
assert(uiSession.sharedSecretStorageService.isRecoverySetup())
assert(uiSession.sharedSecretStorageService.isMegolmKeyInBackup())
assert(uiSession.sharedSecretStorageService().isRecoverySetup())
assert(uiSession.sharedSecretStorageService().isMegolmKeyInBackup())
}
}

View File

@ -49,7 +49,7 @@ class TestTokenRegistration @Inject constructor(private val context: FragmentAct
status = TestStatus.FAILED
return
}
val pushers = session.getPushers().filter {
val pushers = session.pushersService().getPushers().filter {
it.pushKey == fcmToken && it.state == PusherState.REGISTERED
}
if (pushers.isEmpty()) {

View File

@ -46,6 +46,7 @@ import kotlinx.coroutines.runBlocking
import org.matrix.android.sdk.api.extensions.tryOrNull
import org.matrix.android.sdk.api.logger.LoggerTag
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.getRoom
import timber.log.Timber
import javax.inject.Inject
@ -194,7 +195,7 @@ class VectorFirebaseMessagingService : FirebaseMessagingService() {
coroutineScope.launch {
Timber.tag(loggerTag.value).d("Fast lane: start request")
val event = tryOrNull { session.getEvent(roomId, eventId) } ?: return@launch
val event = tryOrNull { session.eventService().getEvent(roomId, eventId) } ?: return@launch
val resolvedEvent = notifiableEventResolver.resolveInMemoryEvent(session, event, canBeReplaced = true)

View File

@ -38,6 +38,8 @@ import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import org.matrix.android.sdk.api.extensions.tryOrNull
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.getRoomSummary
import org.matrix.android.sdk.api.session.group.model.GroupSummary
import org.matrix.android.sdk.api.session.initsync.SyncStatusService
import org.matrix.android.sdk.api.session.room.model.RoomSummary
@ -78,7 +80,7 @@ class AppStateHandler @Inject constructor(
return selectedSpaceDataSource.currentValue?.orNull()?.let {
if (it is RoomGroupingMethod.BySpace) {
// try to refresh sum?
it.spaceSummary?.roomId?.let { activeSessionHolder.getSafeActiveSession()?.getRoomSummary(it) }?.let {
it.spaceSummary?.roomId?.let { activeSessionHolder.getSafeActiveSession()?.roomService()?.getRoomSummary(it) }?.let {
RoomGroupingMethod.BySpace(it)
} ?: it
} else it
@ -110,12 +112,12 @@ class AppStateHandler @Inject constructor(
val uSession = session ?: activeSessionHolder.getSafeActiveSession() ?: return
if (selectedSpaceDataSource.currentValue?.orNull() is RoomGroupingMethod.ByLegacyGroup &&
groupId == selectedSpaceDataSource.currentValue?.orNull()?.group()?.groupId) return
val activeGroup = groupId?.let { uSession.getGroupSummary(groupId) }
val activeGroup = groupId?.let { uSession.groupService().getGroupSummary(groupId) }
selectedSpaceDataSource.post(Option.just(RoomGroupingMethod.ByLegacyGroup(activeGroup)))
if (groupId != null) {
uSession.coroutineScope.launch {
tryOrNull {
uSession.getGroup(groupId)?.fetchGroupData()
uSession.groupService().getGroup(groupId)?.fetchGroupData()
}
}
}
@ -139,7 +141,7 @@ class AppStateHandler @Inject constructor(
}
private fun observeSyncStatus(session: Session) {
session.getSyncStatusLive()
session.syncStatusService().getSyncStatusLive()
.asFlow()
.filterIsInstance<SyncStatusService.Status.IncrementalSyncDone>()
.map { session.spaceService().getRootSpaceSummaries().size }

View File

@ -169,7 +169,7 @@ class AutoRageShaker @Inject constructor(
coroutineScope.launch {
try {
activeSessionHolder.getSafeActiveSession()?.sendToDevice(
activeSessionHolder.getSafeActiveSession()?.toDeviceService()?.sendToDevice(
eventType = AUTO_RS_REQUEST,
userId = target.senderUserId,
deviceId = target.senderDeviceId,
@ -261,7 +261,7 @@ class AutoRageShaker @Inject constructor(
this.currentActiveSessionId = sessionId
hasSynced = session.hasAlreadySynced()
session.getSyncStatusLive()
session.syncStatusService().getSyncStatusLive()
.asFlow()
.onEach {
hasSynced = it !is SyncStatusService.Status.InitialSyncProgressing
@ -269,11 +269,11 @@ class AutoRageShaker @Inject constructor(
.launchIn(session.coroutineScope)
activeSessionIds.add(sessionId)
session.addListener(this)
session.addEventStreamListener(detector)
session.eventStreamService().addEventStreamListener(detector)
}
override fun onSessionStopped(session: Session) {
session.removeEventStreamListener(detector)
session.eventStreamService().removeEventStreamListener(detector)
activeSessionIds.remove(session.sessionId)
}
}

View File

@ -30,11 +30,11 @@ import timber.log.Timber
fun Session.configureAndStart(context: Context, startSyncing: Boolean = true) {
Timber.i("Configure and start session for $myUserId")
open()
setFilter(FilterService.FilterPreset.ElementFilter)
filterService().setFilter(FilterService.FilterPreset.ElementFilter)
if (startSyncing) {
startSyncing(context)
}
refreshPushers()
pushersService().refreshPushers()
context.singletonEntryPoint().webRtcCallManager().checkForProtocolsSupportIfNeeded()
}
@ -75,7 +75,7 @@ fun Session.cannotLogoutSafely(): Boolean {
// has local cross signing keys
(cryptoService().crossSigningService().allPrivateKeysKnown() &&
// That are not backed up
!sharedSecretStorageService.isRecoverySetup())
!sharedSecretStorageService().isRecoverySetup())
}
fun Session.vectorStore(context: Context) = VectorSessionStore(context, myUserId)

View File

@ -37,7 +37,7 @@ class PushersManager @Inject constructor(
suspend fun testPush(pushKey: String) {
val currentSession = activeSessionHolder.getActiveSession()
currentSession.testPush(
currentSession.pushersService().testPush(
stringProvider.getString(R.string.pusher_http_url),
stringProvider.getString(R.string.pusher_app_id),
pushKey,
@ -47,12 +47,12 @@ class PushersManager @Inject constructor(
fun enqueueRegisterPusherWithFcmKey(pushKey: String): UUID {
val currentSession = activeSessionHolder.getActiveSession()
return currentSession.enqueueAddHttpPusher(createHttpPusher(pushKey))
return currentSession.pushersService().enqueueAddHttpPusher(createHttpPusher(pushKey))
}
suspend fun registerPusherWithFcmKey(pushKey: String) {
val currentSession = activeSessionHolder.getActiveSession()
currentSession.addHttpPusher(createHttpPusher(pushKey))
currentSession.pushersService().addHttpPusher(createHttpPusher(pushKey))
}
private fun createHttpPusher(pushKey: String) = PushersService.HttpPusher(
@ -70,7 +70,7 @@ class PushersManager @Inject constructor(
suspend fun registerEmailForPush(email: String) {
val currentSession = activeSessionHolder.getActiveSession()
val appName = appNameProvider.getAppName()
currentSession.addEmailPusher(
currentSession.pushersService().addEmailPusher(
email = email,
lang = localeProvider.current().language,
emailBranding = appName,
@ -81,12 +81,12 @@ class PushersManager @Inject constructor(
suspend fun unregisterEmailPusher(email: String) {
val currentSession = activeSessionHolder.getSafeActiveSession() ?: return
currentSession.removeEmailPusher(email)
currentSession.pushersService().removeEmailPusher(email)
}
suspend fun unregisterPusher(pushKey: String) {
val currentSession = activeSessionHolder.getSafeActiveSession() ?: return
currentSession.removeHttpPusher(pushKey, stringProvider.getString(R.string.pusher_app_id))
currentSession.pushersService().removeHttpPusher(pushKey, stringProvider.getString(R.string.pusher_app_id))
}
companion object {

View File

@ -160,7 +160,7 @@ class MainActivity : VectorBaseActivity<ActivityMainBinding>(), UnlockedActivity
args.clearCredentials -> {
lifecycleScope.launch {
try {
session.signOut(!args.isUserLoggedOut)
session.signOutService().signOut(!args.isUserLoggedOut)
} catch (failure: Throwable) {
displayError(failure)
return@launch

View File

@ -66,7 +66,7 @@ class AnalyticsAccountDataViewModel @AssistedInject constructor(
private fun observeInitSync() {
combine(
session.getSyncStatusLive().asFlow(),
session.syncStatusService().getSyncStatusLive().asFlow(),
analytics.getUserConsent(),
analytics.getAnalyticsId()
) { status, userConsent, analyticsId ->

View File

@ -58,7 +58,7 @@ class ReAuthViewModel @AssistedInject constructor(
is ReAuthActions.ReAuthWithPass -> {
val safeForIntentCypher = ByteArrayOutputStream().also {
it.use {
session.securelyStoreObject(action.password, initialState.resultKeyStoreAlias, it)
session.secureStorageService().securelyStoreObject(action.password, initialState.resultKeyStoreAlias, it)
}
}.toByteArray().toBase64NoPadding()
_viewEvents.post(ReAuthEvents.PasswordFinishSuccess(safeForIntentCypher))

View File

@ -55,7 +55,7 @@ class AutocompleteGroupPresenter @Inject constructor(context: Context,
QueryStringValue.Contains(query.toString(), QueryStringValue.Case.INSENSITIVE)
}
}
val groups = session.getGroupSummaries(queryParams)
val groups = session.groupService().getGroupSummaries(queryParams)
.asSequence()
.sortedBy { it.displayName }
controller.setData(groups.toList())

View File

@ -27,6 +27,7 @@ import im.vector.app.features.autocomplete.RecyclerViewPresenter
import org.matrix.android.sdk.api.query.QueryStringValue
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.events.model.Event
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.pushrules.SenderNotificationPermissionCondition
import org.matrix.android.sdk.api.session.room.members.RoomMemberQueryParams
import org.matrix.android.sdk.api.session.room.members.roomMemberQueryParams
@ -147,7 +148,7 @@ class AutocompleteMemberPresenter @AssistedInject constructor(context: Context,
AutocompleteMemberItem.Everyone(it)
}
private fun canNotifyEveryone() = session.resolveSenderNotificationPermissionCondition(
private fun canNotifyEveryone() = session.pushRuleService().resolveSenderNotificationPermissionCondition(
Event(
senderId = session.myUserId,
roomId = roomId

View File

@ -51,7 +51,7 @@ class AutocompleteRoomPresenter @Inject constructor(context: Context,
QueryStringValue.Contains(query.toString(), QueryStringValue.Case.INSENSITIVE)
}
}
val rooms = session.getRoomSummaries(queryParams)
val rooms = session.roomService().getRoomSummaries(queryParams)
.asSequence()
.sortedBy { it.displayName }
controller.setData(rooms.toList())

View File

@ -42,6 +42,7 @@ import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.call.CallState
import org.matrix.android.sdk.api.session.call.MxCall
import org.matrix.android.sdk.api.session.call.MxPeerConnectionState
import org.matrix.android.sdk.api.session.getRoomSummary
import org.matrix.android.sdk.api.session.room.model.call.supportCallTransfer
import org.matrix.android.sdk.api.util.MatrixItem

View File

@ -31,6 +31,7 @@ import org.jitsi.meet.sdk.JitsiMeetUserInfo
import org.matrix.android.sdk.api.extensions.tryOrNull
import org.matrix.android.sdk.api.raw.RawService
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.getRoomSummary
import org.matrix.android.sdk.api.session.widgets.model.Widget
import org.matrix.android.sdk.api.session.widgets.model.WidgetType
import org.matrix.android.sdk.api.util.MatrixJsonParser
@ -99,7 +100,7 @@ class JitsiService @Inject constructor(
}
suspend fun joinConference(roomId: String, jitsiWidget: Widget, enableVideo: Boolean): JitsiCallViewEvents.JoinConference {
val me = session.getRoomMember(session.myUserId, roomId)?.toMatrixItem()
val me = session.roomService().getRoomMember(session.myUserId, roomId)?.toMatrixItem()
val userDisplayName = me?.getBestName()
val userAvatar = me?.avatarUrl?.let { session.contentUrlResolver().resolveFullSize(it) }
val userInfo = JitsiMeetUserInfo().apply {

View File

@ -47,7 +47,7 @@ class DialPadLookup @Inject constructor(
if (nativeUserId == session.myUserId) {
throw Failure.NumberIsYours
}
session.getExistingDirectRoomWithUser(nativeUserId)
session.roomService().getExistingDirectRoomWithUser(nativeUserId)
// if there is not, just create a DM with the sip user
?: directRoomHelper.ensureDMExists(sipUserId)
} else {

View File

@ -20,6 +20,7 @@ import org.matrix.android.sdk.api.extensions.tryOrNull
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.events.model.toContent
import org.matrix.android.sdk.api.session.events.model.toModel
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.room.Room
import org.matrix.android.sdk.api.session.room.accountdata.RoomAccountDataTypes
import org.matrix.android.sdk.api.session.room.model.create.CreateRoomParams
@ -61,7 +62,7 @@ class CallUserMapper(private val session: Session, private val protocolsChecker:
val nativeLookup = session.sipNativeLookup(inviterId).firstOrNull() ?: return
if (nativeLookup.fields.containsKey("is_virtual")) {
val nativeUser = nativeLookup.userId
val nativeRoomId = session.getExistingDirectRoomWithUser(nativeUser)
val nativeRoomId = session.roomService().getExistingDirectRoomWithUser(nativeUser)
if (nativeRoomId != null) {
// It's a virtual room with a matching native room, so set the room account data. This
// will make sure we know where how to map calls and also allow us know not to display
@ -82,7 +83,7 @@ class CallUserMapper(private val session: Session, private val protocolsChecker:
}
private suspend fun ensureVirtualRoomExists(userId: String, nativeRoomId: String): String {
val existingDMRoom = tryOrNull { session.getExistingDirectRoomWithUser(userId) }
val existingDMRoom = tryOrNull { session.roomService().getExistingDirectRoomWithUser(userId) }
val roomId: String
if (existingDMRoom != null) {
roomId = existingDMRoom
@ -92,7 +93,7 @@ class CallUserMapper(private val session: Session, private val protocolsChecker:
setDirectMessage()
creationContent[RoomAccountDataTypes.EVENT_TYPE_VIRTUAL_ROOM] = nativeRoomId
}
roomId = session.createRoom(roomParams)
roomId = session.roomService().createRoom(roomParams)
}
return roomId
}

View File

@ -989,7 +989,7 @@ class WebRtcCall(
val nativeUserId = session.sipNativeLookup(newAssertedIdentity.id!!).firstOrNull()?.userId
if (nativeUserId != null) {
val resolvedUser = tryOrNull {
session.resolveUser(nativeUserId)
session.userService().resolveUser(nativeUserId)
}
if (resolvedUser != null) {
remoteAssertedIdentity = newAssertedIdentity.copy(

View File

@ -18,6 +18,7 @@ package im.vector.app.features.call.webrtc
import org.matrix.android.sdk.api.extensions.orFalse
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.util.MatrixItem
import org.matrix.android.sdk.api.util.toMatrixItem

View File

@ -36,6 +36,7 @@ import kotlinx.coroutines.launch
import org.matrix.android.sdk.api.extensions.orFalse
import org.matrix.android.sdk.api.raw.RawService
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.getUser
import org.matrix.android.sdk.api.session.permalinks.PermalinkData
import org.matrix.android.sdk.api.session.permalinks.PermalinkParser
import org.matrix.android.sdk.api.session.room.model.create.CreateRoomParams
@ -74,7 +75,11 @@ class CreateDirectRoomViewModel @AssistedInject constructor(
_viewEvents.post(CreateDirectRoomViewEvents.DmSelf)
} else {
// Try to get user from known users and fall back to creating a User object from MXID
val qrInvitee = if (session.getUser(mxid) != null) session.getUser(mxid)!! else User(mxid, null, null)
val qrInvitee = if (session.getUser(mxid) != null) {
session.getUser(mxid)!!
} else {
User(mxid, null, null)
}
onSubmitInvitees(setOf(PendingSelection.UserPendingSelection(qrInvitee)))
}
}
@ -85,7 +90,7 @@ class CreateDirectRoomViewModel @AssistedInject constructor(
*/
private fun onSubmitInvitees(selections: Set<PendingSelection>) {
val existingRoomId = selections.singleOrNull()?.getMxId()?.let { userId ->
session.getExistingDirectRoomWithUser(userId)
session.roomService().getExistingDirectRoomWithUser(userId)
}
if (existingRoomId != null) {
// Do not create a new DM, just tell that the creation is successful by passing the existing roomId
@ -119,7 +124,7 @@ class CreateDirectRoomViewModel @AssistedInject constructor(
}
val result = runCatchingToAsync {
session.createRoom(roomParams)
session.roomService().createRoom(roomParams)
}
analyticsTracker.capture(CreatedRoom(isDM = roomParams.isDirect.orFalse()))

View File

@ -34,7 +34,7 @@ class DirectRoomHelper @Inject constructor(
) {
suspend fun ensureDMExists(userId: String): String {
val existingRoomId = tryOrNull { session.getExistingDirectRoomWithUser(userId) }
val existingRoomId = tryOrNull { session.roomService().getExistingDirectRoomWithUser(userId) }
val roomId: String
if (existingRoomId != null) {
roomId = existingRoomId
@ -48,7 +48,7 @@ class DirectRoomHelper @Inject constructor(
setDirectMessage()
enableEncryptionIfInvitedUsersSupportIt = adminE2EByDefault
}
roomId = session.createRoom(roomParams)
roomId = session.roomService().createRoom(roomParams)
analyticsTracker.capture(CreatedRoom(isDM = roomParams.isDirect.orFalse()))
}
return roomId

View File

@ -170,7 +170,7 @@ class KeysBackupRestoreSharedViewModel @Inject constructor(
fun handleGotSecretFromSSSS(cipherData: String, alias: String) {
try {
cipherData.fromBase64().inputStream().use { ins ->
val res = session.loadSecureSecret<Map<String, String>>(ins, alias)
val res = session.secureStorageService().loadSecureSecret<Map<String, String>>(ins, alias)
val secret = res?.get(KEYBACKUP_SECRET_SSSS_NAME)
if (secret == null) {
_navigateEvent.postValue(
@ -252,7 +252,7 @@ class KeysBackupRestoreSharedViewModel @Inject constructor(
?: return false
// Some sanity ?
val defaultKeyResult = session.sharedSecretStorageService.getDefaultKey()
val defaultKeyResult = session.sharedSecretStorageService().getDefaultKey()
val keyInfo = (defaultKeyResult as? KeyInfoResult.Success)?.keyInfo
?: return false

View File

@ -87,7 +87,7 @@ class SharedSecureStorageViewModel @AssistedInject constructor(
setState {
copy(userId = session.myUserId)
}
val integrityResult = session.sharedSecretStorageService.checkShouldBeAbleToAccessSecrets(initialState.requestedSecrets, initialState.keyId)
val integrityResult = session.sharedSecretStorageService().checkShouldBeAbleToAccessSecrets(initialState.requestedSecrets, initialState.keyId)
if (integrityResult !is IntegrityResult.Success) {
_viewEvents.post(
SharedSecureStorageViewEvent.Error(
@ -96,8 +96,8 @@ class SharedSecureStorageViewModel @AssistedInject constructor(
)
)
}
val keyResult = initialState.keyId?.let { session.sharedSecretStorageService.getKey(it) }
?: session.sharedSecretStorageService.getDefaultKey()
val keyResult = initialState.keyId?.let { session.sharedSecretStorageService().getKey(it) }
?: session.sharedSecretStorageService().getDefaultKey()
if (!keyResult.isSuccess()) {
_viewEvents.post(SharedSecureStorageViewEvent.Dismiss)
@ -205,7 +205,7 @@ class SharedSecureStorageViewModel @AssistedInject constructor(
viewModelScope.launch(Dispatchers.IO) {
runCatching {
val recoveryKey = action.recoveryKey
val keyInfoResult = session.sharedSecretStorageService.getDefaultKey()
val keyInfoResult = session.sharedSecretStorageService().getDefaultKey()
if (!keyInfoResult.isSuccess()) {
_viewEvents.post(SharedSecureStorageViewEvent.HideModalLoading)
_viewEvents.post(SharedSecureStorageViewEvent.Error(stringProvider.getString(R.string.failed_to_access_secure_storage)))
@ -228,7 +228,7 @@ class SharedSecureStorageViewModel @AssistedInject constructor(
withContext(Dispatchers.IO) {
initialState.requestedSecrets.forEach {
if (session.accountDataService().getUserAccountDataEvent(it) != null) {
val res = session.sharedSecretStorageService.getSecret(
val res = session.sharedSecretStorageService().getSecret(
name = it,
keyId = keyInfo.id,
secretKey = keySpec)
@ -243,7 +243,7 @@ class SharedSecureStorageViewModel @AssistedInject constructor(
_viewEvents.post(SharedSecureStorageViewEvent.HideModalLoading)
val safeForIntentCypher = ByteArrayOutputStream().also {
it.use {
session.securelyStoreObject(decryptedSecretMap as Map<String, String>, initialState.resultKeyStoreAlias, it)
session.secureStorageService().securelyStoreObject(decryptedSecretMap as Map<String, String>, initialState.resultKeyStoreAlias, it)
}
}.toByteArray().toBase64NoPadding()
_viewEvents.post(SharedSecureStorageViewEvent.FinishSuccess(safeForIntentCypher))
@ -262,7 +262,7 @@ class SharedSecureStorageViewModel @AssistedInject constructor(
viewModelScope.launch(Dispatchers.IO) {
runCatching {
val passphrase = action.passphrase
val keyInfoResult = session.sharedSecretStorageService.getDefaultKey()
val keyInfoResult = session.sharedSecretStorageService().getDefaultKey()
if (!keyInfoResult.isSuccess()) {
_viewEvents.post(SharedSecureStorageViewEvent.HideModalLoading)
_viewEvents.post(SharedSecureStorageViewEvent.Error("Cannot find ssss key"))
@ -297,7 +297,7 @@ class SharedSecureStorageViewModel @AssistedInject constructor(
withContext(Dispatchers.IO) {
initialState.requestedSecrets.forEach {
if (session.accountDataService().getUserAccountDataEvent(it) != null) {
val res = session.sharedSecretStorageService.getSecret(
val res = session.sharedSecretStorageService().getSecret(
name = it,
keyId = keyInfo.id,
secretKey = keySpec)
@ -312,7 +312,7 @@ class SharedSecureStorageViewModel @AssistedInject constructor(
_viewEvents.post(SharedSecureStorageViewEvent.HideModalLoading)
val safeForIntentCypher = ByteArrayOutputStream().also {
it.use {
session.securelyStoreObject(decryptedSecretMap as Map<String, String>, initialState.resultKeyStoreAlias, it)
session.secureStorageService().securelyStoreObject(decryptedSecretMap as Map<String, String>, initialState.resultKeyStoreAlias, it)
}
}.toByteArray().toBase64NoPadding()
_viewEvents.post(SharedSecureStorageViewEvent.FinishSuccess(safeForIntentCypher))

View File

@ -61,7 +61,7 @@ class BackupToQuadSMigrationTask @Inject constructor(
// We need to use the current secret for keybackup and use it as the new master key for SSSS
// Then we need to put back the backup key in sss
val keysBackupService = session.cryptoService().keysBackupService()
val quadS = session.sharedSecretStorageService
val quadS = session.sharedSecretStorageService()
val version = keysBackupService.keysBackupVersion ?: return Result.NoKeyBackupVersion

View File

@ -117,7 +117,7 @@ class BootstrapCrossSigningTask @Inject constructor(
val keyInfo: SsssKeyCreationInfo
val ssssService = session.sharedSecretStorageService
val ssssService = session.sharedSecretStorageService()
params.progressListener?.onProgress(
WaitingViewData(

View File

@ -246,7 +246,8 @@ class BootstrapSharedViewModel @AssistedInject constructor(
uiaContinuation?.resume(DefaultBaseAuth(session = pendingAuth?.session ?: ""))
}
is BootstrapActions.PasswordAuthDone -> {
val decryptedPass = session.loadSecureSecret<String>(action.password.fromBase64().inputStream(), ReAuthActivity.DEFAULT_RESULT_KEYSTORE_ALIAS)
val decryptedPass = session.secureStorageService()
.loadSecureSecret<String>(action.password.fromBase64().inputStream(), ReAuthActivity.DEFAULT_RESULT_KEYSTORE_ALIAS)
uiaContinuation?.resume(
UserPasswordAuth(
session = pendingAuth?.session,

View File

@ -63,7 +63,7 @@ class IncomingVerificationRequestHandler @Inject constructor(
when (tx.state) {
is VerificationTxState.OnStarted -> {
// Add a notification for every incoming request
val user = session?.getUser(tx.otherUserId)
val user = session?.userService()?.getUser(tx.otherUserId)
val name = user?.toMatrixItem()?.getBestName() ?: tx.otherUserId
val alert = VerificationVectorAlert(
uid,
@ -127,7 +127,7 @@ class IncomingVerificationRequestHandler @Inject constructor(
// XXX this is a bit hard coded :/
popupAlertManager.cancelAlert("review_login")
}
val user = session?.getUser(pr.otherUserId)?.toMatrixItem()
val user = session?.userService()?.getUser(pr.otherUserId)?.toMatrixItem()
val name = user?.getBestName() ?: pr.otherUserId
val description = if (name == pr.otherUserId) {
name

View File

@ -53,6 +53,7 @@ import org.matrix.android.sdk.api.session.crypto.verification.VerificationServic
import org.matrix.android.sdk.api.session.crypto.verification.VerificationTransaction
import org.matrix.android.sdk.api.session.crypto.verification.VerificationTxState
import org.matrix.android.sdk.api.session.events.model.LocalEcho
import org.matrix.android.sdk.api.session.getUser
import org.matrix.android.sdk.api.util.MatrixItem
import org.matrix.android.sdk.api.util.awaitCallback
import org.matrix.android.sdk.api.util.fromBase64
@ -149,7 +150,7 @@ class VerificationBottomSheetViewModel @AssistedInject constructor(
pendingRequest = if (pr != null) Success(pr) else Uninitialized,
isMe = initialState.otherUserId == session.myUserId,
currentDeviceCanCrossSign = session.cryptoService().crossSigningService().canCrossSign(),
quadSContainsSecrets = session.sharedSecretStorageService.isRecoverySetup(),
quadSContainsSecrets = session.sharedSecretStorageService().isRecoverySetup(),
hasAnyOtherSession = hasAnyOtherSession
)
}
@ -231,7 +232,7 @@ class VerificationBottomSheetViewModel @AssistedInject constructor(
override fun handle(action: VerificationAction) = withState { state ->
val otherUserId = state.otherUserMxItem?.id ?: return@withState
val roomId = state.roomId
?: session.getExistingDirectRoomWithUser(otherUserId)
?: session.roomService().getExistingDirectRoomWithUser(otherUserId)
when (action) {
is VerificationAction.RequestVerificationByDM -> {
@ -244,7 +245,7 @@ class VerificationBottomSheetViewModel @AssistedInject constructor(
)
}
viewModelScope.launch {
val result = runCatching { session.createDirectRoom(otherUserId) }
val result = runCatching { session.roomService().createDirectRoom(otherUserId) }
result.fold(
{ data ->
setState {
@ -372,7 +373,7 @@ class VerificationBottomSheetViewModel @AssistedInject constructor(
viewModelScope.launch(Dispatchers.IO) {
try {
action.cypherData.fromBase64().inputStream().use { ins ->
val res = session.loadSecureSecret<Map<String, String>>(ins, action.alias)
val res = session.secureStorageService().loadSecureSecret<Map<String, String>>(ins, action.alias)
val trustResult = session.cryptoService().crossSigningService().checkTrustFromPrivateKeys(
res?.get(MASTER_KEY_SSSS_NAME),
res?.get(USER_SIGNING_KEY_SSSS_NAME),

View File

@ -40,6 +40,7 @@ import org.matrix.android.sdk.api.session.crypto.verification.SasVerificationTra
import org.matrix.android.sdk.api.session.crypto.verification.VerificationService
import org.matrix.android.sdk.api.session.crypto.verification.VerificationTransaction
import org.matrix.android.sdk.api.session.crypto.verification.VerificationTxState
import org.matrix.android.sdk.api.session.getUser
import org.matrix.android.sdk.api.util.MatrixItem
import org.matrix.android.sdk.api.util.toMatrixItem

View File

@ -36,6 +36,7 @@ import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.events.model.Event
import org.matrix.android.sdk.api.session.events.model.EventType
import org.matrix.android.sdk.api.session.events.model.toModel
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.room.model.message.MessageContent
import org.matrix.android.sdk.api.util.JsonDict
import org.matrix.android.sdk.api.util.MatrixJsonParser

View File

@ -290,7 +290,7 @@ class DiscoverySettingsViewModel @AssistedInject constructor(
}
private fun retrieveBinding() {
retrieveBinding(session.getThreePids())
retrieveBinding(session.profileService().getThreePids())
}
private fun retrieveBinding(threePids: List<ThreePid>) = withState { state ->

View File

@ -24,7 +24,7 @@ import org.matrix.android.sdk.api.session.terms.TermsService
suspend fun Session.fetchIdentityServerWithTerms(userLanguage: String): ServerAndPolicies? {
return identityService().getCurrentIdentityServerUrl()
?.let { identityServerUrl ->
val termsResponse = getTerms(TermsService.ServiceType.IdentityService, identityServerUrl.ensureProtocol())
val termsResponse = termsService().getTerms(TermsService.ServiceType.IdentityService, identityServerUrl.ensureProtocol())
.serverResponse
buildServerAndPolicies(identityServerUrl, termsResponse, userLanguage)
}
@ -32,7 +32,7 @@ suspend fun Session.fetchIdentityServerWithTerms(userLanguage: String): ServerAn
suspend fun Session.fetchHomeserverWithTerms(userLanguage: String): ServerAndPolicies {
val homeserverUrl = sessionParams.homeServerUrl
val terms = getHomeserverTerms(homeserverUrl.ensureProtocol())
val terms = termsService().getHomeserverTerms(homeserverUrl.ensureProtocol())
return buildServerAndPolicies(homeserverUrl, terms, userLanguage)
}

View File

@ -107,7 +107,7 @@ class SetIdentityServerViewModel @AssistedInject constructor(
private suspend fun checkTerms(baseUrl: String) {
try {
val data = mxSession.getTerms(TermsService.ServiceType.IdentityService, baseUrl)
val data = mxSession.termsService().getTerms(TermsService.ServiceType.IdentityService, baseUrl)
// has all been accepted?
val resp = data.serverResponse

View File

@ -44,6 +44,7 @@ import org.matrix.android.sdk.api.auth.registration.nextUncompletedStage
import org.matrix.android.sdk.api.extensions.tryOrNull
import org.matrix.android.sdk.api.session.crypto.model.CryptoDeviceInfo
import org.matrix.android.sdk.api.session.crypto.model.MXUsersDevicesMap
import org.matrix.android.sdk.api.session.getUser
import org.matrix.android.sdk.api.session.initsync.SyncStatusService
import org.matrix.android.sdk.api.session.pushrules.RuleIds
import org.matrix.android.sdk.api.session.room.model.Membership
@ -175,7 +176,7 @@ class HomeActivityViewModel @AssistedInject constructor(
private fun observeInitialSync() {
val session = activeSessionHolder.getSafeActiveSession() ?: return
session.getSyncStatusLive()
session.syncStatusService().getSyncStatusLive()
.asFlow()
.onEach { status ->
when (status) {
@ -215,13 +216,16 @@ class HomeActivityViewModel @AssistedInject constructor(
if (!vectorPreferences.areNotificationEnabledForDevice()) {
// Check if set at account level
val mRuleMaster = activeSessionHolder.getSafeActiveSession()
?.pushRuleService()
?.getPushRules()
?.getAllRules()
?.find { it.ruleId == RuleIds.RULE_ID_DISABLE_ALL }
if (mRuleMaster?.enabled == false) {
// So push are enabled at account level but not for this session
// Let's check that there are some rooms?
val knownRooms = activeSessionHolder.getSafeActiveSession()?.getRoomSummaries(roomSummaryQueryParams {
val knownRooms = activeSessionHolder.getSafeActiveSession()
?.roomService()
?.getRoomSummaries(roomSummaryQueryParams {
memberships = Membership.activeMemberships()
})?.size ?: 0

View File

@ -91,7 +91,7 @@ class HomeDetailViewModel @AssistedInject constructor(
private val refreshRoomSummariesOnCryptoSessionChange = object : NewSessionListener {
override fun onNewSession(roomId: String?, senderKey: String, sessionId: String) {
session.refreshJoinedRoomSummaryPreviews(roomId)
session.roomService().refreshJoinedRoomSummaryPreviews(roomId)
}
}
@ -176,7 +176,7 @@ class HomeDetailViewModel @AssistedInject constructor(
private fun handleMarkAllRoomsRead() = withState { _ ->
// questionable to use viewmodelscope
viewModelScope.launch(Dispatchers.Default) {
val roomIds = session.getRoomSummaries(
val roomIds = session.roomService().getRoomSummaries(
roomSummaryQueryParams {
memberships = listOf(Membership.JOIN)
roomCategoryFilter = RoomCategoryFilter.ONLY_WITH_NOTIFICATIONS
@ -184,7 +184,7 @@ class HomeDetailViewModel @AssistedInject constructor(
)
.map { it.roomId }
try {
session.markAllAsRead(roomIds)
session.roomService().markAllAsRead(roomIds)
} catch (failure: Throwable) {
Timber.d(failure, "Failed to mark all as read")
}
@ -198,7 +198,7 @@ class HomeDetailViewModel @AssistedInject constructor(
copy(syncState = syncState)
}
session.getSyncStatusLive()
session.syncStatusService().getSyncStatusLive()
.asFlow()
.filterIsInstance<SyncStatusService.Status.IncrementalSyncStatus>()
.setOnEach {
@ -219,7 +219,7 @@ class HomeDetailViewModel @AssistedInject constructor(
appStateHandler.selectedRoomGroupingFlow.distinctUntilChanged().flatMapLatest {
// we use it as a trigger to all changes in room, but do not really load
// the actual models
session.getPagedRoomSummariesLive(
session.roomService().getPagedRoomSummariesLive(
roomSummaryQueryParams {
memberships = Membership.activeMemberships()
},
@ -237,7 +237,7 @@ class HomeDetailViewModel @AssistedInject constructor(
var dmInvites = 0
var roomsInvite = 0
if (autoAcceptInvites.showInvites()) {
dmInvites = session.getRoomSummaries(
dmInvites = session.roomService().getRoomSummaries(
roomSummaryQueryParams {
memberships = listOf(Membership.INVITE)
roomCategoryFilter = RoomCategoryFilter.ONLY_DM
@ -245,7 +245,7 @@ class HomeDetailViewModel @AssistedInject constructor(
}
).size
roomsInvite = session.getRoomSummaries(
roomsInvite = session.roomService().getRoomSummaries(
roomSummaryQueryParams {
memberships = listOf(Membership.INVITE)
roomCategoryFilter = RoomCategoryFilter.ONLY_ROOMS
@ -254,7 +254,7 @@ class HomeDetailViewModel @AssistedInject constructor(
).size
}
val dmRooms = session.getNotificationCountForRooms(
val dmRooms = session.roomService().getNotificationCountForRooms(
roomSummaryQueryParams {
memberships = listOf(Membership.JOIN)
roomCategoryFilter = RoomCategoryFilter.ONLY_DM
@ -262,7 +262,7 @@ class HomeDetailViewModel @AssistedInject constructor(
}
)
val otherRooms = session.getNotificationCountForRooms(
val otherRooms = session.roomService().getNotificationCountForRooms(
roomSummaryQueryParams {
memberships = listOf(Membership.JOIN)
roomCategoryFilter = RoomCategoryFilter.ONLY_ROOMS

View File

@ -60,7 +60,7 @@ class HomeDrawerFragment @Inject constructor(
if (savedInstanceState == null) {
replaceChildFragment(R.id.homeDrawerGroupListContainer, SpaceListFragment::class.java)
}
session.getUserLive(session.myUserId).observeK(viewLifecycleOwner) { optionalUser ->
session.userService().getUserLive(session.myUserId).observeK(viewLifecycleOwner) { optionalUser ->
val user = optionalUser?.getOrNull()
if (user != null) {
avatarRenderer.render(user.toMatrixItem(), views.homeDrawerHeaderAvatarView)

View File

@ -39,6 +39,7 @@ import org.matrix.android.sdk.api.NoOpMatrixCallback
import org.matrix.android.sdk.api.extensions.orFalse
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.crypto.model.DeviceInfo
import org.matrix.android.sdk.api.session.getUser
import org.matrix.android.sdk.api.util.MatrixItem
import org.matrix.android.sdk.api.util.toMatrixItem
import org.matrix.android.sdk.flow.flow

View File

@ -71,9 +71,11 @@ class UnreadMessagesSharedViewModel @AssistedInject constructor(@Assisted initia
override fun handle(action: EmptyAction) {}
private val roomService = session.roomService()
init {
session.getPagedRoomSummariesLive(
roomService.getPagedRoomSummariesLive(
roomSummaryQueryParams {
this.memberships = listOf(Membership.JOIN)
this.activeSpaceFilter = ActiveSpaceFilter.ActiveSpace(null)
@ -81,7 +83,7 @@ class UnreadMessagesSharedViewModel @AssistedInject constructor(@Assisted initia
).asFlow()
.throttleFirst(300)
.execute {
val counts = session.getNotificationCountForRooms(
val counts = roomService.getNotificationCountForRooms(
roomSummaryQueryParams {
this.memberships = listOf(Membership.JOIN)
this.activeSpaceFilter = ActiveSpaceFilter.ActiveSpace(null)
@ -90,7 +92,7 @@ class UnreadMessagesSharedViewModel @AssistedInject constructor(@Assisted initia
val invites = if (autoAcceptInvites.hideInvites) {
0
} else {
session.getRoomSummaries(
roomService.getRoomSummaries(
roomSummaryQueryParams {
this.memberships = listOf(Membership.INVITE)
this.activeSpaceFilter = ActiveSpaceFilter.ActiveSpace(null)
@ -109,7 +111,7 @@ class UnreadMessagesSharedViewModel @AssistedInject constructor(@Assisted initia
combine(
appStateHandler.selectedRoomGroupingFlow.distinctUntilChanged(),
appStateHandler.selectedRoomGroupingFlow.flatMapLatest {
session.getPagedRoomSummariesLive(
roomService.getPagedRoomSummariesLive(
roomSummaryQueryParams {
this.memberships = Membership.activeMemberships()
}, sortOrder = RoomSortOrder.NONE
@ -131,7 +133,7 @@ class UnreadMessagesSharedViewModel @AssistedInject constructor(@Assisted initia
val inviteCount = if (autoAcceptInvites.hideInvites) {
0
} else {
session.getRoomSummaries(
roomService.getRoomSummaries(
roomSummaryQueryParams { this.memberships = listOf(Membership.INVITE) }
).size
}
@ -139,14 +141,14 @@ class UnreadMessagesSharedViewModel @AssistedInject constructor(@Assisted initia
val spaceInviteCount = if (autoAcceptInvites.hideInvites) {
0
} else {
session.getRoomSummaries(
roomService.getRoomSummaries(
spaceSummaryQueryParams {
this.memberships = listOf(Membership.INVITE)
}
).size
}
val totalCount = session.getNotificationCountForRooms(
val totalCount = roomService.getNotificationCountForRooms(
roomSummaryQueryParams {
this.memberships = listOf(Membership.JOIN)
this.activeSpaceFilter = ActiveSpaceFilter.ActiveSpace(null).takeIf {

View File

@ -86,6 +86,7 @@ import org.matrix.android.sdk.api.session.events.model.isTextMessage
import org.matrix.android.sdk.api.session.events.model.toContent
import org.matrix.android.sdk.api.session.events.model.toModel
import org.matrix.android.sdk.api.session.file.FileService
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.initsync.SyncStatusService
import org.matrix.android.sdk.api.session.room.members.ChangeMembershipState
import org.matrix.android.sdk.api.session.room.members.roomMemberQueryParams
@ -185,7 +186,7 @@ class TimelineViewModel @AssistedInject constructor(
}
// Inform the SDK that the room is displayed
viewModelScope.launch(Dispatchers.IO) {
tryOrNull { session.onRoomDisplayed(initialState.roomId) }
tryOrNull { session.roomService().onRoomDisplayed(initialState.roomId) }
}
callManager.addProtocolsCheckerListener(this)
callManager.checkForProtocolsSupportIfNeeded()
@ -682,7 +683,7 @@ class TimelineViewModel @AssistedInject constructor(
}
viewModelScope.launch {
val result = runCatchingToAsync {
session.joinRoom(roomId, viaServers = viaServers)
session.roomService().joinRoom(roomId, viaServers = viaServers)
roomId
}
setState {
@ -808,7 +809,7 @@ class TimelineViewModel @AssistedInject constructor(
notificationDrawerManager.updateEvents { it.clearMemberShipNotificationForRoom(initialState.roomId) }
viewModelScope.launch {
try {
session.leaveRoom(room.roomId)
session.roomService().leaveRoom(room.roomId)
} catch (throwable: Throwable) {
_viewEvents.post(RoomDetailViewEvents.Failure(throwable, showInDialog = true))
}
@ -819,7 +820,7 @@ class TimelineViewModel @AssistedInject constructor(
notificationDrawerManager.updateEvents { it.clearMemberShipNotificationForRoom(initialState.roomId) }
viewModelScope.launch {
try {
session.joinRoom(room.roomId)
session.roomService().joinRoom(room.roomId)
analyticsTracker.capture(room.roomSummary().toAnalyticsJoinedRoom())
} catch (throwable: Throwable) {
_viewEvents.post(RoomDetailViewEvents.Failure(throwable, showInDialog = true))
@ -996,7 +997,7 @@ class TimelineViewModel @AssistedInject constructor(
viewModelScope.launch {
val event = try {
session.ignoreUserIds(listOf(action.userId))
session.userService().ignoreUserIds(listOf(action.userId))
RoomDetailViewEvents.ActionSuccess(action)
} catch (failure: Throwable) {
RoomDetailViewEvents.ActionFailure(action, failure)
@ -1086,7 +1087,7 @@ class TimelineViewModel @AssistedInject constructor(
copy(syncState = syncState)
}
session.getSyncStatusLive()
session.syncStatusService().getSyncStatusLive()
.asFlow()
.filterIsInstance<SyncStatusService.Status.IncrementalSyncStatus>()
.setOnEach {
@ -1190,7 +1191,7 @@ class TimelineViewModel @AssistedInject constructor(
}
if (summary.membership == Membership.INVITE) {
summary.inviterId?.let { inviterId ->
session.getRoomMember(inviterId, summary.roomId)
session.roomService().getRoomMember(inviterId, summary.roomId)
}?.also {
setState { copy(asyncInviter = Success(it)) }
}

View File

@ -50,6 +50,8 @@ import org.matrix.android.sdk.api.session.events.model.getRootThreadEventId
import org.matrix.android.sdk.api.session.events.model.isThread
import org.matrix.android.sdk.api.session.events.model.toContent
import org.matrix.android.sdk.api.session.events.model.toModel
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.getRoomSummary
import org.matrix.android.sdk.api.session.room.model.PowerLevelsContent
import org.matrix.android.sdk.api.session.room.model.RoomAvatarContent
import org.matrix.android.sdk.api.session.room.model.RoomEncryptionAlgorithm
@ -445,7 +447,7 @@ class MessageComposerViewModel @AssistedInject constructor(
is ParsedCommand.LeaveRoom -> {
viewModelScope.launch(Dispatchers.IO) {
try {
session.leaveRoom(parsedCommand.roomId)
session.roomService().leaveRoom(parsedCommand.roomId)
popDraft()
_viewEvents.post(MessageComposerViewEvents.SlashCommandResultOk(parsedCommand))
} catch (failure: Throwable) {
@ -609,7 +611,7 @@ class MessageComposerViewModel @AssistedInject constructor(
private fun handleJoinToAnotherRoomSlashCommand(command: ParsedCommand.JoinRoom) {
viewModelScope.launch {
try {
session.joinRoom(command.roomAlias, command.reason, emptyList())
session.roomService().joinRoom(command.roomAlias, command.reason, emptyList())
} catch (failure: Throwable) {
_viewEvents.post(MessageComposerViewEvents.SlashCommandResultError(failure))
return@launch
@ -676,7 +678,7 @@ class MessageComposerViewModel @AssistedInject constructor(
private fun handleChangeDisplayNameSlashCommand(changeDisplayName: ParsedCommand.ChangeDisplayName) {
launchSlashCommandFlowSuspendable(changeDisplayName) {
session.setDisplayName(session.myUserId, changeDisplayName.displayName)
session.profileService().setDisplayName(session.myUserId, changeDisplayName.displayName)
}
}
@ -691,7 +693,7 @@ class MessageComposerViewModel @AssistedInject constructor(
?.let { session.getRoom(it) }
}
?.let {
session.leaveRoom(it.roomId)
session.roomService().leaveRoom(it.roomId)
}
}
}
@ -756,7 +758,7 @@ class MessageComposerViewModel @AssistedInject constructor(
private fun handleIgnoreSlashCommand(ignore: ParsedCommand.IgnoreUser) {
launchSlashCommandFlowSuspendable(ignore) {
session.ignoreUserIds(listOf(ignore.userId))
session.userService().ignoreUserIds(listOf(ignore.userId))
}
}
@ -773,7 +775,7 @@ class MessageComposerViewModel @AssistedInject constructor(
private fun handleUnignoreSlashCommandConfirmed(unignore: ParsedCommand.UnignoreUser) {
launchSlashCommandFlowSuspendable(unignore) {
session.unIgnoreUserIds(listOf(unignore.userId))
session.userService().unIgnoreUserIds(listOf(unignore.userId))
}
}

View File

@ -125,7 +125,7 @@ class SearchResultController @Inject constructor(
.formattedDate(dateFormatter.format(event.originServerTs, DateFormatKind.MESSAGE_SIMPLE))
.spannable(spannable.toEpoxyCharSequence())
.sender(eventAndSender.sender
?: eventAndSender.event.senderId?.let { session.getRoomMember(it, data.roomId) }?.toMatrixItem())
?: eventAndSender.event.senderId?.let { session.roomService().getRoomMember(it, data.roomId) }?.toMatrixItem())
.threadDetails(event.threadDetails)
.threadSummaryFormatted(displayableEventFormatter.formatThreadSummary(event.threadDetails?.threadSummaryLatestEvent).toString())
.areThreadMessagesEnabled(userPreferencesProvider.areThreadMessagesEnabled())

View File

@ -30,6 +30,7 @@ import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.search.SearchResult
class SearchViewModel @AssistedInject constructor(

View File

@ -48,6 +48,7 @@ import org.matrix.android.sdk.api.session.events.model.isAttachmentMessage
import org.matrix.android.sdk.api.session.events.model.isTextMessage
import org.matrix.android.sdk.api.session.events.model.isThread
import org.matrix.android.sdk.api.session.events.model.toModel
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.room.model.message.MessageContent
import org.matrix.android.sdk.api.session.room.model.message.MessageFormat
import org.matrix.android.sdk.api.session.room.model.message.MessagePollContent
@ -454,7 +455,7 @@ class MessageActionsViewModel @AssistedInject constructor(
// if (!vectorPreferences.areThreadMessagesEnabled()) return false
// Disable beta prompt if the homeserver do not support threads
if (!vectorPreferences.areThreadMessagesEnabled() &&
!session.getHomeServerCapabilities().canUseThreading) return false
!session.homeServerCapabilitiesService().getHomeServerCapabilities().canUseThreading) return false
if (initialState.isFromThreadTimeline) return false
if (event.root.isThread()) return false

View File

@ -32,6 +32,7 @@ import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.crypto.MXCryptoError
import org.matrix.android.sdk.api.session.crypto.model.OlmDecryptionResult
import org.matrix.android.sdk.api.session.events.model.isReply
import org.matrix.android.sdk.api.session.getRoom
import timber.log.Timber
import java.util.UUID

View File

@ -29,6 +29,7 @@ import org.matrix.android.sdk.api.extensions.orFalse
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.events.model.content.EncryptionEventContent
import org.matrix.android.sdk.api.session.events.model.toModel
import org.matrix.android.sdk.api.session.getRoomSummary
import javax.inject.Inject
class EncryptionItemFactory @Inject constructor(

View File

@ -38,6 +38,7 @@ import org.matrix.android.sdk.api.query.QueryStringValue
import org.matrix.android.sdk.api.session.events.model.EventType
import org.matrix.android.sdk.api.session.events.model.content.EncryptionEventContent
import org.matrix.android.sdk.api.session.events.model.toModel
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.room.model.PowerLevelsContent
import org.matrix.android.sdk.api.session.room.model.create.RoomCreateContent
import org.matrix.android.sdk.api.session.room.powerlevels.PowerLevelsHelper

View File

@ -436,7 +436,7 @@ class MessageItemFactory @Inject constructor(
val otherUserId = if (informationData.sentByMe) messageContent.toUserId else informationData.senderId
val otherUserName = if (informationData.sentByMe) {
session.getRoomMember(messageContent.toUserId, roomId)?.displayName
session.roomService().getRoomMember(messageContent.toUserId, roomId)?.displayName
} else {
informationData.memberName
}

View File

@ -22,6 +22,7 @@ import im.vector.app.features.home.room.detail.timeline.merged.MergedTimelines
import kotlinx.coroutines.CoroutineScope
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.events.model.EventType
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.room.Room
import org.matrix.android.sdk.api.session.room.timeline.Timeline
import javax.inject.Inject

View File

@ -32,6 +32,7 @@ import org.matrix.android.sdk.api.session.crypto.verification.safeValueOf
import org.matrix.android.sdk.api.session.events.model.EventType
import org.matrix.android.sdk.api.session.events.model.RelationType
import org.matrix.android.sdk.api.session.events.model.toModel
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.room.model.message.MessageRelationContent
import org.matrix.android.sdk.api.session.room.model.message.MessageVerificationCancelContent
import javax.inject.Inject

View File

@ -29,6 +29,7 @@ import im.vector.app.core.di.ActiveSessionHolder
import im.vector.app.core.glide.GlideApp
import im.vector.app.core.utils.DimensionConverter
import im.vector.app.features.home.AvatarRenderer
import org.matrix.android.sdk.api.session.getUser
import org.matrix.android.sdk.api.util.toMatrixItem
import timber.log.Timber
import javax.inject.Inject

View File

@ -33,6 +33,7 @@ import im.vector.app.core.platform.VectorViewModel
import im.vector.app.features.home.room.detail.timeline.action.TimelineEventFragmentArgs
import kotlinx.coroutines.flow.map
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.flow.flow
import org.matrix.android.sdk.flow.unwrap

View File

@ -62,7 +62,7 @@ class EventTextRenderer @AssistedInject constructor(@Assisted private val roomId
* ========================================================================================== */
private fun addNotifyEveryoneSpans(text: Spannable, roomId: String) {
val room: RoomSummary? = sessionHolder.getSafeActiveSession()?.getRoomSummary(roomId)
val room: RoomSummary? = sessionHolder.getSafeActiveSession()?.roomService()?.getRoomSummary(roomId)
val matrixItem = MatrixItem.EveryoneInRoomItem(
id = roomId,
avatarUrl = room?.avatarUrl,

View File

@ -29,6 +29,8 @@ import im.vector.app.core.platform.VectorViewModel
import im.vector.app.features.session.coroutineScope
import kotlinx.coroutines.launch
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.getRoomSummary
class MigrateRoomViewModel @AssistedInject constructor(
@Assisted initialState: MigrateRoomViewState,

View File

@ -20,6 +20,7 @@ import im.vector.app.core.platform.ViewModelTask
import im.vector.app.core.resources.StringProvider
import org.matrix.android.sdk.api.extensions.tryOrNull
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.getRoom
import timber.log.Timber
import javax.inject.Inject

View File

@ -70,11 +70,11 @@ class RoomListSectionBuilderGroup(
},
{ qpm ->
val name = stringProvider.getString(R.string.bottom_action_rooms)
val updatableFilterLivePageResult = session.getFilteredPagedRoomSummariesLive(qpm)
val updatableFilterLivePageResult = session.roomService().getFilteredPagedRoomSummariesLive(qpm)
onUpdatable(updatableFilterLivePageResult)
val itemCountFlow = updatableFilterLivePageResult.livePagedList.asFlow()
.flatMapLatest { session.getRoomCountLive(updatableFilterLivePageResult.queryParams).asFlow() }
.flatMapLatest { session.roomService().getRoomCountLive(updatableFilterLivePageResult.queryParams).asFlow() }
.distinctUntilChanged()
sections.add(
@ -252,7 +252,7 @@ class RoomListSectionBuilderGroup(
query: (RoomSummaryQueryParams.Builder) -> Unit) {
withQueryParams(query) { roomQueryParams ->
val name = stringProvider.getString(nameRes)
session.getFilteredPagedRoomSummariesLive(roomQueryParams)
session.roomService().getFilteredPagedRoomSummariesLive(roomQueryParams)
.also {
activeSpaceUpdaters.add(it)
}.livePagedList
@ -262,7 +262,7 @@ class RoomListSectionBuilderGroup(
.onEach {
sections.find { it.sectionName == name }
?.notificationCount
?.postValue(session.getNotificationCountForRooms(roomQueryParams))
?.postValue(session.roomService().getNotificationCountForRooms(roomQueryParams))
}
.flowOn(Dispatchers.Default)
.launchIn(coroutineScope)
@ -272,7 +272,7 @@ class RoomListSectionBuilderGroup(
sectionName = name,
livePages = livePagedList,
notifyOfLocalEcho = notifyOfLocalEcho,
itemCount = session.getRoomCountLive(roomQueryParams).asFlow()
itemCount = session.roomService().getRoomCountLive(roomQueryParams).asFlow()
)
)
}

View File

@ -47,6 +47,7 @@ import org.matrix.android.sdk.api.query.ActiveSpaceFilter
import org.matrix.android.sdk.api.query.RoomCategoryFilter
import org.matrix.android.sdk.api.query.RoomTagQueryFilter
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.getRoomSummary
import org.matrix.android.sdk.api.session.room.RoomSummaryQueryParams
import org.matrix.android.sdk.api.session.room.UpdatableLivePageResult
import org.matrix.android.sdk.api.session.room.model.Membership
@ -324,11 +325,11 @@ class RoomListSectionBuilderSpace(
},
{ qpm ->
val name = stringProvider.getString(R.string.bottom_action_rooms)
val updatableFilterLivePageResult = session.getFilteredPagedRoomSummariesLive(qpm)
val updatableFilterLivePageResult = session.roomService().getFilteredPagedRoomSummariesLive(qpm)
onUpdatable(updatableFilterLivePageResult)
val itemCountFlow = updatableFilterLivePageResult.livePagedList.asFlow()
.flatMapLatest { session.getRoomCountLive(updatableFilterLivePageResult.queryParams).asFlow() }
.flatMapLatest { session.roomService().getRoomCountLive(updatableFilterLivePageResult.queryParams).asFlow() }
.distinctUntilChanged()
sections.add(
@ -354,13 +355,13 @@ class RoomListSectionBuilderSpace(
val liveQueryParams = MutableStateFlow(updatedQueryParams)
val itemCountFlow = liveQueryParams
.flatMapLatest {
session.getRoomCountLive(it).asFlow()
session.roomService().getRoomCountLive(it).asFlow()
}
.flowOn(Dispatchers.Main)
.distinctUntilChanged()
val name = stringProvider.getString(nameRes)
val filteredPagedRoomSummariesLive = session.getFilteredPagedRoomSummariesLive(
val filteredPagedRoomSummariesLive = session.roomService().getFilteredPagedRoomSummariesLive(
roomQueryParams.process(spaceFilterStrategy, appStateHandler.safeActiveSpaceId()),
pagedListConfig
)
@ -407,7 +408,7 @@ class RoomListSectionBuilderSpace(
if (countRoomAsNotif) {
RoomAggregateNotificationCount(it.size, it.size)
} else {
session.getNotificationCountForRooms(
session.roomService().getNotificationCountForRooms(
roomQueryParams.process(spaceFilterStrategy, appStateHandler.safeActiveSpaceId())
)
}

View File

@ -42,6 +42,7 @@ import kotlinx.coroutines.launch
import org.matrix.android.sdk.api.extensions.orFalse
import org.matrix.android.sdk.api.query.QueryStringValue
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.room.UpdatableLivePageResult
import org.matrix.android.sdk.api.session.room.members.ChangeMembershipState
import org.matrix.android.sdk.api.session.room.model.tag.RoomTag
@ -233,7 +234,7 @@ class RoomListViewModel @AssistedInject constructor(
viewModelScope.launch {
try {
session.leaveRoom(roomId)
session.roomService().leaveRoom(roomId)
// We do not update the rejectingRoomsIds here, because, the room is not rejected yet regarding the sync data.
// Instead, we wait for the room to be rejected
// Known bug: if the user is invited again (after rejecting the first invitation), the loading will be displayed instead of the buttons.
@ -265,7 +266,7 @@ class RoomListViewModel @AssistedInject constructor(
viewModelScope.launch {
try {
session.joinRoom(action.roomId, null, action.viaServers ?: emptyList())
session.roomService().joinRoom(action.roomId, null, action.viaServers ?: emptyList())
suggestedRoomJoiningState.postValue(suggestedRoomJoiningState.value.orEmpty().toMutableMap().apply {
this[action.roomId] = Success(Unit)
@ -319,7 +320,7 @@ class RoomListViewModel @AssistedInject constructor(
private fun handleLeaveRoom(action: RoomListAction.LeaveRoom) {
_viewEvents.post(RoomListViewEvents.Loading(null))
viewModelScope.launch {
val value = runCatching { session.leaveRoom(action.roomId) }
val value = runCatching { session.roomService().leaveRoom(action.roomId) }
.fold({ RoomListViewEvents.Done }, { RoomListViewEvents.Failure(it) })
_viewEvents.post(value)
}

View File

@ -49,7 +49,7 @@ class ThreadListController @Inject constructor(
}
override fun buildModels() =
when (session.getHomeServerCapabilities().canUseThreading) {
when (session.homeServerCapabilitiesService().getHomeServerCapabilities().canUseThreading) {
true -> buildThreadSummaries()
false -> buildThreadList()
}

View File

@ -33,6 +33,7 @@ import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.threads.ThreadTimelineEvent
import org.matrix.android.sdk.flow.flow
@ -68,7 +69,7 @@ class ThreadListViewModel @AssistedInject constructor(@Assisted val initialState
* capabilities
*/
private fun fetchAndObserveThreads() {
when (session.getHomeServerCapabilities().canUseThreading) {
when (session.homeServerCapabilitiesService().getHomeServerCapabilities().canUseThreading) {
true -> {
fetchThreadList()
observeThreadSummaries()
@ -125,7 +126,7 @@ class ThreadListViewModel @AssistedInject constructor(@Assisted val initialState
}
}
fun canHomeserverUseThreading() = session.getHomeServerCapabilities().canUseThreading
fun canHomeserverUseThreading() = session.homeServerCapabilitiesService().getHomeServerCapabilities().canUseThreading
fun applyFiltering(shouldFilterThreads: Boolean) {
analyticsTracker.capture(Interaction.Name.MobileThreadListFilterItem.toAnalyticsInteraction())

View File

@ -53,7 +53,7 @@ class HomeServerCapabilitiesViewModel @AssistedInject constructor(
override fun initialState(viewModelContext: ViewModelContext): HomeServerCapabilitiesViewState {
val session = EntryPoints.get(viewModelContext.app(), SingletonEntryPoint::class.java).activeSessionHolder().getSafeActiveSession()
return HomeServerCapabilitiesViewState(
capabilities = session?.getHomeServerCapabilities() ?: HomeServerCapabilities()
capabilities = session?.homeServerCapabilitiesService()?.getHomeServerCapabilities() ?: HomeServerCapabilities()
)
}
}

View File

@ -26,6 +26,8 @@ import im.vector.app.core.di.ActiveSessionHolder
import im.vector.app.core.glide.GlideApp
import im.vector.app.features.home.AvatarRenderer
import io.noties.markwon.core.spans.LinkSpan
import org.matrix.android.sdk.api.session.getRoomSummary
import org.matrix.android.sdk.api.session.getUser
import org.matrix.android.sdk.api.session.permalinks.PermalinkData
import org.matrix.android.sdk.api.session.permalinks.PermalinkParser
import org.matrix.android.sdk.api.session.room.model.RoomSummary
@ -100,7 +102,7 @@ class PillsPostProcessor @AssistedInject constructor(@Assisted private val roomI
if (roomId == null) {
sessionHolder.getSafeActiveSession()?.getUser(userId)?.toMatrixItem()
} else {
sessionHolder.getSafeActiveSession()?.getRoomMember(userId, roomId)?.toMatrixItem()
sessionHolder.getSafeActiveSession()?.roomService()?.getRoomMember(userId, roomId)?.toMatrixItem()
}
private fun PermalinkData.RoomLink.toMatrixItem(): MatrixItem? =
@ -116,7 +118,7 @@ class PillsPostProcessor @AssistedInject constructor(@Assisted private val roomI
}
private fun PermalinkData.GroupLink.toMatrixItem(): MatrixItem? {
val group = sessionHolder.getSafeActiveSession()?.getGroupSummary(groupId)
val group = sessionHolder.getSafeActiveSession()?.groupService()?.getGroupSummary(groupId)
return MatrixItem.GroupItem(groupId, group?.displayName, group?.avatarUrl)
}
}

View File

@ -31,6 +31,7 @@ import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.getRoom
class InviteUsersToRoomViewModel @AssistedInject constructor(
@Assisted initialState: InviteUsersToRoomViewState,

View File

@ -34,6 +34,7 @@ import kotlinx.coroutines.sync.withPermit
import org.matrix.android.sdk.api.extensions.orFalse
import org.matrix.android.sdk.api.failure.Failure
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.room.members.ChangeMembershipState
import org.matrix.android.sdk.api.session.room.model.Membership
import org.matrix.android.sdk.api.session.room.roomSummaryQueryParams
@ -111,11 +112,11 @@ class InvitesAcceptor @Inject constructor(
rejectInviteSafely(roomId)
return
}
val roomMembershipChanged = getChangeMemberships(roomId)
val roomMembershipChanged = roomService().getChangeMemberships(roomId)
if (roomMembershipChanged != ChangeMembershipState.Joined && !roomMembershipChanged.isInProgress()) {
try {
Timber.v("Try auto join room: $roomId")
joinRoom(roomId)
roomService().joinRoom(roomId)
} catch (failure: Throwable) {
Timber.v("Failed auto join room: $roomId")
// if we got 404 on invites, the inviting user have left or the hs is off.
@ -134,7 +135,7 @@ class InvitesAcceptor @Inject constructor(
private suspend fun Session.rejectInviteSafely(roomId: String) {
try {
leaveRoom(roomId)
roomService().leaveRoom(roomId)
shouldRejectRoomIds.remove(roomId)
} catch (failure: Throwable) {
Timber.v("Fail rejecting invite for room: $roomId")

View File

@ -133,7 +133,7 @@ class LinkHandlerActivity : VectorBaseActivity<ActivityProgressBinding>() {
} else {
lifecycleScope.launch {
try {
session.signOut(true)
session.signOutService().signOut(true)
Timber.d("## displayAlreadyLoginPopup(): logout succeeded")
sessionHolder.clearActiveSession()
startLoginActivity(uri)

View File

@ -31,6 +31,7 @@ import kotlinx.parcelize.Parcelize
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.events.model.EventType
import org.matrix.android.sdk.api.session.events.model.toContent
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.room.model.livelocation.BeaconInfo
import org.matrix.android.sdk.api.session.room.model.livelocation.LiveLocationBeaconContent
import timber.log.Timber

View File

@ -36,6 +36,8 @@ import kotlinx.coroutines.flow.sample
import kotlinx.coroutines.launch
import org.matrix.android.sdk.api.extensions.orFalse
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.getUser
import org.matrix.android.sdk.api.util.toMatrixItem
/**

View File

@ -81,7 +81,7 @@ class AccountCreatedViewModel @AssistedInject constructor(
private fun handleSetAvatar(action: AccountCreatedAction.SetAvatar) {
setState { copy(isLoading = true) }
viewModelScope.launch {
val result = runCatching { session.updateAvatar(session.myUserId, action.avatarUri, action.filename) }
val result = runCatching { session.profileService().updateAvatar(session.myUserId, action.avatarUri, action.filename) }
.onFailure { _viewEvents.post(AccountCreatedViewEvents.Failure(it)) }
setState {
copy(
@ -95,7 +95,7 @@ class AccountCreatedViewModel @AssistedInject constructor(
private fun handleSetDisplayName(action: AccountCreatedAction.SetDisplayName) {
setState { copy(isLoading = true) }
viewModelScope.launch {
val result = runCatching { session.setDisplayName(session.myUserId, action.displayName) }
val result = runCatching { session.profileService().setDisplayName(session.myUserId, action.displayName) }
.onFailure { _viewEvents.post(AccountCreatedViewEvents.Failure(it)) }
setState {
copy(

View File

@ -36,6 +36,7 @@ import kotlinx.coroutines.launch
import org.matrix.android.sdk.api.MatrixPatterns
import org.matrix.android.sdk.api.extensions.tryOrNull
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.permalinks.PermalinkData
import org.matrix.android.sdk.api.session.room.model.Membership
import org.matrix.android.sdk.api.session.room.peeking.PeekResult
@ -110,7 +111,7 @@ class MatrixToBottomSheetViewModel @AssistedInject constructor(
// could this room be already known
val knownRoom = if (permalinkData.isRoomAlias) {
tryOrNull {
session.getRoomIdByAlias(permalinkData.roomIdOrAlias, false)
session.roomService().getRoomIdByAlias(permalinkData.roomIdOrAlias, false)
}
?.getOrNull()
?.roomId?.let {
@ -195,7 +196,7 @@ class MatrixToBottomSheetViewModel @AssistedInject constructor(
private fun checkForKnownMembers(someMembers: List<MatrixItem.UserItem>) {
viewModelScope.launch(Dispatchers.Default) {
val knownMembers = someMembers.filter {
session.getExistingDirectRoomWithUser(it.id) != null
session.roomService().getExistingDirectRoomWithUser(it.id) != null
}
// put one with avatar first, and take 5
val finalRes = (knownMembers.filter { it.avatarUrl != null } + knownMembers.filter { it.avatarUrl == null })
@ -234,7 +235,7 @@ class MatrixToBottomSheetViewModel @AssistedInject constructor(
}
private suspend fun resolveUser(userId: String): User {
return tryOrNull { session.resolveUser(userId) }
return tryOrNull { session.userService().resolveUser(userId) }
// Create raw user in case the user is not searchable
?: User(userId, null, null)
}
@ -244,7 +245,7 @@ class MatrixToBottomSheetViewModel @AssistedInject constructor(
* main thing is trying to see if it's a space or a room
*/
private suspend fun resolveRoom(roomIdOrAlias: String): PeekResult {
return session.peekRoom(roomIdOrAlias)
return session.roomService().peekRoom(roomIdOrAlias)
}
override fun handle(action: MatrixToAction) {
@ -297,7 +298,7 @@ class MatrixToBottomSheetViewModel @AssistedInject constructor(
}
viewModelScope.launch {
try {
session.joinRoom(
session.roomService().joinRoom(
roomIdOrAlias = action.roomIdOrAlias,
reason = null,
viaServers = action.viaServers?.take(3) ?: emptyList()
@ -316,7 +317,7 @@ class MatrixToBottomSheetViewModel @AssistedInject constructor(
private suspend fun getRoomIdFromRoomIdOrAlias(roomIdOrAlias: String): String {
return if (MatrixPatterns.isRoomAlias(roomIdOrAlias)) {
session.getRoomIdByAlias(roomIdOrAlias, true).get().roomId
session.roomService().getRoomIdByAlias(roomIdOrAlias, true).get().roomId
} else roomIdOrAlias
}

View File

@ -53,6 +53,7 @@ import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.parcelize.Parcelize
import org.matrix.android.sdk.api.session.getRoom
import timber.log.Timber
import javax.inject.Inject

View File

@ -101,6 +101,8 @@ import im.vector.app.features.widgets.WidgetActivity
import im.vector.app.features.widgets.WidgetArgsBuilder
import im.vector.app.space
import org.matrix.android.sdk.api.session.crypto.verification.IncomingSasVerificationTransaction
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.getRoomSummary
import org.matrix.android.sdk.api.session.permalinks.PermalinkData
import org.matrix.android.sdk.api.session.room.model.roomdirectory.PublicRoom
import org.matrix.android.sdk.api.session.terms.TermsService

View File

@ -34,6 +34,9 @@ import org.matrix.android.sdk.api.session.events.model.isEdition
import org.matrix.android.sdk.api.session.events.model.isImageMessage
import org.matrix.android.sdk.api.session.events.model.supportsNotification
import org.matrix.android.sdk.api.session.events.model.toModel
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.getRoomSummary
import org.matrix.android.sdk.api.session.getUser
import org.matrix.android.sdk.api.session.room.model.Membership
import org.matrix.android.sdk.api.session.room.model.RoomMemberContent
import org.matrix.android.sdk.api.session.room.model.message.MessageWithAttachmentContent
@ -100,7 +103,7 @@ class NotifiableEventResolver @Inject constructor(
// Ignore message edition
if (event.isEdition()) return null
val actions = session.getActions(event)
val actions = session.pushRuleService().getActions(event)
val notificationAction = actions.toNotificationAction()
return if (notificationAction.shouldNotify) {
@ -233,7 +236,7 @@ class NotifiableEventResolver @Inject constructor(
private fun resolveStateRoomEvent(event: Event, session: Session, canBeReplaced: Boolean, isNoisy: Boolean): NotifiableEvent? {
val content = event.content?.toModel<RoomMemberContent>() ?: return null
val roomId = event.roomId ?: return null
val dName = event.senderId?.let { session.getRoomMember(it, roomId)?.displayName }
val dName = event.senderId?.let { session.roomService().getRoomMember(it, roomId)?.displayName }
if (Membership.INVITE == content.membership) {
val roomSummary = session.getRoomSummary(roomId)
val body = noticeEventFormatter.format(event, dName, isDm = roomSummary?.isDirect.orFalse())

View File

@ -29,6 +29,7 @@ import im.vector.app.features.session.coroutineScope
import kotlinx.coroutines.launch
import org.matrix.android.sdk.api.extensions.tryOrNull
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.getRoom
import org.matrix.android.sdk.api.session.room.Room
import org.matrix.android.sdk.api.session.room.read.ReadService
import timber.log.Timber
@ -83,7 +84,7 @@ class NotificationBroadcastReceiver : BroadcastReceiver() {
if (room != null) {
session.coroutineScope.launch {
tryOrNull {
session.joinRoom(room.roomId)
session.roomService().joinRoom(room.roomId)
analyticsTracker.capture(room.roomSummary().toAnalyticsJoinedRoom())
}
}
@ -94,7 +95,7 @@ class NotificationBroadcastReceiver : BroadcastReceiver() {
private fun handleRejectRoom(roomId: String) {
activeSessionHolder.getSafeActiveSession()?.let { session ->
session.coroutineScope.launch {
tryOrNull { session.leaveRoom(roomId) }
tryOrNull { session.roomService().leaveRoom(roomId) }
}
}
}
@ -137,7 +138,7 @@ class NotificationBroadcastReceiver : BroadcastReceiver() {
editedEventId = null,
noisy = false,
timestamp = System.currentTimeMillis(),
senderName = session.getRoomMember(session.myUserId, room.roomId)?.displayName
senderName = session.roomService().getRoomMember(session.myUserId, room.roomId)?.displayName
?: context?.getString(R.string.notification_sender_me),
senderId = session.myUserId,
body = message,

View File

@ -27,6 +27,7 @@ import im.vector.app.features.displayname.getBestName
import im.vector.app.features.settings.VectorPreferences
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.content.ContentUrlResolver
import org.matrix.android.sdk.api.session.getUser
import org.matrix.android.sdk.api.util.toMatrixItem
import timber.log.Timber
import javax.inject.Inject

Some files were not shown because too many files have changed in this diff Show More