Bobarik31p 1 月之前
父节点
当前提交
d72c7a0599

+ 2 - 1
app/src/main/java/com/example/tasks/model/User.kt

@@ -13,5 +13,6 @@ data class User (
     val Patronymic:String? = null,
     val DateOfBirth: String = "",
     val Gender: Int? = null ,
-    val UID: String = ""
+    val UID: String = "",
+    val avatar: String? = null
 )

+ 42 - 21
app/src/main/java/com/example/tasks/screens/CreateProfile.kt

@@ -1,5 +1,12 @@
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.net.Uri
 import android.os.Build
 import android.widget.Toast
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.PickVisualMediaRequest
+import androidx.activity.result.contract.ActivityResultContracts
 import androidx.annotation.RequiresApi
 import androidx.compose.foundation.BorderStroke
 import androidx.compose.foundation.background
@@ -36,7 +43,6 @@ import androidx.compose.runtime.getValue
 import androidx.compose.runtime.mutableStateOf
 import androidx.compose.runtime.remember
 import androidx.compose.runtime.setValue
-import androidx.compose.ui.AbsoluteAlignment
 import androidx.compose.ui.Alignment
 import androidx.compose.ui.Modifier
 import androidx.compose.ui.draw.clip
@@ -58,6 +64,7 @@ import com.example.tasks.viewModels.AuthViewModel
 import com.vanpra.composematerialdialogs.MaterialDialog
 import com.vanpra.composematerialdialogs.datetime.date.datepicker
 import com.vanpra.composematerialdialogs.rememberMaterialDialogState
+import java.io.ByteArrayOutputStream
 import java.time.LocalDate
 import java.time.format.DateTimeFormatter
 
@@ -77,6 +84,13 @@ fun CreateProfile(navController: NavController, viewModel: AuthViewModel) {
     val name = remember { mutableStateOf("") }
     val surname = remember { mutableStateOf("") }
     val patronymic = remember { mutableStateOf("") }
+    var avatar = remember {byteArrayOf() }
+    val launcher =
+        rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
+            if (uri == null) return@rememberLauncherForActivityResult
+            avatar = bitmapToByteArray(context,uri)
+
+        }
     var expanded by remember {
         mutableStateOf(false)
     }
