Skip to content

Commit

Permalink
Pusher did not work
Browse files Browse the repository at this point in the history
  • Loading branch information
OverLeo007 committed Jul 18, 2024
1 parent 98e531c commit dbb36da
Show file tree
Hide file tree
Showing 9 changed files with 122 additions and 70 deletions.
2 changes: 1 addition & 1 deletion app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 12 additions & 8 deletions app/src/main/java/ru/hihit/cobuy/App.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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()
Expand All @@ -52,6 +51,11 @@ class App : Application() {
fun getContext(): Context {
return instance
}

fun getPusherService(): PusherService {
instance.pusherService.isPusherConnected()
return instance.pusherService
}
}
}

Expand All @@ -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
}
}
32 changes: 31 additions & 1 deletion app/src/main/java/ru/hihit/cobuy/pusher/PusherService.kt
Original file line number Diff line number Diff line change
@@ -1,26 +1,56 @@
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

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)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ fun AuthScreen(
vm: AuthViewModel
) {
val context = LocalContext.current
var email by remember { mutableStateOf("[email protected]") }
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) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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())

Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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() {

Expand All @@ -42,8 +35,31 @@ class GroupViewModel(private val groupId: Int) : ViewModel() {
MutableStateFlow(GroupData(0, "", "", "", 0, 0, 0, emptyList()))
var lists: MutableStateFlow<List<ListData>> = 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)
}


Expand Down Expand Up @@ -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")
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 }
}
Expand Down
46 changes: 46 additions & 0 deletions app/src/main/java/ru/hihit/cobuy/utils/Utils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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
}

0 comments on commit dbb36da

Please sign in to comment.