From dbb36da339b367d861d2829570850633ff3f7362 Mon Sep 17 00:00:00 2001 From: OverLeo007 Date: Thu, 18 Jul 2024 18:38:24 +0700 Subject: [PATCH] Pusher did not work --- app/build.gradle.kts | 2 +- app/src/main/java/ru/hihit/cobuy/App.kt | 20 +++--- .../ru/hihit/cobuy/pusher/PusherService.kt | 32 ++++++++- .../composableElems/AvatarPlaceholder.kt | 4 -- .../cobuy/ui/components/screens/AuthScreen.kt | 4 +- .../ui/components/screens/GroupsScreen.kt | 1 - .../components/viewmodels/GroupViewModel.kt | 70 ++++++++----------- .../components/viewmodels/GroupsViewModel.kt | 13 ---- .../main/java/ru/hihit/cobuy/utils/Utils.kt | 46 ++++++++++++ 9 files changed, 122 insertions(+), 70 deletions(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index dde19b4..71e6c1f 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -14,7 +14,7 @@ android { minSdk = 31 targetSdk = 34 versionCode = 1 - versionName = "1.0" + versionName = "0.1" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" vectorDrawables { useSupportLibrary = true diff --git a/app/src/main/java/ru/hihit/cobuy/App.kt b/app/src/main/java/ru/hihit/cobuy/App.kt index 3275805..b3c11a7 100644 --- a/app/src/main/java/ru/hihit/cobuy/App.kt +++ b/app/src/main/java/ru/hihit/cobuy/App.kt @@ -2,22 +2,22 @@ package ru.hihit.cobuy import android.app.Application import android.content.Context -import android.util.Log +import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory +import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.json.Json import okhttp3.Interceptor +import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.Response -import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory -import kotlinx.serialization.ExperimentalSerializationApi -import okhttp3.MediaType.Companion.toMediaType import retrofit2.Retrofit - +import ru.hihit.cobuy.pusher.PusherService class App : Application() { lateinit var retrofit: Retrofit private lateinit var okHttpClient: OkHttpClient + lateinit var pusherService: PusherService @OptIn(ExperimentalSerializationApi::class) private val json = Json { @@ -27,16 +27,15 @@ class App : Application() { override fun onCreate() { super.onCreate() + pusherService = PusherService() instance = this val authInterceptor = AuthInterceptor(this) - okHttpClient = OkHttpClient.Builder() .addInterceptor(authInterceptor) .build() retrofit = Retrofit.Builder() .addConverterFactory(json.asConverterFactory("application/json".toMediaType())) -// .addConverterFactory(GsonConverterFactory.create()) .baseUrl(this.getString(R.string.api_url)) .client(okHttpClient) .build() @@ -52,6 +51,11 @@ class App : Application() { fun getContext(): Context { return instance } + + fun getPusherService(): PusherService { + instance.pusherService.isPusherConnected() + return instance.pusherService + } } } @@ -70,7 +74,7 @@ class AuthInterceptor(context: Context) : Interceptor { private fun getToken(): String { val token = sharedPreferences.getString("auth_token", "") ?: "" - Log.d("AuthInterceptor", "Got token: $token") +// Log.d("AuthInterceptor", "Got token: $token") return token } } \ No newline at end of file diff --git a/app/src/main/java/ru/hihit/cobuy/pusher/PusherService.kt b/app/src/main/java/ru/hihit/cobuy/pusher/PusherService.kt index 0b992b1..266d047 100644 --- a/app/src/main/java/ru/hihit/cobuy/pusher/PusherService.kt +++ b/app/src/main/java/ru/hihit/cobuy/pusher/PusherService.kt @@ -1,8 +1,14 @@ +package ru.hihit.cobuy.pusher + +import android.util.Log import com.pusher.client.Pusher import com.pusher.client.PusherOptions import com.pusher.client.channel.Channel +import com.pusher.client.channel.PusherEvent import com.pusher.client.channel.SubscriptionEventListener +import com.pusher.client.connection.ConnectionState import ru.hihit.cobuy.BuildConfig +import java.lang.Exception class PusherService { private val pusher: Pusher @@ -10,17 +16,41 @@ class PusherService { init { val options = PusherOptions().apply { setCluster(BuildConfig.PUSHER_CLUSTER) +// setChannelAuthorizer() } pusher = Pusher(BuildConfig.PUSHER_KEY, options) pusher.connect() } - fun subscribeToChannel(channelName: String, eventName: String, listener: SubscriptionEventListener) { + fun subscribeToChannel( + channelName: String, + eventName: String, + onEvent: (PusherEvent) -> Unit, + onError: (String?, Exception?) -> Unit + ) { + Log.d("PusherService", "Subscribing to channel $channelName") val channel: Channel = pusher.subscribe(channelName) + val listener: SubscriptionEventListener = object : SubscriptionEventListener { + override fun onEvent(event: PusherEvent) { + Log.d("PusherService", "Received event: $event") + onEvent(event) + } + + override fun onError(message: String?, e: Exception?) { + Log.d("PusherService", "Error: $message") + onError(message, e) + } + } channel.bind(eventName, listener) + Log.d("PusherService", "Subscribed to channel? ${channel.isSubscribed}") + } + + fun isPusherConnected(): Unit { + Log.d("PusherService", "Checking if Pusher is connected: ${pusher.connection.state == ConnectionState.CONNECTED}") } fun unsubscribeFromChannel(channelName: String) { + Log.d("PusherService", "Unsubscribing from channel $channelName") pusher.unsubscribe(channelName) } } \ No newline at end of file diff --git a/app/src/main/java/ru/hihit/cobuy/ui/components/composableElems/AvatarPlaceholder.kt b/app/src/main/java/ru/hihit/cobuy/ui/components/composableElems/AvatarPlaceholder.kt index 5573817..e7cd199 100644 --- a/app/src/main/java/ru/hihit/cobuy/ui/components/composableElems/AvatarPlaceholder.kt +++ b/app/src/main/java/ru/hihit/cobuy/ui/components/composableElems/AvatarPlaceholder.kt @@ -3,19 +3,15 @@ package ru.hihit.cobuy.ui.components.composableElems import android.net.Uri import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.ColorPainter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import coil.request.ImageRequest import ru.hihit.cobuy.ui.theme.getColorByHash diff --git a/app/src/main/java/ru/hihit/cobuy/ui/components/screens/AuthScreen.kt b/app/src/main/java/ru/hihit/cobuy/ui/components/screens/AuthScreen.kt index c89e5dc..1018f7e 100644 --- a/app/src/main/java/ru/hihit/cobuy/ui/components/screens/AuthScreen.kt +++ b/app/src/main/java/ru/hihit/cobuy/ui/components/screens/AuthScreen.kt @@ -45,8 +45,8 @@ fun AuthScreen( vm: AuthViewModel ) { val context = LocalContext.current - var email by remember { mutableStateOf("test1@test.com") } - var password by remember { mutableStateOf("qwe123123") } + var email by remember { mutableStateOf("") } + var password by remember { mutableStateOf("") } var passwordVisible by remember { mutableStateOf(false) } var login by remember { mutableStateOf("") } var isRegistering by remember { mutableStateOf(false) } diff --git a/app/src/main/java/ru/hihit/cobuy/ui/components/screens/GroupsScreen.kt b/app/src/main/java/ru/hihit/cobuy/ui/components/screens/GroupsScreen.kt index 10f02f0..f219dec 100644 --- a/app/src/main/java/ru/hihit/cobuy/ui/components/screens/GroupsScreen.kt +++ b/app/src/main/java/ru/hihit/cobuy/ui/components/screens/GroupsScreen.kt @@ -70,7 +70,6 @@ fun GroupsScreen( val isRefreshing by vm.isLoading.observeAsState(false) val swipeRefreshState = rememberSwipeRefreshState(isRefreshing) - val groups by vm.groups.collectAsState() Log.d("GroupsScreen", groups.toString()) diff --git a/app/src/main/java/ru/hihit/cobuy/ui/components/viewmodels/GroupViewModel.kt b/app/src/main/java/ru/hihit/cobuy/ui/components/viewmodels/GroupViewModel.kt index 6f316e0..a4b2885 100644 --- a/app/src/main/java/ru/hihit/cobuy/ui/components/viewmodels/GroupViewModel.kt +++ b/app/src/main/java/ru/hihit/cobuy/ui/components/viewmodels/GroupViewModel.kt @@ -1,25 +1,18 @@ package ru.hihit.cobuy.ui.components.viewmodels -import android.content.ClipData import android.content.Context import android.content.Intent -import android.graphics.Bitmap -import android.graphics.Canvas -import android.graphics.Color import android.net.Uri import android.util.Log import android.widget.Toast import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.graphics.ImageBitmap -import androidx.compose.ui.graphics.asAndroidBitmap -import androidx.core.content.FileProvider import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.joinAll import kotlinx.coroutines.launch import ru.hihit.cobuy.App -import ru.hihit.cobuy.R import ru.hihit.cobuy.api.GroupData import ru.hihit.cobuy.api.GroupRequester import ru.hihit.cobuy.api.ListData @@ -29,8 +22,8 @@ import ru.hihit.cobuy.api.UserData import ru.hihit.cobuy.api.groups.CreateUpdateGroupRequest import ru.hihit.cobuy.api.groups.KickUserRequest import ru.hihit.cobuy.api.lists.CreateListRequest -import java.io.File -import java.io.FileOutputStream +import ru.hihit.cobuy.pusher.PusherWebsocketClient +import ru.hihit.cobuy.utils.makeShareQrIntent class GroupViewModel(private val groupId: Int) : ViewModel() { @@ -42,8 +35,31 @@ class GroupViewModel(private val groupId: Int) : ViewModel() { MutableStateFlow(GroupData(0, "", "", "", 0, 0, 0, emptyList())) var lists: MutableStateFlow> = MutableStateFlow(emptyList()) + private val pusherService = PusherWebsocketClient() + init { updateAll() + subscribeToGroup() + } + + + + private fun subscribeToGroup() { + pusherService.subscribeToChannel( + channelName = "group-changed.$groupId", + eventName = "group-changed", + onEvent = { onWsEvent(it) }, + onError = { message, e -> onWsError(message, e) } + ) + } + + + private fun onWsEvent(event: String) { + Log.d("GroupViewModel", "onWsEvent: $event") + } + + private fun onWsError(message: String?, e: Exception?) { + Log.e("GroupViewModel", "onWsError: $message", e) } @@ -187,39 +203,13 @@ class GroupViewModel(private val groupId: Int) : ViewModel() { } fun shareQr(qrBitmap: ImageBitmap, context: Context) { - val file = File(context.cacheDir, "qr_code.png") - val fOut = FileOutputStream(file) - - // Преобразование ImageBitmap в android.graphics.Bitmap - val androidBitmap = qrBitmap.asAndroidBitmap() - - // Создание нового Bitmap с белым фоном - val whiteBmp = Bitmap.createBitmap(androidBitmap.width, androidBitmap.height, androidBitmap.config) - val canvas = Canvas(whiteBmp) - canvas.drawColor(Color.WHITE) - canvas.drawBitmap(androidBitmap, 0f, 0f, null) - - // Сжатие Bitmap с белым фоном - whiteBmp.compress(Bitmap.CompressFormat.PNG, 85, fOut) - fOut.flush() - fOut.close() - - val uri = FileProvider.getUriForFile(context, "${context.packageName}.provider", file) - - val shareIntent = Intent().apply { - action = Intent.ACTION_SEND - putExtra(Intent.EXTRA_STREAM, uri) - putExtra(Intent.EXTRA_TEXT, context.getString(R.string.share_qr_text, group.value.name)) - type = "image/png" - addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); - } - - // Установите ClipData для поддержки как текста, так и изображения - val clipData = ClipData.newUri(context.contentResolver, "QR Code", uri) - shareIntent.clipData = clipData - + val shareIntent: Intent = makeShareQrIntent(context, qrBitmap, group.value.name) context.startActivity(Intent.createChooser(shareIntent, "Share QR Code")) } + override fun onCleared() { + super.onCleared() + pusherService.unsubscribeFromChannel("group-changed.$groupId") + } } \ No newline at end of file diff --git a/app/src/main/java/ru/hihit/cobuy/ui/components/viewmodels/GroupsViewModel.kt b/app/src/main/java/ru/hihit/cobuy/ui/components/viewmodels/GroupsViewModel.kt index 7a9aa40..470676b 100644 --- a/app/src/main/java/ru/hihit/cobuy/ui/components/viewmodels/GroupsViewModel.kt +++ b/app/src/main/java/ru/hihit/cobuy/ui/components/viewmodels/GroupsViewModel.kt @@ -7,10 +7,8 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel -import androidx.lifecycle.viewModelScope import androidx.navigation.NavHostController import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.launch import ru.hihit.cobuy.App import ru.hihit.cobuy.R import ru.hihit.cobuy.api.GroupData @@ -37,17 +35,6 @@ class GroupsViewModel : ViewModel() { } - fun onWsEditGroup(editedGroup: GroupData) { - viewModelScope.launch { - val currentGroups = groups.value.toMutableList() - val index = currentGroups.indexOfFirst { it.id == editedGroup.id } - if (index != -1) { - currentGroups[index] = editedGroup - groups.value = currentGroups - } - } - } - private fun getGroups() { getAndProcessGroups { groups.value = it } } diff --git a/app/src/main/java/ru/hihit/cobuy/utils/Utils.kt b/app/src/main/java/ru/hihit/cobuy/utils/Utils.kt index 19d231d..ac4a4d1 100644 --- a/app/src/main/java/ru/hihit/cobuy/utils/Utils.kt +++ b/app/src/main/java/ru/hihit/cobuy/utils/Utils.kt @@ -3,10 +3,20 @@ package ru.hihit.cobuy.utils import android.content.ClipData import android.content.ClipboardManager import android.content.Context +import android.content.Intent +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Color import android.net.Uri import android.widget.Toast +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.asAndroidBitmap +import androidx.core.content.FileProvider import com.google.gson.Gson import com.google.gson.reflect.TypeToken +import ru.hihit.cobuy.R +import java.io.File +import java.io.FileOutputStream import java.lang.reflect.Type @@ -106,4 +116,40 @@ fun isJwt(token: String): Boolean { fun String?.toUri(): Uri? { return this?.let { Uri.parse(it) } +} + + +fun makeShareQrIntent(context: Context, qrBitmap: ImageBitmap, groupName: String): Intent { + val file = File(context.cacheDir, "qr_code.png") + val fOut = FileOutputStream(file) + + // Преобразование ImageBitmap в android.graphics.Bitmap + val androidBitmap = qrBitmap.asAndroidBitmap() + + // Создание нового Bitmap с белым фоном + val whiteBmp = + Bitmap.createBitmap(androidBitmap.width, androidBitmap.height, androidBitmap.config) + val canvas = Canvas(whiteBmp) + canvas.drawColor(Color.WHITE) + canvas.drawBitmap(androidBitmap, 0f, 0f, null) + + // Сжатие Bitmap с белым фоном + whiteBmp.compress(Bitmap.CompressFormat.PNG, 85, fOut) + fOut.flush() + fOut.close() + + val uri = FileProvider.getUriForFile(context, "${context.packageName}.provider", file) + + val shareIntent = Intent().apply { + action = Intent.ACTION_SEND + putExtra(Intent.EXTRA_STREAM, uri) + putExtra(Intent.EXTRA_TEXT, context.getString(R.string.share_qr_text, groupName)) + type = "image/png" + addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + } + + // Установите ClipData для поддержки как текста, так и изображения + val clipData = ClipData.newUri(context.contentResolver, "QR Code", uri) + shareIntent.clipData = clipData + return shareIntent } \ No newline at end of file