@@ -100,7 +114,7 @@ fun CreateProfile(navController: NavController, viewModel: AuthViewModel) {
     val formattedDateFromBase by remember {
         derivedStateOf { DateTimeFormatter.ofPattern("yyyy-MM-dd").format(pickedDate) }
     }
-    if(!surnameFlag.value && !nameFlag.value && !dateOfBirthFlag.value && !genderFlag.value){
+    if (!surnameFlag.value && !nameFlag.value && !dateOfBirthFlag.value && !genderFlag.value) {
         enabled.value = false
     }
     Spacer(modifier = Modifier.height(20.dp))
@@ -126,10 +140,10 @@ fun CreateProfile(navController: NavController, viewModel: AuthViewModel) {
                 modifier = Modifier.padding(bottom = 30.dp)
             )
             Spacer(modifier = Modifier.height(20.dp))
-            Button(onClick = {}) {
+            Button(onClick = { launcher.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) }) {
                 Text("Добавить аватарку")
             }
-            Column{
+            Column {
                 OutlinedTextField(value = surname.value,
                     onValueChange = { it -> surname.value = it },
                     leadingIcon = { Icon(Icons.Filled.Person, contentDescription = "Фамилия") },
@@ -162,8 +176,7 @@ fun CreateProfile(navController: NavController, viewModel: AuthViewModel) {
                 if (surname.value.isEmpty()) {
                     surnameFlag.value = true
                     Text("Введите фамилию", color = Color.Red, fontSize = 10.sp)
-                }
-                else{
+                } else {
                     surnameFlag.value = false
                 }
 
@@ -202,8 +215,7 @@ fun CreateProfile(navController: NavController, viewModel: AuthViewModel) {
                 if (name.value.isEmpty()) {
                     nameFlag.value = true
                     Text("Введите имя", color = Color.Red, fontSize = 10.sp)
-                }
-                else{
+                } else {
                     nameFlag.value = false
                 }
 
@@ -298,8 +310,7 @@ fun CreateProfile(navController: NavController, viewModel: AuthViewModel) {
                 if (pickedDate == LocalDate.now()) {
                     dateOfBirthFlag.value = true
                     Text("Введите дату рождения", color = Color.Red, fontSize = 10.sp)
-                }
-                else{
+                } else {
                     dateOfBirthFlag.value = false
                 }
 
@@ -346,7 +357,8 @@ fun CreateProfile(navController: NavController, viewModel: AuthViewModel) {
                     trailingIcon = {
                         Icon(
                             icon,
-                            contentDescription = "")
+                            contentDescription = ""
+                        )
                     },
                     placeholder = {
                         Text(
@@ -387,8 +399,7 @@ fun CreateProfile(navController: NavController, viewModel: AuthViewModel) {
                 if (selectedItem == "") {
                     genderFlag.value = true
                     Text("Выберете пол", color = Color.Red, fontSize = 10.sp)
-                }
-                else{
+                } else {
                     genderFlag.value = false
                 }
             }
@@ -403,18 +414,19 @@ fun CreateProfile(navController: NavController, viewModel: AuthViewModel) {
                         .width(width = 500.dp)
                         .height(height = 56.dp),
                     onClick = {
-                        viewModel.addUser(
-                            name = name.value,
-                            surname = surname.value,
-                            patronymic = patronymic.value,
-                            date_of_birth = formattedDateFromBase,
-                            gender = selectedItem
-                        )
+                        viewModel.addAvatar(avatar)
+                            viewModel.addUser(
+                                name = name.value,
+                                surname = surname.value,
+                                patronymic = patronymic.value,
+                                date_of_birth = formattedDateFromBase,
+                                gender = selectedItem
+                            )
+
                         flag.value = true
 
                     },
                     shape = RoundedCornerShape(size = 10.dp),
-                    enabled = enabled.value,
                     colors = ButtonDefaults.buttonColors(
                         containerColor = Color(0xFF92DCE5),
                         contentColor = Color.White
@@ -480,6 +492,15 @@ fun CreateProfile(navController: NavController, viewModel: AuthViewModel) {
 }
 
 
+private fun bitmapToByteArray(context: Context, uri: Uri): ByteArray {
+    val inputStream = context.contentResolver.openInputStream(uri)
+    val bitmap = BitmapFactory.decodeStream(inputStream)
+    val baos = ByteArrayOutputStream()
+    bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos)
+    return baos.toByteArray()
+}
+
+
 
 
 

+ 29 - 3
app/src/main/java/com/example/tasks/viewModels/AuthViewModel.kt

@@ -14,7 +14,10 @@ import io.github.jan.supabase.gotrue.OtpType
 import io.github.jan.supabase.gotrue.auth
 import io.github.jan.supabase.gotrue.providers.builtin.OTP
 import io.github.jan.supabase.postgrest.from
+import io.github.jan.supabase.storage.storage
+import io.github.jan.supabase.storage.upload
 import kotlinx.coroutines.launch
+import kotlin.time.Duration.Companion.minutes
 
 
 class AuthViewModel : ViewModel() {
@@ -133,11 +136,13 @@ class AuthViewModel : ViewModel() {
         surname: String,
         patronymic: String,
         date_of_birth: String,
-        gender: String
+        gender: String,
+
     ) {
         viewModelScope.launch {
             try {
                 _userState.value = UserState.Loading
+                val basket = Constants.supabase.storage["avatars"]
                 if (gender == "Женский") {
                     Constants.supabase.from("Users").insert(
                         User(
@@ -146,7 +151,8 @@ class AuthViewModel : ViewModel() {
                             DateOfBirth = date_of_birth,
                             Gender = 1,
                             UID = Constants.supabase.auth.currentUserOrNull()!!.id,
-                            Patronymic = patronymic
+                            Patronymic = patronymic,
+                            avatar = basket.createSignedUrl("${Constants.supabase.auth.currentUserOrNull()!!.email}.jpg", expiresIn = 20.minutes)
                         )
                     )
                 } else {
@@ -157,10 +163,13 @@ class AuthViewModel : ViewModel() {
                             DateOfBirth = date_of_birth,
                             Gender = 2,
                             UID = Constants.supabase.auth.currentUserOrNull()!!.id,
-                            Patronymic = patronymic
+                            Patronymic = patronymic,
+                            avatar = basket.createSignedUrl("${Constants.supabase.auth.currentUserOrNull()!!.email}.jpg", expiresIn = 20.minutes)
                         )
                     )
                 }
+
+
                 _userState.value = UserState.Success("The user has been successfully added")
 
             } catch (e: Exception) {
@@ -171,4 +180,21 @@ class AuthViewModel : ViewModel() {
         }
 
     }
+
+    fun addAvatar(byteArray: ByteArray){
+        viewModelScope.launch {
+            try {
+                _userState.value = UserState.Loading
+                val basket = Constants.supabase.storage["avatars"]
+                basket.upload(
+                    "${Constants.supabase.auth.currentUserOrNull()!!.email}.jpg",
+                    byteArray,
+                    true
+                )
+                _userState.value = UserState.Success("The avatar has been successfully added")
+            }catch (e:Exception){
+                _userState.value = UserState.Error("Error: ${e.message}")
+            }
+        }
+    }
 }