Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[i85] add ability to fetch current user #4857

Merged
merged 10 commits into from
Jul 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
### ⬆️ Improved

### ✅ Added
- Added `ChannelClient.fetchCurrentUser` to fetch current user from backend. [#4857](https://github.com/GetStream/stream-chat-android/pull/4857)
- Added `FetchCurrentUserListener` interface used to perform actions as side effects when the `ChatCliet.fetchCurrentUser()` method is used to fetch the current user from the backend. [#4857](https://github.com/GetStream/stream-chat-android/pull/4857)

### ⚠️ Changed

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ public final class io/getstream/chat/android/client/ChatClient {
public final fun disconnectSocket ()V
public static final fun dismissChannelNotifications (Ljava/lang/String;Ljava/lang/String;)V
public final fun enableSlowMode (Ljava/lang/String;Ljava/lang/String;I)Lio/getstream/chat/android/client/call/Call;
public final fun fetchCurrentUser ()Lio/getstream/chat/android/client/call/Call;
public final fun flagMessage (Ljava/lang/String;)Lio/getstream/chat/android/client/call/Call;
public final fun flagUser (Ljava/lang/String;)Lio/getstream/chat/android/client/call/Call;
public final fun getAppSettings ()Lio/getstream/chat/android/client/models/AppSettings;
Expand Down Expand Up @@ -3737,6 +3738,10 @@ public abstract interface class io/getstream/chat/android/client/plugin/listener
public abstract fun onMessageEditResult (Lio/getstream/chat/android/client/models/Message;Lio/getstream/chat/android/client/utils/Result;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
}

public abstract interface class io/getstream/chat/android/client/plugin/listeners/FetchCurrentUserListener {
public abstract fun onFetchCurrentUserResult (Lio/getstream/chat/android/client/utils/Result;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
}

public abstract interface class io/getstream/chat/android/client/plugin/listeners/GetMessageListener {
public abstract fun onGetMessageResult (Ljava/lang/String;Lio/getstream/chat/android/client/utils/Result;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
}
Expand Down
29 changes: 29 additions & 0 deletions stream-chat-android-client/detekt-baseline.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,40 @@
<ID>ComplexMethod:Attachment.kt$Attachment$override fun toString(): String</ID>
<ID>ComplexMethod:Message.kt$Message$override fun toString(): String</ID>
<ID>ComplexMethod:User.kt$User$override fun getComparableField(fieldName: String): Comparable&lt;*>?</ID>
<ID>FinalNewline:io.getstream.chat.android.client.chatclient.WhenFetchCurrentUser.kt:1</ID>
<ID>FinalNewline:io.getstream.chat.android.client.user.CurrentUserFetcher.kt:1</ID>
<ID>FinalNewline:io.getstream.chat.android.client.user.CurrentUserFetcherTests.kt:1</ID>
<ID>FinalNewline:io.getstream.chat.android.client.user.CurrentUserUrlBuilderTests.kt:1</ID>
<ID>ForbiddenComment:MessageUtils.kt$// TODO: type should be a sealed/class or enum at the client level</ID>
<ID>LongParameterList:BaseChatModule.kt$BaseChatModule$( private val appContext: Context, private val clientScope: ClientScope, private val userScope: UserScope, private val config: ChatClientConfig, private val notificationsHandler: NotificationHandler, private val notificationConfig: NotificationConfig, private val fileUploader: FileUploader? = null, private val tokenManager: TokenManager = TokenManagerImpl(), private val customOkHttpClient: OkHttpClient? = null, private val lifecycle: Lifecycle, private val httpClientConfig: (OkHttpClient.Builder) -> OkHttpClient.Builder = { it }, )</ID>
<ID>MagicNumber:Attachment.kt$Attachment$9</ID>
<ID>MaxLineLength:Message.kt$*</ID>
<ID>MaxLineLength:Reaction.kt$*</ID>
<ID>NewLineAtEndOfFile:CurrentUserFetcher.kt$io.getstream.chat.android.client.user.CurrentUserFetcher.kt</ID>
<ID>NewLineAtEndOfFile:CurrentUserFetcherTests.kt$io.getstream.chat.android.client.user.CurrentUserFetcherTests.kt</ID>
<ID>NewLineAtEndOfFile:CurrentUserUrlBuilderTests.kt$io.getstream.chat.android.client.user.CurrentUserUrlBuilderTests.kt</ID>
<ID>NewLineAtEndOfFile:WhenFetchCurrentUser.kt$io.getstream.chat.android.client.chatclient.WhenFetchCurrentUser.kt</ID>
<ID>NoBlankLineBeforeRbrace:io.getstream.chat.android.client.user.CurrentUserFetcher.kt:97</ID>
<ID>NoConsecutiveBlankLines:io.getstream.chat.android.client.chatclient.WhenFetchCurrentUser.kt:130</ID>
<ID>NoUnusedImports:io.getstream.chat.android.client.DevicesApiCallsTests.kt:26</ID>
<ID>NoUnusedImports:io.getstream.chat.android.client.chatclient.WhenFetchCurrentUser.kt:14</ID>
<ID>NoUnusedImports:io.getstream.chat.android.client.chatclient.WhenFetchCurrentUser.kt:25</ID>
<ID>NoUnusedImports:io.getstream.chat.android.client.chatclient.WhenFetchCurrentUser.kt:5</ID>
<ID>NoUnusedImports:io.getstream.chat.android.client.chatclient.WhenFetchCurrentUser.kt:6</ID>
<ID>NoUnusedImports:io.getstream.chat.android.client.chatclient.WhenFetchCurrentUser.kt:9</ID>
<ID>NoUnusedImports:io.getstream.chat.android.client.user.CurrentUserFetcher.kt:44</ID>
<ID>ReturnCount:Channel.kt$@InternalStreamChatApi public fun Channel.addMember(member: Member?): Channel</ID>
<ID>ReturnCount:CurrentUserFetcher.kt$CurrentUserFetcherImpl$override suspend fun fetch(): Result&lt;User></ID>
<ID>TooGenericExceptionCaught:CurrentUserFetcher.kt$CurrentUserFetcherImpl$e: Throwable</ID>
<ID>TooGenericExceptionCaught:CurrentUserFetcher.kt$CurrentUserFetcherImpl$t: Throwable</ID>
<ID>UnusedImports:CurrentUserFetcher.kt$import java.net.URI</ID>
<ID>UnusedImports:DevicesApiCallsTests.kt$import kotlinx.coroutines.ExperimentalCoroutinesApi</ID>
<ID>UnusedImports:WhenFetchCurrentUser.kt$import io.getstream.chat.android.client.api.models.QueryChannelRequest</ID>
<ID>UnusedImports:WhenFetchCurrentUser.kt$import io.getstream.chat.android.client.call.CoroutineCall</ID>
<ID>UnusedImports:WhenFetchCurrentUser.kt$import io.getstream.chat.android.client.errors.ChatError</ID>
<ID>UnusedImports:WhenFetchCurrentUser.kt$import io.getstream.chat.android.client.plugin.listeners.QueryChannelListener</ID>
<ID>UnusedImports:WhenFetchCurrentUser.kt$import org.mockito.kotlin.doAnswer</ID>
<ID>UnusedPrivateMember:BaseChatModule.kt$BaseChatModule$private val clientScope: ClientScope</ID>
<ID>UnusedPrivateMember:ChatEventsObservable.kt$ChatEventsObservable$private val logger = StreamLog.getLogger("Chat:EventsObservable")</ID>
</CurrentIssues>
</SmellBaseline>
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import io.getstream.chat.android.client.api.ChatClientConfig
import io.getstream.chat.android.client.notifications.handler.NotificationConfig
import io.getstream.chat.android.client.notifications.handler.NotificationHandler
import io.getstream.chat.android.client.parser.ChatParser
import io.getstream.chat.android.client.scope.ClientScope
import io.getstream.chat.android.client.scope.UserScope
import io.getstream.chat.android.client.token.TokenManager
import io.getstream.chat.android.client.uploader.FileUploader
Expand All @@ -35,7 +36,8 @@ import okhttp3.OkHttpClient
*/
internal class ChatModule(
appContext: Context,
scope: UserScope,
clientScope: ClientScope,
userScope: UserScope,
config: ChatClientConfig,
notificationsHandler: NotificationHandler,
notificationConfig: NotificationConfig,
Expand All @@ -45,7 +47,8 @@ internal class ChatModule(
lifecycle: Lifecycle,
) : BaseChatModule(
appContext,
scope,
clientScope,
userScope,
config,
notificationsHandler,
notificationConfig,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ import io.getstream.chat.android.client.plugin.listeners.CreateChannelListener
import io.getstream.chat.android.client.plugin.listeners.DeleteMessageListener
import io.getstream.chat.android.client.plugin.listeners.DeleteReactionListener
import io.getstream.chat.android.client.plugin.listeners.EditMessageListener
import io.getstream.chat.android.client.plugin.listeners.FetchCurrentUserListener
import io.getstream.chat.android.client.plugin.listeners.GetMessageListener
import io.getstream.chat.android.client.plugin.listeners.HideChannelListener
import io.getstream.chat.android.client.plugin.listeners.MarkAllReadListener
Expand All @@ -159,7 +160,6 @@ import io.getstream.chat.android.client.scope.ClientScope
import io.getstream.chat.android.client.scope.UserScope
import io.getstream.chat.android.client.setup.InitializationCoordinator
import io.getstream.chat.android.client.setup.state.ClientState
import io.getstream.chat.android.client.setup.state.internal.ClientStateImpl
import io.getstream.chat.android.client.setup.state.internal.toMutableState
import io.getstream.chat.android.client.socket.ChatSocket
import io.getstream.chat.android.client.socket.SocketListener
Expand All @@ -171,6 +171,7 @@ import io.getstream.chat.android.client.token.TokenProvider
import io.getstream.chat.android.client.uploader.FileUploader
import io.getstream.chat.android.client.uploader.StreamCdnImageMimeTypes
import io.getstream.chat.android.client.user.CredentialConfig
import io.getstream.chat.android.client.user.CurrentUserFetcher
import io.getstream.chat.android.client.user.storage.SharedPreferencesCredentialStorage
import io.getstream.chat.android.client.user.storage.UserCredentialStorage
import io.getstream.chat.android.client.utils.ProgressCallback
Expand Down Expand Up @@ -237,6 +238,7 @@ internal constructor(
private val chatSocketExperimental: ChatSocketExperimental,
private val pluginFactories: List<PluginFactory>,
public val clientState: ClientState,
private val currentUserFetcher: CurrentUserFetcher,
private val lifecycleObserver: StreamLifecycleObserver,
private val repositoryFactoryProvider: RepositoryFactory.Provider,
) {
Expand Down Expand Up @@ -1058,6 +1060,28 @@ internal constructor(
}
}

/**
* Fetches the current user.
* Works only if the user was previously set and the WS connections is closed.
*/
public fun fetchCurrentUser(): Call<User> {
val relevantPlugins = plugins.filterIsInstance<FetchCurrentUserListener>().also(::logPlugins)
return CoroutineCall(userScope) {
logger.d { "[fetchCurrentUser] socketState: ${socketStateService.state}" }
when {
!isUserSet() -> Result.error(ChatError("User is not set, can't fetch current user"))
isSocketConnected() -> Result.error(ChatError("Socket is connected, can't fetch current user"))
else -> currentUserFetcher.fetch(getCurrentUser()!!)
}
}.doOnResult(userScope) { result ->
logger.v { "[fetchCurrentUser] completed: $result" }
relevantPlugins.forEach { plugin ->
logger.v { "[fetchCurrentUser] #doOnResult; plugin: ${plugin::class.qualifiedName}" }
plugin.onFetchCurrentUserResult(result)
}
}
}

public fun reconnectSocket() {
reconnectSocket(true)
}
Expand Down Expand Up @@ -3093,6 +3117,7 @@ internal constructor(
val module =
ChatModule(
appContext,
clientScope,
userScope,
config,
notificationsHandler ?: NotificationHandlerFactory.createNotificationHandler(appContext),
Expand Down Expand Up @@ -3127,7 +3152,8 @@ internal constructor(
.filterIsInstance<RepositoryFactory.Provider>()
.firstOrNull()
?: NoOpRepositoryFactory.Provider,
clientState = ClientStateImpl(module.networkStateProvider)
clientState = module.clientState,
currentUserFetcher = module.currentUserFetcher,
)
}

Expand Down Expand Up @@ -3196,7 +3222,7 @@ internal constructor(
@JvmField
public val DEFAULT_SORT: QuerySorter<Member> = QuerySortByField.descByName("last_updated")

private const val ANONYMOUS_USER_ID = "!anon"
internal const val ANONYMOUS_USER_ID = "!anon"
private val anonUser by lazy { User(id = ANONYMOUS_USER_ID) }

@JvmStatic
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,16 @@ import io.getstream.chat.android.client.notifications.handler.NotificationHandle
import io.getstream.chat.android.client.parser.ChatParser
import io.getstream.chat.android.client.parser2.MoshiChatParser
import io.getstream.chat.android.client.plugins.requests.ApiRequestsAnalyser
import io.getstream.chat.android.client.scope.ClientScope
import io.getstream.chat.android.client.scope.UserScope
import io.getstream.chat.android.client.setup.state.internal.ClientStateImpl
import io.getstream.chat.android.client.socket.ChatSocket
import io.getstream.chat.android.client.socket.SocketFactory
import io.getstream.chat.android.client.token.TokenManager
import io.getstream.chat.android.client.token.TokenManagerImpl
import io.getstream.chat.android.client.uploader.FileUploader
import io.getstream.chat.android.client.uploader.StreamFileUploader
import io.getstream.chat.android.client.user.CurrentUserFetcher
import io.getstream.logging.StreamLog
import okhttp3.OkHttpClient
import retrofit2.Retrofit
Expand All @@ -76,7 +79,8 @@ import io.getstream.chat.android.client.socket.experimental.ChatSocket as ChatSo
@Suppress("TooManyFunctions")
internal open class BaseChatModule(
private val appContext: Context,
private val scope: UserScope,
private val clientScope: ClientScope,
private val userScope: UserScope,
private val config: ChatClientConfig,
private val notificationsHandler: NotificationHandler,
private val notificationConfig: NotificationConfig,
Expand All @@ -88,15 +92,13 @@ internal open class BaseChatModule(
) {

private val moshiParser: ChatParser by lazy { MoshiChatParser() }

private val socketFactory: SocketFactory by lazy { SocketFactory(moshiParser, tokenManager) }
private val defaultNotifications by lazy { buildNotification(notificationsHandler, notificationConfig) }
private val defaultApi by lazy { buildApi(config) }
private val defaultSocket by lazy {
buildSocket(config, moshiParser)
}
private val chatSocketExperimental: ChatSocketExperimental by lazy {
buildExperimentalChatSocket(config, moshiParser)
}
private val chatSocketExperimental: ChatSocketExperimental by lazy { buildExperimentalChatSocket(config) }
private val defaultFileUploader by lazy {
StreamFileUploader(buildRetrofitCdnApi())
}
Expand All @@ -108,6 +110,18 @@ internal open class BaseChatModule(
val socketStateService: SocketStateService = SocketStateService()
val userStateService: UserStateService = UserStateService()

val clientState by lazy {
ClientStateImpl(networkStateProvider)
}

val currentUserFetcher by lazy {
CurrentUserFetcher(
networkStateProvider = networkStateProvider,
socketFactory = socketFactory,
config = config,
)
}

//region Modules

fun api(): ChatApi = defaultApi
Expand Down Expand Up @@ -142,7 +156,7 @@ internal open class BaseChatModule(
.baseUrl(endpoint)
.client(okHttpClient)
.also(parser::configRetrofit)
.addCallAdapterFactory(RetrofitCallAdapterFactory.create(parser, scope))
.addCallAdapterFactory(RetrofitCallAdapterFactory.create(parser, userScope))
.build()
}

Expand Down Expand Up @@ -213,21 +227,20 @@ internal open class BaseChatModule(
chatConfig.apiKey,
chatConfig.wssUrl,
tokenManager,
SocketFactory(parser, tokenManager),
socketFactory,
networkStateProvider,
parser,
scope,
userScope,
)

private fun buildExperimentalChatSocket(
chatConfig: ChatClientConfig,
parser: ChatParser,
) = ChatSocketExperimental.create(
chatConfig.apiKey,
chatConfig.wssUrl,
tokenManager,
SocketFactory(parser, tokenManager),
scope,
socketFactory,
userScope,
lifecycleObserver,
networkStateProvider,
)
Expand All @@ -245,14 +258,14 @@ internal open class BaseChatModule(
buildRetrofitApi<ConfigApi>(),
buildRetrofitApi<VideoCallApi>(),
buildRetrofitApi<FileDownloadApi>(),
scope,
scope
userScope,
userScope
).let { originalApi ->
DistinctChatApiEnabler(DistinctChatApi(scope, originalApi)) {
DistinctChatApiEnabler(DistinctChatApi(userScope, originalApi)) {
chatConfig.distinctApiCalls
}
}.let { originalApi ->
ExtraDataValidator(scope, originalApi)
ExtraDataValidator(userScope, originalApi)
}

private inline fun <reified T> buildRetrofitApi(): T {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Copyright (c) 2014-2023 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-chat-android/blob/main/LICENSE
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.getstream.chat.android.client.plugin.listeners

import io.getstream.chat.android.client.models.User
import io.getstream.chat.android.client.utils.Result

/**
* Listener used when fetching the current user from the backend.
*/
public interface FetchCurrentUserListener {

/**
* Called when the current user is fetched from the backend.
*/
public suspend fun onFetchCurrentUserResult(result: Result<User>)
}
Loading
Loading