content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* Copyright (c) 2023-2024 PhotonicGluon.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package site.overwrite.encryptedfilesapp.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Cancel
import androidx.compose.material.icons.filled.Tablet
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
/**
* Class that contains dialogs.
*/
class Dialogs {
// Composables
companion object {
/**
* Creates a new confirmation dialog.
*
* @param dialogTitle Title of the dialog.
* @param dialogContent Content of the dialog.
* @param confirmText Text to show for the "confirm" button.
* @param dismissText Text to show for the "dismiss" button.
* @param onDismissal Function that handles dismissal requests.
* @param onConfirmation Function that handles confirmation requests.
* @param icon Optional icon to display on the dialog.
* @param iconDesc Optional description for the icon. If an icon is provided, then this must
* be present.
*/
@Composable
fun ConfirmDialog(
dialogTitle: String,
dialogContent: @Composable (() -> Unit)?,
confirmText: String,
dismissText: String,
onConfirmation: () -> Unit,
onDismissal: () -> Unit,
icon: ImageVector? = null,
iconDesc: String? = null
) {
AlertDialog(
icon = {
if (icon != null) {
Icon(icon, iconDesc)
}
},
title = { Text(text = dialogTitle) },
text = dialogContent,
onDismissRequest = { onDismissal() },
confirmButton = {
TextButton(
onClick = { onConfirmation() }
) {
Text(confirmText)
}
},
dismissButton = {
TextButton(
onClick = { onDismissal() }
) {
Text(dismissText)
}
}
)
}
/**
* Creates a new yes/no dialog.
*
* @param dialogTitle Title of the dialog.
* @param dialogContent Content of the dialog.
* @param onYes Function that handles the "yes" request.
* @param onNo Function that handles the "no" request and dismissals.
* @param icon Optional icon to display on the dialog.
* @param iconDesc Optional description for the icon. If an icon is provided, then this must
* be present.
*/
@Composable
fun YesNoDialog(
dialogTitle: String,
dialogContent: @Composable (() -> Unit)?,
onYes: () -> Unit,
onNo: () -> Unit,
icon: ImageVector? = null,
iconDesc: String? = null
) {
ConfirmDialog(
dialogTitle = dialogTitle,
dialogContent = dialogContent,
confirmText = "Yes",
dismissText = "No",
onConfirmation = { onYes() },
onDismissal = { onNo() },
icon = icon,
iconDesc = iconDesc
)
}
/**
* Creates a new text input dialog.
*
* @param dialogTitle Title of the dialog.
* @param textFieldLabel Label for the text field.
* @param textFieldPlaceholder Placeholder for the text field.
* @param textFieldErrorText Text to show if the validation fails.
* @param onConfirmation Function that handles confirmation requests.
* @param onDismissal Function that handles dismissal requests.
* @param textFieldValidator Validation function that validates the input for the text
* field.
* @param icon Optional icon to display on the dialog.
* @param iconDesc Optional description for the icon. If an icon is provided, then this must
* be present.
* @param singleLine Whether the text field accepts only one line of text.
*/
@Composable
fun TextInputDialog(
dialogTitle: String,
textFieldLabel: String,
textFieldPlaceholder: String = "",
textFieldErrorText: String = "Invalid input",
onConfirmation: (String) -> Unit,
onDismissal: () -> Unit,
textFieldValidator: (String) -> Boolean,
icon: ImageVector? = null,
iconDesc: String? = null,
singleLine: Boolean = true,
) {
// Attributes
var text by remember { mutableStateOf("") }
var isInvalidText by remember { mutableStateOf(false) }
val focusRequester = remember { FocusRequester() }
// Dialog
AlertDialog(
icon = {
if (icon != null) {
Icon(icon, iconDesc)
}
},
title = { Text(text = dialogTitle) },
text = {
TextField(
modifier = Modifier.focusRequester(focusRequester),
value = text,
onValueChange = {
text = it
isInvalidText = !textFieldValidator(text)
},
label = { Text(textFieldLabel) },
placeholder = { Text(textFieldPlaceholder) },
isError = isInvalidText,
supportingText = {
if (isInvalidText) {
Text(
modifier = Modifier.fillMaxWidth(),
text = textFieldErrorText,
color = MaterialTheme.colorScheme.error
)
}
},
singleLine = singleLine
)
},
onDismissRequest = { onDismissal() },
confirmButton = {
TextButton(
enabled = !(text.isBlank() || isInvalidText),
onClick = { onConfirmation(text) }
) {
Text("Confirm")
}
},
dismissButton = {
TextButton(
onClick = { onDismissal() }
) {
Text("Cancel")
}
}
)
LaunchedEffect(Unit) {
focusRequester.requestFocus()
}
}
/**
* Shows a dialog that looks like a circular progress indicator. Indicates some process
* that may take an indefinite amount of time to complete.
*/
@Composable
fun LoadingIndicatorDialog() {
Dialog(
onDismissRequest = {},
properties = DialogProperties(
dismissOnBackPress = false,
dismissOnClickOutside = false
)
) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.size(100.dp)
.background(
color = MaterialTheme.colorScheme.primaryContainer,
shape = RoundedCornerShape(8.dp)
)
) {
CircularProgressIndicator(
color = MaterialTheme.colorScheme.secondary
)
}
}
}
@Composable
private fun ProgressBar(
progress: Float?,
onCancel: (() -> Unit)?
) {
val progressModifier = if (onCancel == null) {
Modifier.fillMaxWidth()
} else {
Modifier.fillMaxWidth(0.9f)
}
Row(
modifier = Modifier
.fillMaxWidth()
.height(24.dp),
verticalAlignment = Alignment.CenterVertically
) {
if (progress != null) {
LinearProgressIndicator(
progress = { progress },
modifier = progressModifier,
color = MaterialTheme.colorScheme.secondary,
trackColor = MaterialTheme.colorScheme.surfaceVariant,
)
} else {
LinearProgressIndicator(
modifier = progressModifier,
color = MaterialTheme.colorScheme.secondary,
trackColor = MaterialTheme.colorScheme.surfaceVariant
)
}
if (onCancel != null) {
IconButton(
onClick = { onCancel() }
) {
Icon(
imageVector = Icons.Default.Cancel,
contentDescription = "Cancel"
)
}
}
}
if (progress != null) {
Text(
"${
String.format(
"%.02f",
progress * 100
)
}%",
modifier = Modifier.offset(y = (-8).dp),
fontSize = 12.sp
)
}
}
/**
* Creates a new progress indicator dialog.
*
* @param dialogTitle Title of the dialog.
* @param dialogSubtitle Subtitle of the dialog.
* @param progress Progress to show on the progress indicator. If `null` then the progress
* indicator will be indeterminate.
* @param onCancel Function to run when the cancel button is pressed.
*/
@Composable
fun ProgressIndicatorDialog(
dialogTitle: String,
dialogSubtitle: String = "",
progress: Float?,
onCancel: (() -> Unit)? = null
) {
Dialog(
onDismissRequest = {},
DialogProperties(
dismissOnBackPress = false,
dismissOnClickOutside = false
)
) {
Card(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(12.dp)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
Text(
text = dialogTitle,
fontSize = 18.sp,
textAlign = TextAlign.Center
)
if (dialogSubtitle.isNotEmpty()) {
Text(
text = dialogSubtitle,
fontSize = 16.sp,
textAlign = TextAlign.Center
)
}
ProgressBar(
progress = progress,
onCancel = onCancel
)
}
}
}
}
}
}
// Previews
@Preview
@Composable
fun ConfirmDialogPreview1() {
Dialogs.ConfirmDialog(
dialogTitle = "Test Confirm Dialog 1",
dialogContent = {
Column {
Text("Test 1")
Text("Test 2")
}
},
confirmText = "Confirm",
dismissText = "Dismiss",
onConfirmation = {},
onDismissal = {}
)
}
@Preview
@Composable
fun ConfirmDialogPreview2() {
Dialogs.ConfirmDialog(
dialogTitle = "Test Confirm Dialog 2",
dialogContent = {
Column {
Text("Test 1")
Text("Test 2")
}
},
confirmText = "Confirm",
dismissText = "Dismiss",
onConfirmation = {},
onDismissal = {},
icon = Icons.Filled.Tablet,
iconDesc = "Tablet"
)
}
@Preview
@Composable
fun YesNoDialogPreview1() {
Dialogs.YesNoDialog(
dialogTitle = "Test Yes No Dialog 1",
dialogContent = {
Column {
Text("Test 1")
Text("Test 2")
}
},
onYes = {},
onNo = {}
)
}
@Preview
@Composable
fun YesNoDialogPreview2() {
Dialogs.YesNoDialog(
dialogTitle = "Test Yes No Dialog 2",
dialogContent = {
Column {
Text("Test 1")
Text("Test 2")
}
},
onYes = {},
onNo = {},
icon = Icons.Filled.Tablet,
iconDesc = "Tablet"
)
}
@Preview
@Composable
fun TextInputDialogPreview1() {
Dialogs.TextInputDialog(
dialogTitle = "Test Text Input Dialog",
textFieldLabel = "Test Text Field",
onConfirmation = { _ -> },
onDismissal = { },
textFieldValidator = { _ -> false }
)
}
@Preview
@Composable
fun TextInputDialogPreview2() {
Dialogs.TextInputDialog(
dialogTitle = "Test Text Input Dialog",
textFieldLabel = "Test Text Field",
onConfirmation = { _ -> },
onDismissal = { },
textFieldValidator = { _ -> false },
textFieldPlaceholder = "Placeholder",
textFieldErrorText = "Error text",
icon = Icons.Filled.Tablet,
iconDesc = "Tablet"
)
}
@Preview
@Composable
fun LoadingIndicatorDialogPreview() {
Dialogs.LoadingIndicatorDialog()
}
@Preview
@Composable
fun ProgressIndicatorDialogPreview1() {
Dialogs.ProgressIndicatorDialog(
dialogTitle = "Test Progress Indicator Dialog 1",
progress = 0.5678f
)
}
@Preview
@Composable
fun ProgressIndicatorDialogPreview2() {
Dialogs.ProgressIndicatorDialog(
dialogTitle = "Test Progress Indicator Dialog 2",
dialogSubtitle = "Some subtitle",
progress = 0.6789f
)
}
@Preview
@Composable
fun ProgressIndicatorDialogPreview3() {
Dialogs.ProgressIndicatorDialog(
dialogTitle = "Test Progress Indicator Dialog 3",
progress = null
)
}
@Preview
@Composable
fun ProgressIndicatorDialogPreview4() {
Dialogs.ProgressIndicatorDialog(
dialogTitle = "Test Progress Indicator Dialog 4",
dialogSubtitle = "Some subtitle",
progress = 0.2222f,
onCancel = {}
)
}
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/ui/Dialogs.kt
|
2414112747
|
/*
* Copyright (c) 2024 PhotonicGluon.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package site.overwrite.encryptedfilesapp.ui
import android.widget.Toast
import androidx.compose.material3.SnackbarDuration
data class ToastData(
val message: String = "",
val duration: Int = Toast.LENGTH_LONG
) {
val isEmpty: Boolean
get() = message.isBlank()
}
data class SnackbarData(
val message: String = "",
val actionLabel: String? = null,
val withDismissAction: Boolean = false,
val duration: SnackbarDuration = if (actionLabel == null) SnackbarDuration.Short else
SnackbarDuration.Indefinite,
val onAction: (() -> Unit)? = null,
val onDismiss: (() -> Unit)? = null,
val snackbarFree: Boolean = true
) {
val isEmpty: Boolean
get() = message.isBlank()
|| (actionLabel != null && onAction == null && onDismiss == null)
}
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/ui/DisplayablesData.kt
|
2599433682
|
/*
* Copyright (c) 2023 PhotonicGluon.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package site.overwrite.encryptedfilesapp.ui.theme
import androidx.compose.ui.graphics.Color
val md_theme_light_primary = Color(0xFF4253C4)
val md_theme_light_onPrimary = Color(0xFFFFFFFF)
val md_theme_light_primaryContainer = Color(0xFFDFE0FF)
val md_theme_light_onPrimaryContainer = Color(0xFF000D60)
val md_theme_light_secondary = Color(0xFF4B57A9)
val md_theme_light_onSecondary = Color(0xFFFFFFFF)
val md_theme_light_secondaryContainer = Color(0xFFDFE0FF)
val md_theme_light_onSecondaryContainer = Color(0xFF000D5F)
val md_theme_light_tertiary = Color(0xFF8E437D)
val md_theme_light_onTertiary = Color(0xFFFFFFFF)
val md_theme_light_tertiaryContainer = Color(0xFFFFD7F0)
val md_theme_light_onTertiaryContainer = Color(0xFF3A0032)
val md_theme_light_error = Color(0xFFBA1A1A)
val md_theme_light_errorContainer = Color(0xFFFFDAD6)
val md_theme_light_onError = Color(0xFFFFFFFF)
val md_theme_light_onErrorContainer = Color(0xFF410002)
val md_theme_light_background = Color(0xFFFFFBFF)
val md_theme_light_onBackground = Color(0xFF1B1B1F)
val md_theme_light_surface = Color(0xFFFFFBFF)
val md_theme_light_onSurface = Color(0xFF1B1B1F)
val md_theme_light_surfaceVariant = Color(0xFFE3E1EC)
val md_theme_light_onSurfaceVariant = Color(0xFF46464F)
val md_theme_light_outline = Color(0xFF777680)
val md_theme_light_inverseOnSurface = Color(0xFFF3F0F4)
val md_theme_light_inverseSurface = Color(0xFF303034)
val md_theme_light_inversePrimary = Color(0xFFBBC3FF)
val md_theme_light_shadow = Color(0xFF000000)
val md_theme_light_surfaceTint = Color(0xFF4253C4)
val md_theme_light_outlineVariant = Color(0xFFC7C5D0)
val md_theme_light_scrim = Color(0xFF000000)
val md_theme_dark_primary = Color(0xFFBBC3FF)
val md_theme_dark_onPrimary = Color(0xFF021B95)
val md_theme_dark_primaryContainer = Color(0xFF2739AB)
val md_theme_dark_onPrimaryContainer = Color(0xFFDFE0FF)
val md_theme_dark_secondary = Color(0xFFBBC3FF)
val md_theme_dark_onSecondary = Color(0xFF192678)
val md_theme_dark_secondaryContainer = Color(0xFF323F90)
val md_theme_dark_onSecondaryContainer = Color(0xFFDFE0FF)
val md_theme_dark_tertiary = Color(0xFFFFACE7)
val md_theme_dark_onTertiary = Color(0xFF57124C)
val md_theme_dark_tertiaryContainer = Color(0xFF722B64)
val md_theme_dark_onTertiaryContainer = Color(0xFFFFD7F0)
val md_theme_dark_error = Color(0xFFFFB4AB)
val md_theme_dark_errorContainer = Color(0xFF93000A)
val md_theme_dark_onError = Color(0xFF690005)
val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6)
val md_theme_dark_background = Color(0xFF1B1B1F)
val md_theme_dark_onBackground = Color(0xFFE4E1E6)
val md_theme_dark_surface = Color(0xFF1B1B1F)
val md_theme_dark_onSurface = Color(0xFFE4E1E6)
val md_theme_dark_surfaceVariant = Color(0xFF46464F)
val md_theme_dark_onSurfaceVariant = Color(0xFFC7C5D0)
val md_theme_dark_outline = Color(0xFF90909A)
val md_theme_dark_inverseOnSurface = Color(0xFF1B1B1F)
val md_theme_dark_inverseSurface = Color(0xFFE4E1E6)
val md_theme_dark_inversePrimary = Color(0xFF4253C4)
val md_theme_dark_shadow = Color(0xFF000000)
val md_theme_dark_surfaceTint = Color(0xFFBBC3FF)
val md_theme_dark_outlineVariant = Color(0xFF46464F)
val md_theme_dark_scrim = Color(0xFF000000)
val seed = Color(0xFF4253C4)
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/ui/theme/Color.kt
|
1415164117
|
/*
* Copyright (c) 2023 PhotonicGluon.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package site.overwrite.encryptedfilesapp.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val LightColors = lightColorScheme(
primary = md_theme_light_primary,
onPrimary = md_theme_light_onPrimary,
primaryContainer = md_theme_light_primaryContainer,
onPrimaryContainer = md_theme_light_onPrimaryContainer,
secondary = md_theme_light_secondary,
onSecondary = md_theme_light_onSecondary,
secondaryContainer = md_theme_light_secondaryContainer,
onSecondaryContainer = md_theme_light_onSecondaryContainer,
tertiary = md_theme_light_tertiary,
onTertiary = md_theme_light_onTertiary,
tertiaryContainer = md_theme_light_tertiaryContainer,
onTertiaryContainer = md_theme_light_onTertiaryContainer,
error = md_theme_light_error,
errorContainer = md_theme_light_errorContainer,
onError = md_theme_light_onError,
onErrorContainer = md_theme_light_onErrorContainer,
background = md_theme_light_background,
onBackground = md_theme_light_onBackground,
surface = md_theme_light_surface,
onSurface = md_theme_light_onSurface,
surfaceVariant = md_theme_light_surfaceVariant,
onSurfaceVariant = md_theme_light_onSurfaceVariant,
outline = md_theme_light_outline,
inverseOnSurface = md_theme_light_inverseOnSurface,
inverseSurface = md_theme_light_inverseSurface,
inversePrimary = md_theme_light_inversePrimary,
surfaceTint = md_theme_light_surfaceTint,
outlineVariant = md_theme_light_outlineVariant,
scrim = md_theme_light_scrim,
)
private val DarkColors = darkColorScheme(
primary = md_theme_dark_primary,
onPrimary = md_theme_dark_onPrimary,
primaryContainer = md_theme_dark_primaryContainer,
onPrimaryContainer = md_theme_dark_onPrimaryContainer,
secondary = md_theme_dark_secondary,
onSecondary = md_theme_dark_onSecondary,
secondaryContainer = md_theme_dark_secondaryContainer,
onSecondaryContainer = md_theme_dark_onSecondaryContainer,
tertiary = md_theme_dark_tertiary,
onTertiary = md_theme_dark_onTertiary,
tertiaryContainer = md_theme_dark_tertiaryContainer,
onTertiaryContainer = md_theme_dark_onTertiaryContainer,
error = md_theme_dark_error,
errorContainer = md_theme_dark_errorContainer,
onError = md_theme_dark_onError,
onErrorContainer = md_theme_dark_onErrorContainer,
background = md_theme_dark_background,
onBackground = md_theme_dark_onBackground,
surface = md_theme_dark_surface,
onSurface = md_theme_dark_onSurface,
surfaceVariant = md_theme_dark_surfaceVariant,
onSurfaceVariant = md_theme_dark_onSurfaceVariant,
outline = md_theme_dark_outline,
inverseOnSurface = md_theme_dark_inverseOnSurface,
inverseSurface = md_theme_dark_inverseSurface,
inversePrimary = md_theme_dark_inversePrimary,
surfaceTint = md_theme_dark_surfaceTint,
outlineVariant = md_theme_dark_outlineVariant,
scrim = md_theme_dark_scrim,
)
@Composable
fun EncryptedFilesAppTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColors
else -> LightColors
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primaryContainer.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/ui/theme/Theme.kt
|
153088232
|
package site.overwrite.encryptedfilesapp.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
)
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/ui/theme/Type.kt
|
430429502
|
/*
* Copyright (c) 2024 PhotonicGluon.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package site.overwrite.encryptedfilesapp.ui
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import site.overwrite.encryptedfilesapp.R
/**
* Data for a notification channel.
*
* @property id Channel to create the notification for.
* @property name Name for the notifications channel.
* @property desc Description of the notification channel.
* @property importance Importance level of the channel.
*/
data class NotificationChannelData(
val id: String,
val name: String,
val desc: String,
val importance: Int = NotificationManager.IMPORTANCE_DEFAULT
)
/**
* Data for an action button.
*
* @param Receiver Type of the receiver.
* @property context Context to launch the intent of the action button.
* @property name Name of the action to perform.
* @property title Label of the action button.
* @property actionReceiver Class that handles the message of the action button.
* @property icon Icon for the action button. Defaults to no icon.
* @property requestCode Request code for the action.
* @property flags Any flags for the action.
*/
data class NotificationActionButtonData<Receiver : BroadcastReceiver>(
val context: Context,
val name: String,
val title: String,
val actionReceiver: Class<Receiver>,
val icon: Int = 0,
val requestCode: Int = 0,
val flags: Int = 0
)
/**
* Data for a notification.
*
* @param id Notification ID.
* @param title Title of the notification.
* @param text Content text inside the notification.
* @param icon Icon to show in the notification.
* @param priority Priority of the notification.
* @param isPersistent Whether the notification is persistent or not.
*/
data class NotificationData(
val id: Int,
val title: String,
val text: String,
val icon: Int = R.drawable.ic_launcher_foreground, // TODO: Use proper notification icon
val priority: Int = NotificationCompat.PRIORITY_DEFAULT,
val isPersistent: Boolean = false
)
/**
* Class for creating a notification within a notification channel.
*
* @property context Context of the notification.
* @property channelData Notification channel data.
*/
class NotificationCreator(
private val context: Context,
private val channelData: NotificationChannelData
) {
private var notificationBuilder: NotificationCompat.Builder? = null
private var notificationData: NotificationData? = null
val notification: Notification?
get() {
if (notificationBuilder == null) return null
return notificationBuilder!!.build()
}
init {
val channel = NotificationChannel(
channelData.id,
channelData.name,
channelData.importance
).apply {
description = channelData.desc
}
val notificationManager: NotificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
Log.d("NOTIFICATIONS", "Created new channel '${channelData.name}' (id: ${channelData.id})")
}
/**
* Builds a new notification.
*
* @param notificationData Data of the notification.
* @return Builder for the notification.
*/
fun buildNotification(notificationData: NotificationData) {
this.notificationData = notificationData
notificationBuilder = NotificationCompat.Builder(context, channelData.id)
.setSmallIcon(notificationData.icon)
.setContentTitle(notificationData.title)
.setContentText(notificationData.text)
.setPriority(notificationData.priority)
.setOngoing(notificationData.isPersistent)
}
/**
* Adds an action button to the notification.
*
* @param Receiver Type of the receiver.
* @param actionButtonData Action button data.
*/
fun <Receiver : BroadcastReceiver> addActionButton(
actionButtonData: NotificationActionButtonData<Receiver>
) {
if (notificationBuilder == null) {
throw Error("Need to build notification first!")
}
val actionIntent = Intent(
actionButtonData.context,
actionButtonData.actionReceiver
).apply {
action = actionButtonData.name
}
val actionPendingIntent = PendingIntent.getBroadcast(
actionButtonData.context,
actionButtonData.requestCode,
actionIntent,
actionButtonData.flags
)
notificationBuilder!!.addAction(
actionButtonData.icon,
actionButtonData.title,
actionPendingIntent
)
}
fun cancelNotification() {
if (notificationData != null) {
NotificationManagerCompat.from(context).cancel(notificationData!!.id)
}
notificationData = null
}
fun deleteChannel() {
NotificationManagerCompat.from(context).deleteNotificationChannel(channelData.id)
Log.d("NOTIFICATIONS", "Deleted channel '${channelData.name}' (id: ${channelData.id})")
}
}
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/ui/NotificationCreator.kt
|
2265654262
|
/*
* Copyright (c) 2024 PhotonicGluon.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package site.overwrite.encryptedfilesapp.ui.login
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.HttpTimeout
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import site.overwrite.encryptedfilesapp.DEFAULT_TIMEOUT_MILLIS
import site.overwrite.encryptedfilesapp.LoginResult
import site.overwrite.encryptedfilesapp.Server
import site.overwrite.encryptedfilesapp.data.CredentialCheckResult
import site.overwrite.encryptedfilesapp.data.Credentials
import site.overwrite.encryptedfilesapp.ui.home.HomeActivity
data class LoginViewUIState(
val credentials: Credentials = Credentials(),
val credentialCheckResult: CredentialCheckResult = CredentialCheckResult.PENDING
) {
fun checkCredentials(onResult: (CredentialCheckResult) -> Unit) {
// Check that all fields are non-empty
val emptyCheckResult = credentials.checkCredentialsIsEmpty()
if (emptyCheckResult != CredentialCheckResult.VALID) {
Log.d("LOGIN", "A field is empty")
onResult(emptyCheckResult)
return
}
// Initialize the HTTP client to use
val client = HttpClient(CIO) {
install(HttpTimeout) {
requestTimeoutMillis = DEFAULT_TIMEOUT_MILLIS
}
}
Server.isValidURL(
credentials.serverURL,
CoroutineScope(Job()),
client
) { isValidURL ->
if (!isValidURL) {
Log.d("LOGIN", "Invalid server URL: ${credentials.serverURL}")
onResult(CredentialCheckResult.INVALID_URL)
return@isValidURL
}
Log.d("LOGIN", "Good URL: ${credentials.serverURL}")
// Now check the username and password
val server = Server(credentials.serverURL)
server.handleLogin(
credentials.username,
credentials.password,
false
) { loginResult ->
when (loginResult) {
LoginResult.SUCCESS -> {
Log.d("LOGIN", "Credentials valid; logged in as '${credentials.username}'")
onResult(CredentialCheckResult.VALID)
}
LoginResult.TIMEOUT -> {
Log.d("LOGIN", "Connection timed out")
onResult(CredentialCheckResult.TIMEOUT)
}
LoginResult.INVALID_USERNAME -> {
Log.d("LOGIN", "Invalid username: ${credentials.username}")
onResult(CredentialCheckResult.INVALID_USERNAME)
}
LoginResult.INVALID_PASSWORD -> {
Log.d("LOGIN", "Invalid password")
onResult(CredentialCheckResult.INVALID_PASSWORD)
}
}
}
}
}
}
class LoginViewModel : ViewModel() {
private val _uiState = MutableStateFlow(LoginViewUIState())
val uiState: StateFlow<LoginViewUIState> = _uiState.asStateFlow() // Read-only state flow
init {
_uiState.value = LoginViewUIState()
}
// Mutable values
var hasUpdatedValues by mutableStateOf(true)
var isLoading by mutableStateOf(false)
var serverURL by mutableStateOf("")
private set
var username by mutableStateOf("")
private set
var password by mutableStateOf("")
private set
// Setters
fun updateServerURL(newURL: String) {
hasUpdatedValues = true
serverURL = newURL
}
fun updateUsername(newUsername: String) {
hasUpdatedValues = true
username = newUsername
}
fun updatePassword(newPassword: String) {
hasUpdatedValues = true
password = newPassword
}
// Other methods
fun allFieldsFilled(): Boolean {
return serverURL.isNotBlank() && username.isNotBlank() && password.isNotEmpty()
}
fun submit(context: Context) {
isLoading = true
// Update the login UI state
_uiState.update {
it.copy(
credentials = Credentials(
serverURL, username, password
),
credentialCheckResult = CredentialCheckResult.PENDING
)
}
hasUpdatedValues = false
// Then check the credentials
_uiState.value.checkCredentials { result ->
isLoading = false
_uiState.update {
it.copy(credentialCheckResult = result)
}
if (result != CredentialCheckResult.VALID) {
password = ""
} else {
// Send the credentials onwards
val intent = Intent(context, HomeActivity::class.java)
intent.putExtra("credentials", _uiState.value.credentials)
context.startActivity(intent)
(context as Activity).finish()
}
}
}
}
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/ui/login/LoginViewModel.kt
|
55522737
|
/*
* Copyright (c) 2024 PhotonicGluon.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package site.overwrite.encryptedfilesapp.ui.login
import android.annotation.SuppressLint
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.asLiveData
import kotlinx.coroutines.Dispatchers
import site.overwrite.encryptedfilesapp.data.DataStoreManager
import site.overwrite.encryptedfilesapp.ui.theme.EncryptedFilesAppTheme
class LoginActivity : ComponentActivity() {
// Properties
private val thisActivity = this
private lateinit var dataStoreManager: DataStoreManager
@SuppressLint("SourceLockedOrientationActivity")
override fun onCreate(savedInstanceState: Bundle?) {
Log.d("LOGIN", "Login activity onCreate")
super.onCreate(savedInstanceState)
// Prevent screen rotate
this.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
// Get things from the data store
var serverURL by mutableStateOf("")
var gotServerURL by mutableStateOf(false)
var username by mutableStateOf("")
var gotUsername by mutableStateOf(false)
dataStoreManager = DataStoreManager(applicationContext)
dataStoreManager.getServerURL().asLiveData(Dispatchers.Main)
.observe(thisActivity) {
serverURL = it
gotServerURL = true
}
dataStoreManager.getUsername().asLiveData(Dispatchers.Main)
.observe(thisActivity) {
username = it
gotUsername = true
}
// Then set the content
setContent {
EncryptedFilesAppTheme {
if (gotUsername && gotServerURL) {
LoginForm(
serverURL = serverURL,
username = username
)
}
}
}
}
override fun onStop() {
Log.d("LOGIN", "Login activity onStop")
super.onStop()
}
}
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/ui/login/LoginActivity.kt
|
3675020161
|
/*
* Copyright (c) 2024 PhotonicGluon.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package site.overwrite.encryptedfilesapp.ui.login
import android.content.res.Configuration
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Dns
import androidx.compose.material.icons.filled.Key
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import site.overwrite.encryptedfilesapp.data.CredentialCheckResult
import site.overwrite.encryptedfilesapp.ui.theme.EncryptedFilesAppTheme
import site.overwrite.encryptedfilesapp.ui.Dialogs
// Constants
const val SERVER_FIELD_LABEL = "Server URL"
const val SERVER_FIELD_PLACEHOLDER = "https://example.com/"
const val SERVER_FIELD_ERROR_TEXT = "Invalid URL"
const val SERVER_FIELD_TIMEOUT_TEXT = "Timed out when connecting"
const val USERNAME_FIELD_LABEL = "Username"
const val USERNAME_FIELD_PLACEHOLDER = "Username"
const val USERNAME_FIELD_ERROR_TEXT = "Invalid Username"
const val PASSWORD_FIELD_LABEL = "Password"
const val PASSWORD_FIELD_PLACEHOLDER = "Password"
const val PASSWORD_FIELD_ERROR_TEXT = "Invalid Password"
// Composables
/**
* Form to handle the login.
*
* @param serverURL Default value for the server URL field.
* @param username Default value for the username field.
* @param loginViewModel Login view model that for the login activity.
*/
@Composable
fun LoginForm(
serverURL: String = "",
username: String = "",
loginViewModel: LoginViewModel = viewModel()
) {
val loginUIState by loginViewModel.uiState.collectAsState()
loginViewModel.updateServerURL(serverURL)
loginViewModel.updateUsername(username)
Surface {
val context = LocalContext.current
Column(
verticalArrangement = Arrangement.spacedBy(2.dp, Alignment.CenterVertically),
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 30.dp)
) {
Text(text = "Login", style = MaterialTheme.typography.titleLarge)
Spacer(modifier = Modifier.padding(vertical = 5.dp))
ServerURLField(
value = loginViewModel.serverURL,
onChange = { loginViewModel.updateServerURL(it) },
isError = !loginViewModel.hasUpdatedValues &&
loginUIState.credentialCheckResult == CredentialCheckResult.INVALID_URL,
isTimeout = !loginViewModel.hasUpdatedValues &&
loginUIState.credentialCheckResult == CredentialCheckResult.TIMEOUT,
modifier = Modifier.fillMaxWidth()
)
UsernameField(
value = loginViewModel.username,
onChange = { loginViewModel.updateUsername(it) },
modifier = Modifier.fillMaxWidth(),
isError = !loginViewModel.hasUpdatedValues &&
loginUIState.credentialCheckResult == CredentialCheckResult.INVALID_USERNAME
)
PasswordField(
value = loginViewModel.password,
onChange = { loginViewModel.updatePassword(it) },
submit = { loginViewModel.submit(context) },
modifier = Modifier.fillMaxWidth(),
isError = !loginViewModel.hasUpdatedValues &&
loginUIState.credentialCheckResult == CredentialCheckResult.INVALID_PASSWORD
)
Spacer(modifier = Modifier.height(20.dp))
Button(
onClick = { loginViewModel.submit(context) },
enabled = loginViewModel.allFieldsFilled(),
shape = RoundedCornerShape(5.dp),
modifier = Modifier.fillMaxWidth()
) {
Text("Login")
}
}
if (loginViewModel.isLoading) {
Dialogs.LoadingIndicatorDialog()
}
}
}
/**
* Field that asks for a server URL input.
*
* @param value Value to use for the field.
* @param onChange Function to run upon input change.
* @param isError Whether the value is erroneous or not.
* @param isTimeout Whether there was a timeout.
* @param modifier Modifier for the input field.
* @param label Label to display for the input field.
* @param placeholder Placeholder for the input field.
* @param errorText Text to show if the value is erroneous.
* @param timeoutText Text to show if the connection timed out.
*/
@Composable
fun ServerURLField(
value: String,
onChange: (String) -> Unit,
isError: Boolean,
isTimeout: Boolean,
modifier: Modifier = Modifier,
label: String = SERVER_FIELD_LABEL,
placeholder: String = SERVER_FIELD_PLACEHOLDER,
errorText: String = SERVER_FIELD_ERROR_TEXT,
timeoutText: String = SERVER_FIELD_TIMEOUT_TEXT
) {
val focusManager = LocalFocusManager.current
val leadingIcon = @Composable {
Icon(
Icons.Default.Dns,
contentDescription = "Server",
tint = MaterialTheme.colorScheme.primary
)
}
OutlinedTextField(
value = value,
onValueChange = onChange,
modifier = modifier,
leadingIcon = leadingIcon,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
keyboardActions = KeyboardActions(
onNext = { focusManager.moveFocus(FocusDirection.Down) }
),
placeholder = { Text(placeholder) },
label = { Text(label) },
singleLine = true,
isError = isError,
supportingText = {
if (isError) {
Text(
modifier = Modifier.fillMaxWidth(),
text = errorText,
color = MaterialTheme.colorScheme.error
)
}
if (isTimeout) {
Text(
modifier = Modifier.fillMaxWidth(),
text = timeoutText,
color = MaterialTheme.colorScheme.error
)
}
}
)
}
/**
* Field that asks for a username input.
*
* @param value Value to place in the field.
* @param onChange Function to run upon input change.
* @param isError Whether the value is erroneous or not.
* @param modifier Modifier for the input field.
* @param label Label to display for the input field.
* @param placeholder Placeholder for the input field.
* @param errorText Text to show if the value is erroneous.
*/
@Composable
fun UsernameField(
value: String,
onChange: (String) -> Unit,
isError: Boolean,
modifier: Modifier = Modifier,
label: String = USERNAME_FIELD_LABEL,
placeholder: String = USERNAME_FIELD_PLACEHOLDER,
errorText: String = USERNAME_FIELD_ERROR_TEXT
) {
val focusManager = LocalFocusManager.current
val leadingIcon = @Composable {
Icon(
Icons.Default.Person,
contentDescription = "Username",
tint = MaterialTheme.colorScheme.primary
)
}
OutlinedTextField(
value = value,
onValueChange = onChange,
modifier = modifier,
leadingIcon = leadingIcon,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
keyboardActions = KeyboardActions(
onNext = { focusManager.moveFocus(FocusDirection.Down) }
),
placeholder = { Text(placeholder) },
label = { Text(label) },
singleLine = true,
isError = isError,
supportingText = {
if (isError) {
Text(
modifier = Modifier.fillMaxWidth(),
text = errorText,
color = MaterialTheme.colorScheme.error
)
}
}
)
}
/**
* Field that asks for a password input.
*
* @param value Value to place in the field.
* @param onChange Function to run upon input change.
* @param submit Function to run when the "done" button is pressed.
* @param isError Whether the value is erroneous or not.
* @param modifier Modifier for the input field.
* @param label Label to display for the input field.
* @param placeholder Placeholder for the input field.
* @param errorText Text to show if the value is erroneous.
*/
@Composable
fun PasswordField(
value: String,
onChange: (String) -> Unit,
submit: () -> Unit,
isError: Boolean,
modifier: Modifier = Modifier,
label: String = PASSWORD_FIELD_LABEL,
placeholder: String = PASSWORD_FIELD_PLACEHOLDER,
errorText: String = PASSWORD_FIELD_ERROR_TEXT
) {
var isPasswordVisible by remember { mutableStateOf(false) }
val leadingIcon = @Composable {
Icon(
Icons.Default.Key,
contentDescription = "Password",
tint = MaterialTheme.colorScheme.primary
)
}
val trailingIcon = @Composable {
IconButton(onClick = { isPasswordVisible = !isPasswordVisible }) {
Icon(
if (isPasswordVisible) Icons.Default.VisibilityOff else Icons.Default.Visibility,
contentDescription = "",
tint = MaterialTheme.colorScheme.primary
)
}
}
OutlinedTextField(
value = value,
onValueChange = onChange,
modifier = modifier,
leadingIcon = leadingIcon,
trailingIcon = trailingIcon,
keyboardOptions = KeyboardOptions(
imeAction = ImeAction.Done,
keyboardType = KeyboardType.Password
),
keyboardActions = KeyboardActions(
onDone = { submit() }
),
placeholder = { Text(placeholder) },
label = { Text(label) },
singleLine = true,
isError = isError,
supportingText = {
if (isError) {
Text(
modifier = Modifier.fillMaxWidth(),
text = errorText,
color = MaterialTheme.colorScheme.error
)
}
},
visualTransformation = if (isPasswordVisible) VisualTransformation.None else
PasswordVisualTransformation()
)
}
// Previews
@Preview(uiMode = Configuration.UI_MODE_NIGHT_NO)
@Composable
fun LoginFormPreviewLight() {
EncryptedFilesAppTheme {
LoginForm()
}
}
@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun LoginFormPreviewDark() {
EncryptedFilesAppTheme {
LoginForm()
}
}
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/ui/login/LoginComponents.kt
|
4202045410
|
/*
* Copyright (c) 2024 PhotonicGluon.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package site.overwrite.encryptedfilesapp.file
import java.io.File
/**
* Secure deletion as described in "NIST SP-800-88 Rev. 1".
*/
class SDelete {
companion object {
/**
* Securely deletes the contents of the file using the method described in "NIST SP-800-88
* Rev. 1".
*
* @param file File to securely delete. Assumes that
* - the file exists; and
* - it is indeed a file (and not a folder)
* @return Status of the deletion: `true` if the item was deleted and `false` if not.
*/
fun deleteFile(file: File): Boolean {
// Get the file size so we know how many null bytes we need to write
val fileSize = file.length()
// We want to fill the file with blocks of null bytes
val content = CharArray(1024)
val numBlocks = fileSize / 1024 + 1 // Good enough approximation of the ceiling
// Now write the blocks
file.bufferedWriter().use { out ->
for (i in 1..numBlocks) {
out.write(content)
}
}
// Finally, attempt deletion
return file.delete()
}
}
}
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/file/SDelete.kt
|
3300009899
|
/*
* Copyright (c) 2024 PhotonicGluon.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package site.overwrite.encryptedfilesapp.file
import android.content.ContentResolver
import android.net.Uri
import android.os.Environment
import android.provider.OpenableColumns
import java.io.File
val FOLDER_NAME_REGEX = Regex("[0-9A-Za-z+\\-_=() ]+")
const val APP_DIR_NAME = "Excelsior"
val DOWNLOADS_DIR: File =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
class Pathing {
companion object {
/**
* @return The application directory that is within the downloads directory.
*/
private fun getAppDir(): String {
return "${DOWNLOADS_DIR.path}/$APP_DIR_NAME"
}
/**
* Gets the file/directory path with reference to the application directory.
*
* @param itemPath Path to the file/directory, with reference to the application directory.
*/
fun getItemPath(itemPath: String): String {
return "${getAppDir()}/$itemPath".trimEnd('/')
}
/**
* Gets the file name from the file path.
*
* @param filePath Path to the file.
* @return File name.
*/
fun getFileName(filePath: String): String {
return filePath.split('/').last()
}
/**
* Gets the file name from a "content://" URI.
*
* @param uri A URI with the "content" scheme.
* @param contentResolver Content resolver that helps resolve the file.
* @return File name.
*/
fun getFileName(
uri: Uri,
contentResolver: ContentResolver
): String {
var result = ""
contentResolver.query(uri, null, null, null, null).use { cursor ->
if (cursor != null) {
if (cursor.moveToFirst()) {
val colIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
result = cursor.getString(colIndex)
}
}
}
return result
}
/**
* Gets the directory that contains the item.
*
* @param itemPath Path to the item.
* @return Directory that contains the item.
*/
fun getContainingDir(itemPath: String): String {
val split = itemPath.split('/')
return split.subList(0, split.size - 1).joinToString("/")
}
/**
* Checks if an item exists at the specified path.
*
* @param itemPath Path to the item to check.
* @return Boolean whether there is an item at the specified path.
*/
fun doesItemExist(itemPath: String): Boolean {
return File(getItemPath(itemPath)).exists()
}
/**
* Checks if a file exists at the specified path.
*
* @param filePath Path to the file to check.
* @return Boolean whether there is a file at the specified path.
*/
fun doesFileExist(filePath: String): Boolean {
val possibleFile = File(getItemPath(filePath))
if (possibleFile.isFile) {
return possibleFile.exists()
}
return false
}
/**
* Recursively list the items in the directory.
*
* @param dirPath Path to the directory.
* @return
*/
fun traverseDir(dirPath: String): List<String> {
val paths = mutableListOf<String>()
val appDir = getAppDir()
File(getItemPath(dirPath)).walkTopDown().forEach {
// We only want to add files and non-empty directories
if (it.isFile || (it.isDirectory && (it.list()?.size ?: 0) != 0)) {
paths.add(it.path.substring(appDir.length))
}
}
// Remove the empty app directory
paths.remove("")
// Now sort the paths
return paths.sorted()
}
/**
* Checks if the provided name is a valid folder name.
*
* The requirements for a valid folder name are adapted from the valid names that Unix
* folders may take.
*
* @param name Proposed name for the folder.
* @return A boolean whether the proposed name is valid or not.
*/
fun isValidFolderName(name: String): Boolean {
return name.isNotBlank() && FOLDER_NAME_REGEX.matches(name)
}
}
}
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/file/Pathing.kt
|
1272100797
|
/*
* Copyright (c) 2024 PhotonicGluon.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package site.overwrite.encryptedfilesapp.file
import android.util.Log
import java.io.File
import java.io.IOException
class CRUDOperations {
companion object {
/**
* Creates a directory at the specified path.
*
* The directory is created within the application directory that is within the `Download`
* directory.
*
* @param pathToDir Path to the directory.
* @return File object representing the directory, or `null` if the directory creation
* failed.
*/
fun createDirectory(pathToDir: String): File? {
val appDirectory = File(Pathing.getItemPath(pathToDir))
if (!appDirectory.exists()) {
val directoryCreated = appDirectory.mkdirs()
if (!directoryCreated) {
// Failed to create the directory
return null
} else {
Log.d("CRUD-OPERATIONS", "Created directory '$pathToDir'")
}
}
return appDirectory
}
/**
* Creates a file with the specified content.
*
* @param filePath Path to the file.
* @return File object representing the file, or `null` if the file creation fails.
*/
fun createFile(
filePath: String
): File? {
val containingDir = createDirectory(Pathing.getContainingDir(filePath))
if (containingDir != null) {
// Create the file within the directory
val file = File(Pathing.getItemPath(filePath))
try {
if (!file.exists()) {
val fileCreated = file.createNewFile()
if (!fileCreated) {
// Failed to create the file
Log.d("CRUD-OPERATIONS", "Failed to create file")
return null
}
}
return file
} catch (e: IOException) {
Log.d("CRUD-OPERATIONS", "Failed to create file: ${e.message}")
}
}
return null
}
/**
* Creates a file with the specified content.
*
* @param filePath Path to the file.
* @param fileContent Content of the file.
* @return File object representing the file, or `null` if the file creation fails.
*/
fun createFile(
filePath: String,
fileContent: ByteArray
): File? {
// Get the directory that contains the file
val containingDir = createDirectory(Pathing.getContainingDir(filePath))
if (containingDir != null) {
// Create the file within the directory
val file = File(Pathing.getItemPath(filePath))
try {
if (!file.exists()) {
val fileCreated = file.createNewFile()
if (!fileCreated) {
// Failed to create the file
Log.d("CRUD-OPERATIONS", "Failed to create file")
return null
} else {
// With the file created, fill it with the contents
file.writeBytes(fileContent)
Log.d("CRUD-OPERATIONS", "Created file '$filePath'")
}
}
return file
} catch (e: IOException) {
Log.d("CRUD-OPERATIONS", "Failed to create file: ${e.message}")
}
}
return null
}
/**
* Gets the file at the specified file path.
*
* @param filePath Path to the file, with respect to the application directory.
* @return The file object, or `null` if the file does not exist.
*/
fun getFile(filePath: String): File? {
if (Pathing.doesFileExist(filePath)) {
return File(Pathing.getItemPath(filePath))
}
return null
}
/**
* Delete a item on the phone.
*
* If the item is a directory, then this function also deletes its contents.
*
* @param fileOrDirectory File or directory to delete.
* @return Status of the deletion: `true` if the item was deleted and `false` if not.
*/
fun deleteItem(fileOrDirectory: File): Boolean {
var allDeleted = true
if (fileOrDirectory.isDirectory) {
for (child in fileOrDirectory.listFiles()!!) {
if (!deleteItem(child)) {
allDeleted = false
}
}
if (allDeleted) {
// The `allDeleted` flag now depends on if we can delete the directory
allDeleted = fileOrDirectory.delete()
}
} else {
// Just try to delete the file using secure deletion
allDeleted = SDelete.deleteFile(fileOrDirectory)
}
if (allDeleted) {
Log.d("CRUD-OPERATIONS", "Deleted '${fileOrDirectory.path}'")
} else {
Log.d("CRUD-OPERATIONS", "Failed to delete '${fileOrDirectory.path}'")
}
return allDeleted
}
/**
* Delete a item on the phone.
*
* If the path points to a directory, then this function also deletes its contents.
*
* @param itemPath Path to the file/folder.
* @return Status of the deletion: `true` if the item was deleted and `false` if not.
*/
fun deleteItem(itemPath: String): Boolean {
val fileOrDirectory = File(Pathing.getItemPath(itemPath))
return deleteItem(fileOrDirectory)
}
}
}
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/file/CRUDOperations.kt
|
2325818089
|
/*
* Copyright (c) 2023-2024 PhotonicGluon.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package site.overwrite.encryptedfilesapp.cryptography
import android.util.Base64
import java.io.FileOutputStream
import java.io.InputStream
import javax.crypto.BadPaddingException
import javax.crypto.Cipher
import javax.crypto.CipherOutputStream
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.SecretKeySpec
// CONSTANTS
private const val AES_KEY_LENGTH = 256
private const val AES_TRANSFORMATION = "AES/CBC/PKCS5Padding"
private const val KEYGEN_ALGORITHM = "PBKDF2WithHmacSHA256"
private const val KEYGEN_ITERATIONS = 120000
/**
* Cryptography functions.
*/
class Cryptography {
companion object {
/**
* Generates the key for AES encryption based on a user's password.
*
* @param password User's password to generate the key for.
* @param salt Salt for the password.
* @return AES key.
*/
fun genAESKey(
password: String,
salt: String
): ByteArray {
val factory = SecretKeyFactory.getInstance(KEYGEN_ALGORITHM)
val spec = PBEKeySpec(
password.toCharArray(),
salt.toByteArray(),
KEYGEN_ITERATIONS,
AES_KEY_LENGTH
)
val key = factory.generateSecret(spec)
return key.encoded
}
/**
* Encrypts bytes using AES.
*
* @param inputStream Input stream for the bytes to encrypt.
* @param outputStream Output stream for encrypted bytes.
* @param key AES encryption/decryption key.
* @param iv Initialization vector used to encrypt the data.
* @param bufferSize Encryption buffer size.
* @param interruptChecker Checks if the request for the encryption was interrupted.
* @param listener Listener for changes in the number of bytes encrypted.
* @return A boolean whether the operation was successful (`true`) or not (`false`).
*/
fun encryptAES(
inputStream: InputStream,
outputStream: FileOutputStream,
key: ByteArray,
iv: String,
bufferSize: Int = 4096,
interruptChecker: () -> Boolean = { false },
listener: (numBytesEncrypted: Long) -> Unit = { _ -> }
): Boolean {
// Set up cipher
val cipher = Cipher.getInstance(AES_TRANSFORMATION)
val secretKeySpec = SecretKeySpec(key, "AES")
val ivParameterSpec = IvParameterSpec(iv.toByteArray())
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec)
// Then process the encryption
val cipherOutputStream = CipherOutputStream(outputStream, cipher)
val buffer = ByteArray(bufferSize)
var numBytesEncrypted = 0L
var numReadBytes: Int
inputStream.use { input ->
cipherOutputStream.use { output ->
while (!interruptChecker()) {
// Read bytes from input and decrypt them
numReadBytes = input.read(buffer)
if (numReadBytes == -1) {
break
}
output.write(buffer, 0, numReadBytes)
// Update the statuses
numBytesEncrypted += numReadBytes
listener(numBytesEncrypted)
}
}
}
return !interruptChecker()
}
/**
* Decrypts encrypted AES text.
*
* @param encryptedText Text to decrypt. This text *should* be a Base64 string.
* @param key AES encryption/decryption key.
* @param iv Initialization vector used to encrypt the data.
* @return Original plaintext.
*/
fun decryptAES(
encryptedText: String,
key: ByteArray,
iv: String
): ByteArray {
val cipher = Cipher.getInstance(AES_TRANSFORMATION)
val secretKeySpec = SecretKeySpec(key, "AES")
val ivParameterSpec = IvParameterSpec(iv.toByteArray())
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec)
try {
val encryptedBytes = Base64.decode(encryptedText, Base64.NO_WRAP)
return cipher.doFinal(encryptedBytes)
} catch (e: IllegalArgumentException) {
throw InvalidDecryptionException("Invalid decryption of ciphertext")
} catch (e: BadPaddingException) {
throw InvalidDecryptionException("Invalid decryption of ciphertext")
}
}
/**
* Decrypts encrypted AES text.
*
* @param inputStream Input stream for the bytes to decrypt. This should *not* be a Base64
* encrypted string.
* @param outputStream Output stream for decrypted bytes.
* @param key AES encryption/decryption key.
* @param iv Initialization vector used to encrypt the data.
* @param bufferSize Encryption buffer size.
* @param interruptChecker Checks if the request for the decryption was interrupted.
* @param listener Listener for changes in the number of bytes encrypted.
* @return A boolean whether the operation was successful (`true`) or not (`false`).
*/
fun decryptAES(
inputStream: InputStream,
outputStream: FileOutputStream,
key: ByteArray,
iv: String,
bufferSize: Int = 4096,
interruptChecker: () -> Boolean = { false },
listener: (numBytesDecrypted: Long) -> Unit = { _ -> }
): Boolean {
// Set up cipher
val cipher = Cipher.getInstance(AES_TRANSFORMATION)
val secretKeySpec = SecretKeySpec(key, "AES")
val ivParameterSpec = IvParameterSpec(iv.toByteArray())
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec)
// Then process the decryption
/*
* Apparently the cipher input stream here has a limited buffer size of 512 bytes.
* (See https://stackoverflow.com/a/49957428)
* So we need to implement our own class to remove this arbitrary limit.
*/
val cipherInputStream = MyCipherInputStream(inputStream, cipher, bufferSize)
val buffer = ByteArray(bufferSize)
var numBytesDecrypted = 0L
var numReadBytes: Int
cipherInputStream.use { input ->
outputStream.use { output ->
while (!interruptChecker()) {
// Read bytes from input and decrypt them
numReadBytes = input.read(buffer)
if (numReadBytes == -1) {
break
}
output.write(buffer, 0, numReadBytes)
// Update the statuses
numBytesDecrypted += numReadBytes
listener(numBytesDecrypted)
}
}
}
return !interruptChecker()
}
}
}
// EXCEPTIONS
class InvalidDecryptionException(message: String) : Exception(message)
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/cryptography/Cryptography.kt
|
4084031127
|
/*
* Copyright (c) 2024 PhotonicGluon.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package site.overwrite.encryptedfilesapp.cryptography
data class EncryptionParameters(
val iv: String = "",
val salt: String = "",
val key: ByteArray? = null
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as EncryptionParameters
if (iv != other.iv) return false
if (salt != other.salt) return false
if (key != null) {
if (other.key == null) return false
if (!key.contentEquals(other.key)) return false
} else if (other.key != null) return false
return true
}
override fun hashCode(): Int {
var result = iv.hashCode()
result = 31 * result + salt.hashCode()
result = 31 * result + (key?.contentHashCode() ?: 0)
return result
}
fun isFilled(): Boolean {
return iv.isNotEmpty() && salt.isNotEmpty() && key != null && key.isNotEmpty()
}
}
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/cryptography/EncryptionParameters.kt
|
424802265
|
/*
* Copyright (c) 2024 PhotonicGluon.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package site.overwrite.encryptedfilesapp
import android.content.Intent
import android.os.Build
import android.os.Bundle
import java.io.Serializable
// Serializable
inline fun <reified T : Serializable> Bundle.serializable(key: String): T? = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU -> getSerializable(key, T::class.java)
else -> @Suppress("DEPRECATION") getSerializable(key) as? T
}
inline fun <reified T : Serializable> Intent.serializable(key: String): T? = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU -> getSerializableExtra(key, T::class.java)
else -> @Suppress("DEPRECATION") getSerializableExtra(key) as? T
}
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/MiscMethods.kt
|
2025202530
|
/*
* Copyright (c) 2023-2024 PhotonicGluon.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package site.overwrite.encryptedfilesapp
import android.util.Log
import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.network.sockets.ConnectTimeoutException
import io.ktor.client.plugins.HttpTimeout
import io.ktor.client.plugins.cookies.HttpCookies
import io.ktor.client.plugins.onDownload
import io.ktor.client.plugins.onUpload
import io.ktor.client.plugins.timeout
import io.ktor.client.request.delete
import io.ktor.client.request.forms.formData
import io.ktor.client.request.forms.submitForm
import io.ktor.client.request.forms.submitFormWithBinaryData
import io.ktor.client.request.get
import io.ktor.client.statement.bodyAsChannel
import io.ktor.client.statement.bodyAsText
import io.ktor.http.Headers
import io.ktor.http.HttpHeaders
import io.ktor.http.parameters
import io.ktor.utils.io.ByteReadChannel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.io.File
import java.net.URLEncoder
// CONSTANTS
// General
const val DEFAULT_TIMEOUT_MILLIS = 5000L
const val TIMEOUT_MILLIS_PER_KILOBYTE_TRANSFER = 250 // Completely arbitrary
// Page paths
const val LOGIN_PAGE = "auth/login"
const val LOGOUT_PAGE = "auth/logout"
const val GET_ENCRYPTION_PARAMS_PAGE = "auth/get-encryption-params"
const val LIST_DIR_PAGE = "file-ops/list-dir"
const val PATH_EXISTS_PAGE = "file-ops/path-exists"
const val GET_FILE_PAGE = "file-ops/get-file"
const val CREATE_FOLDER_PAGE = "file-ops/create-dir"
const val CREATE_FILE_PAGE = "file-ops/create-file"
const val DELETE_ITEM_PAGE = "file-ops/delete-item"
const val PING_PAGE = "ping"
const val GET_VERSION_PAGE = "version"
// CLASSES
enum class HttpMethod {
GET, POST, DELETE
}
enum class LoginResult {
SUCCESS,
INVALID_USERNAME,
INVALID_PASSWORD,
TIMEOUT;
companion object {
fun codeToEnumVal(value: Int): LoginResult {
return entries[value]
}
}
}
/**
* Class that handles the communication with the encrypted files server.
*
* @property serverURL URL to the server. **Assumed to be valid**.
*/
class Server(val serverURL: String) {
// Attributes
private val client = HttpClient(CIO) {
install(HttpCookies)
install(HttpTimeout)
}
private val scope = CoroutineScope(Job())
// Authentication methods
/**
* Checks if the provided credentials are valid and log in, if requested.
*
* @param username Username to check.
* @param password Password to check.
* @param listener Listener to process the result.
*/
fun handleLogin(
username: String,
password: String,
actuallyLogin: Boolean = true,
listener: (LoginResult) -> Unit
) {
// Create the POST Data
val postData = HashMap<String, String>()
postData["username"] = username
postData["password"] = password
// Send the request to the server
sendRequest(
url = serverURL,
method = HttpMethod.POST,
page = if (actuallyLogin) LOGIN_PAGE else "$LOGIN_PAGE?actually-login=false",
scope = scope,
client = client,
timeoutMillis = DEFAULT_TIMEOUT_MILLIS,
processJSONResponse = {
Log.d("SERVER", "Login successful")
listener(LoginResult.SUCCESS)
},
failedResponse = { _, json ->
val message = json.getString("message")
val errorCode = json.getInt("error_code")
Log.d("SERVER", "Login failed: $message")
listener(LoginResult.codeToEnumVal(errorCode))
},
errorListener = { error ->
Log.d("SERVER", "Error when logging in: $error")
if (error is ConnectTimeoutException) {
listener(LoginResult.TIMEOUT)
} else {
listener(LoginResult.INVALID_USERNAME)
}
},
postData = postData
)
}
/**
* Handle the logging out of the user from the server.
*
* @param listener Listener to process the result.
*/
fun handleLogout(
listener: (Boolean) -> Unit
) {
sendRequest(
url = serverURL,
method = HttpMethod.GET,
page = LOGOUT_PAGE,
scope = scope,
client = client,
timeoutMillis = DEFAULT_TIMEOUT_MILLIS,
processJSONResponse = {
Log.d("SERVER", "Logout successful")
listener(true)
},
failedResponse = { _, json ->
val message = json.getString("message")
Log.d("SERVER", "Logout failed: $message")
listener(false)
},
errorListener = { error ->
Log.d("SERVER", "Error when logging out: $error")
listener(false)
}
)
}
// File methods
/**
* Gets the encryption parameters for the logged in user.
*
* @param processResponse Listener for a successful page request.
* @param failedResponse Listener for a failed page request.
* @param errorListener Listener for an page request that results in an error.
*/
fun getEncryptionParameters(
processResponse: (JSONObject) -> Unit,
failedResponse: (String, JSONObject) -> Unit,
errorListener: (Exception) -> Unit,
) {
sendRequest(
url = serverURL,
method = HttpMethod.GET,
page = GET_ENCRYPTION_PARAMS_PAGE,
scope = scope,
client = client,
timeoutMillis = DEFAULT_TIMEOUT_MILLIS,
processJSONResponse = processResponse,
failedResponse = failedResponse,
errorListener = errorListener
)
}
/**
* Gets the list of files in the path.
*
* @param path Path to the directory.
* @param processResponse Listener for a successful page request.
* @param failedResponse Listener for a failed page request.
* @param errorListener Listener for an page request that results in an error.
*/
fun listDir(
path: String,
processResponse: (JSONObject) -> Unit,
failedResponse: (String, JSONObject) -> Unit,
errorListener: (Exception) -> Unit,
) {
// Properly set the page
val encodedPath = encodeString(path)
val page: String = if (encodedPath != "") {
"$LIST_DIR_PAGE?path=$encodedPath"
} else {
LIST_DIR_PAGE
}
// Now we can send the request
sendRequest(
url = serverURL,
method = HttpMethod.GET,
page = page,
scope = scope,
client = client,
timeoutMillis = DEFAULT_TIMEOUT_MILLIS,
processJSONResponse = processResponse,
failedResponse = failedResponse,
errorListener = errorListener
)
}
/**
* Checks if an item exists at the specified path.
*
* @param path Path to the file or folder.
* @param listener Listener for the path check.
* @param errorListener Listener for an page request that results in an error.
*/
fun doesItemExist(
path: String,
listener: (Boolean) -> Unit,
errorListener: (Exception) -> Unit
) {
val encodedPath = encodeString(path)
sendRequest(
url = serverURL,
method = HttpMethod.GET,
page = "$PATH_EXISTS_PAGE/$encodedPath",
scope = scope,
client = client,
timeoutMillis = DEFAULT_TIMEOUT_MILLIS,
processJSONResponse = { json ->
listener(json.getBoolean("exists"))
},
failedResponse = { _, _ -> },
errorListener = errorListener
)
}
/**
* Gets the contents of a file.
*
* @param path Path to the file.
* @param timeoutMillis Timeout for the downloading of the file.
* @param interruptChecker Function that checks whether the operation was cancelled or not.
* @param processResponse Listener for a successful page request.
* @param errorListener Listener for an page request that results in an error.
* @param downloadHandler Function that takes two parameters, the number of transmitted
* bytes (`bytesSentTotal`) and the total bytes to download (`contentLength`), and processes
* it.
*/
fun getFile(
path: String,
timeoutMillis: Long?,
interruptChecker: () -> Boolean,
processResponse: (ByteReadChannel) -> Unit,
errorListener: (Exception) -> Unit,
downloadHandler: suspend (bytesSentTotal: Long, contentLength: Long) -> Unit = { _, _ -> }
) {
val encodedPath = encodeString(path)
sendRequest(
url = serverURL,
method = HttpMethod.GET,
page = "$GET_FILE_PAGE/$encodedPath",
scope = scope,
client = client,
timeoutMillis = timeoutMillis,
responseIsJSON = false,
processRawResponse = processResponse,
errorListener = errorListener,
interruptChecker = interruptChecker,
downloadHandler = downloadHandler
)
}
/**
* Creates a new folder with the specified path.
*
* @param path Path to the new folder.
* @param processResponse Listener for a successful page request.
* @param failedResponse Listener for a failed page request.
* @param errorListener Listener for an page request that results in an error.
*/
fun createFolder(
path: String,
processResponse: (JSONObject) -> Unit,
failedResponse: (String, JSONObject) -> Unit,
errorListener: (Exception) -> Unit,
) {
val encodedPath = encodeString(path)
sendRequest(
url = serverURL,
method = HttpMethod.POST,
page = "$CREATE_FOLDER_PAGE/$encodedPath",
scope = scope,
client = client,
timeoutMillis = DEFAULT_TIMEOUT_MILLIS,
processJSONResponse = processResponse,
failedResponse = failedResponse,
errorListener = errorListener
)
}
/**
* Uploads a file to the server.
*
* @param path Path to the file on the server.
* @param encryptedFile Encrypted file.
* @param mimeType MIME type of the original unencrypted file.
* @param timeoutMillis Timeout for uploading the file.
* @param interruptChecker Function that checks whether the operation was cancelled or not.
* @param processResponse Listener for a successful page request.
* @param failedResponse Listener for a failed page request.
* @param errorListener Listener for an page request that results in an error.
* @param uploadHandler Function that handles uploads. Takes two parameters, the number of
* transmitted bytes (`bytesSentTotal`) and the total bytes to upload (`contentLength`).
*/
fun uploadFile(
path: String,
encryptedFile: File,
mimeType: String,
timeoutMillis: Long?,
interruptChecker: () -> Boolean,
processResponse: (JSONObject) -> Unit,
failedResponse: (String, JSONObject) -> Unit,
errorListener: (Exception) -> Unit,
uploadHandler: suspend (bytesSentTotal: Long, contentLength: Long) -> Unit = { _, _ -> }
) {
val encodedPath = encodeString(path)
sendRequest(
url = serverURL,
method = HttpMethod.POST,
page = "$CREATE_FILE_PAGE/$encodedPath",
scope = scope,
client = client,
timeoutMillis = timeoutMillis,
processJSONResponse = processResponse,
failedResponse = failedResponse,
errorListener = errorListener,
postFile = encryptedFile,
postFileMimeType = mimeType,
interruptChecker = interruptChecker,
uploadHandler = uploadHandler
)
}
/**
* Deletes an item from the server. **This action is irreversible.**
*
* @param path Path to the item.
* @param processResponse Listener for a successful page request.
* @param failedResponse Listener for a failed page request.
* @param errorListener Listener for an page request that results in an error.
*/
fun deleteItem(
path: String,
processResponse: (JSONObject) -> Unit,
failedResponse: (String, JSONObject) -> Unit,
errorListener: (Exception) -> Unit,
) {
val encodedPath = encodeString(path)
sendRequest(
url = serverURL,
method = HttpMethod.DELETE,
page = "$DELETE_ITEM_PAGE/$encodedPath",
scope = scope,
client = client,
timeoutMillis = DEFAULT_TIMEOUT_MILLIS,
processJSONResponse = processResponse,
failedResponse = failedResponse,
errorListener = errorListener
)
}
// Miscellaneous methods
/**
* Gets the server version.
*
* @param processResponse Listener for a successful page request.
* @param failedResponse Listener for a failed page request.
* @param errorListener Listener for an page request that results in an error.
*/
fun getServerVersion(
processResponse: (JSONObject) -> Unit,
failedResponse: (String, JSONObject) -> Unit,
errorListener: (Exception) -> Unit,
) {
sendRequest(
url = serverURL,
method = HttpMethod.GET,
page = GET_VERSION_PAGE,
scope = scope,
client = client,
timeoutMillis = DEFAULT_TIMEOUT_MILLIS,
processJSONResponse = processResponse,
failedResponse = failedResponse,
errorListener = errorListener
)
}
// Static methods
companion object {
/**
* Helper method that sends a request to the specified page on the server.
*
* @param url Server's URL.
* @param method Request method.
* @param page Page (and URL parameters) to send the request to. Assumes that the page
* string is properly encoded.
* @param scope Coroutine scope.
* @param client HTTP client.
* @param timeoutMillis Timeout of the request in milliseconds.
* @param responseIsJSON Whether the response from the server is in JSON format.
* @param processRawResponse Processes a raw successful response from the server. Required
* if [responseIsJSON] is `false`.
* @param processJSONResponse Processes the JSON response from the server. Required if
* [responseIsJSON] is `true`.
* @param failedResponse Listener for a failed page request.
* @param errorListener Listener for an page request that results in an error.
* @param postData Data to included in the POST request. Required if [postFile] is not
* provided and if the request is a POST request.
* @param postFile File to be included in the POST request. Required if [postData] is not
* provided and if the request is a POST request.
* @param postFileMimeType MIME type of the file included in the POST request. Required if
* [postFile] is provided.
* @param interruptChecker Checks if an interrupt was requested. Recommended to be set if
* using this for downloading or uploading.
* @param downloadHandler Function that takes two parameters, the number of transmitted
* bytes (`bytesSentTotal`) and the total bytes to download (`contentLength`), and processes
* it.
* @param uploadHandler Function that takes two parameters, the number of transmitted
* bytes (`bytesSentTotal`) and the total bytes to upload (`contentLength`), and processes
* it.
*/
private fun sendRequest(
url: String,
method: HttpMethod,
page: String,
scope: CoroutineScope,
client: HttpClient,
timeoutMillis: Long?,
responseIsJSON: Boolean = true,
processRawResponse: (channel: ByteReadChannel) -> Unit = { _ -> },
processJSONResponse: (json: JSONObject) -> Unit = { _ -> },
failedResponse: (status: String, json: JSONObject) -> Unit = { _, _ -> },
errorListener: (error: Exception) -> Unit = { _ -> },
postData: HashMap<String, String>? = null,
postFile: File? = null,
postFileMimeType: String? = null,
interruptChecker: suspend () -> Boolean = { false },
downloadHandler: suspend (bytesSentTotal: Long, contentLength: Long) -> Unit = { _, _ -> },
uploadHandler: suspend (bytesSentTotal: Long, contentLength: Long) -> Unit = { _, _ -> },
) {
// Form the full URL
val fullURL = "$url/$page"
scope.launch {
try {
Log.d("SERVER", "Attempting to send $method request to '$fullURL'")
val response = when (method) {
HttpMethod.GET -> client.get(fullURL) {
onDownload { bytesSentTotal: Long, contentLength: Long ->
if (interruptChecker()) {
cancel()
}
downloadHandler(bytesSentTotal, contentLength)
}
timeout {
requestTimeoutMillis = timeoutMillis
}
}
HttpMethod.POST ->
if (postFile != null && postFileMimeType != null) {
client.submitFormWithBinaryData(
url = fullURL,
formData = formData {
// TODO: Is `readBytes()` the best method?
append("file", postFile.readBytes(), Headers.build {
append(HttpHeaders.ContentType, postFileMimeType)
append(
HttpHeaders.ContentDisposition,
"filename=\"${postFile.name}\""
)
})
}
) {
onUpload { bytesSentTotal: Long, contentLength: Long ->
if (interruptChecker()) {
cancel()
}
uploadHandler(bytesSentTotal, contentLength)
}
timeout {
requestTimeoutMillis = timeoutMillis
}
}
} else {
client.submitForm(
url = fullURL,
formParameters = parameters {
postData?.forEach { (key, value) ->
append(key, value)
}
}) {
onUpload { bytesSentTotal: Long, contentLength: Long ->
if (interruptChecker()) {
cancel()
}
uploadHandler(bytesSentTotal, contentLength)
}
timeout {
requestTimeoutMillis = timeoutMillis
}
}
}
HttpMethod.DELETE -> client.delete(fullURL)
}
Log.d("SERVER", "Sent $method request to '$fullURL'")
if (response.status.value == 200) {
if (responseIsJSON) {
val json = JSONObject(response.bodyAsText())
val status = json.getString("status")
if (status == "ok") {
processJSONResponse(json)
} else {
failedResponse(status, json)
}
} else {
processRawResponse(response.bodyAsChannel())
}
} else {
Log.d("SERVER", "Error ${response.status.value} for '$fullURL'")
}
} catch (e: Exception) {
errorListener(e)
}
}
}
/**
* Determines whether the provided URL is a valid server URL.
*
* @param serverURL URL to check.
* @param scope Coroutine scope.
* @param client HTTP client.
* @param listener Listener to process the result.
*/
fun isValidURL(
serverURL: String,
scope: CoroutineScope,
client: HttpClient,
listener: (Boolean) -> Unit
) {
Log.d("SERVER", "Checking if '$serverURL' is valid")
sendRequest(
url = serverURL,
method = HttpMethod.GET,
page = PING_PAGE,
scope = scope,
client = client,
timeoutMillis = DEFAULT_TIMEOUT_MILLIS,
processJSONResponse = { json ->
val response = json.get("content")
if (response == "pong") {
Log.d("SERVER", "'$serverURL' is valid")
listener(true)
} else {
Log.d("SERVER", "'$serverURL' is not valid")
listener(false)
}
},
failedResponse = { _, _ ->
Log.d("SERVER", "Failed to connect to '$serverURL'; is not valid"); listener(
false
)
},
errorListener = { error ->
Log.d(
"SERVER",
"Error when connecting to '$serverURL': $error"
); listener(false)
}
)
}
/**
* Performs URL encoding on strings.
*
* @param string String to URL encode.
* @return URL encoded string.
*/
fun encodeString(string: String): String {
val rawEncodedString = URLEncoder.encode(string, "UTF-8")
return rawEncodedString.replace("+", "%20")
}
}
}
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/Server.kt
|
3658199311
|
/*
* Copyright (c) 2023-2024 PhotonicGluon.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package site.overwrite.encryptedfilesapp.data
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import java.io.IOException
class DataStoreManager(private val context: Context) {
// Properties and keys
companion object {
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
val serverURLKey = stringPreferencesKey("server_url")
val usernameKey = stringPreferencesKey("username")
}
// Helper methods
/**
* Gets the preferences from the data store.
*
* @return Preferences flow.
*/
private fun getPreferences(): Flow<Preferences> {
return context.dataStore.data.catch { exception ->
if (exception is IOException) {
emit(emptyPreferences())
} else {
throw exception
}
}
}
// Getters
/**
* Gets the server URL from the data store.
*
* @return Server URL as a flow string.
*/
fun getServerURL(): Flow<String> {
return getPreferences().map { preferences ->
val serverURL = preferences[serverURLKey] ?: ""
serverURL
}
}
/**
* Gets the username from the data store.
*
* @return Username as a flow string.
*/
fun getUsername(): Flow<String> {
return getPreferences().map { preferences ->
val username = preferences[usernameKey] ?: ""
username
}
}
// Setters
/**
* Sets the server URL in the data store.
*
* @param serverURL Server URL to set.
*/
suspend fun setServerURL(serverURL: String) {
context.dataStore.edit { preferences ->
preferences[serverURLKey] = serverURL
}
}
/**
* Sets the username in the data store.
*
* @param username Username to set.
*/
suspend fun setUsername(username: String) {
context.dataStore.edit { preferences ->
preferences[usernameKey] = username
}
}
}
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/data/DataStoreManager.kt
|
2117493059
|
/*
* Copyright (c) 2024 PhotonicGluon.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package site.overwrite.encryptedfilesapp.data
import android.util.Log
import org.json.JSONObject
import site.overwrite.encryptedfilesapp.file.Pathing
// Enums
enum class ItemType {
FILE,
DIRECTORY
}
enum class SyncStatus {
SYNCED,
NOT_SYNCED,
UNSYNCABLE
}
// Classes
abstract class RemoteItem(
name: String,
path: String,
size: Long,
val type: ItemType,
var parentDir: RemoteDirectory?,
markedForLocalDeletion: Boolean = false,
markedForServerDeletion: Boolean = false
) {
// Fields
var name: String = name
private set
var path: String = path
private set
var size: Long = size
private set
val syncStatus: SyncStatus
get() {
if (size == 0L) {
return SyncStatus.UNSYNCABLE
}
if (!markedForLocalDeletion && isSynced()) {
return SyncStatus.SYNCED
}
return SyncStatus.NOT_SYNCED
}
var markedForLocalDeletion: Boolean = markedForLocalDeletion
private set
var markedForServerDeletion: Boolean = markedForServerDeletion
private set
val dirPath: String
get() {
return Pathing.getContainingDir(path)
}
// Setters
/**
* Sets the new name of the remote item.
*
* @param newName New name of the file.
* @return Status of the name update. Is `true` if successful and `false` otherwise.
*/
fun setName(newName: String): Boolean {
if (newName.isBlank()) {
Log.d("REMOTE ITEMS", "Cannot set a blank file name")
return false
}
name = newName
// TODO: Handle updating name on the server
return true
}
/**
* Sets the new path of the remote item.
*
* @param newPath New path of the file.
* @return Status of the path update. Is `true` if successful and `false` otherwise.
*/
fun setPath(newPath: String): Boolean {
if (newPath.isBlank()) {
Log.d("REMOTE ITEMS", "Cannot set a blank file path")
return false
}
path = newPath
// TODO: Handle updating path on the server
return true
}
/**
* Sets the new size of the remote item.
*
* @param newSize New size of the file.
*/
fun setSize(newSize: Long) {
val sizeDelta = newSize - size
size = newSize
if (parentDir != null) {
parentDir!!.setSize(parentDir!!.size + sizeDelta)
}
}
// Methods
open fun markForLocalDeletion(state: Boolean = true) {
markedForLocalDeletion = state
}
fun unmarkForLocalDeletion() {
markForLocalDeletion(false)
}
open fun markForServerDeletion(state: Boolean = true) {
markedForServerDeletion = state
}
fun unmarkForServerDeletion() {
markForServerDeletion(false)
}
// Methods
/**
* Nicely formats the file size.
*
* @param precision Number of decimal places to format the file size.
* @return Formatted file size.
*/
fun formattedSize(precision: Int = 2): String {
return FileSizeUtils.formatFileSize(size, precision = precision)
}
/**
* Determines whether the item is synced or not.
*
* @return Boolean whether the item is synced or not.
*/
protected abstract fun isSynced(): Boolean
}
/**
* Represents a remote file that is present on the server.
*
* @property name Name of the file.
* @property path Relative path to the file, with respect to the base directory.
* @property size Size of the file.
* @property parentDir Directory that contains this file.
*/
class RemoteFile(
name: String,
path: String,
size: Long,
parentDir: RemoteDirectory?
) : RemoteItem(name, path, size, ItemType.FILE, parentDir) {
// Methods
override fun isSynced(): Boolean {
return path.isNotEmpty() && Pathing.doesFileExist(path)
}
companion object {
/**
* Converts an obtained JSON object.
*
* @param json JSON object that represents the item.
* @return Representative object.
*/
fun fromJSON(json: JSONObject): RemoteFile {
val path = json.getString("path")
return RemoteFile(
json.getString("name"),
path,
json.getLong("size"),
null // Will update when the file is placed in a directory
)
}
}
}
/**
* Represents a remote folder that is present on the server.
*
* @property name Name of the folder.
* @property path Relative path to the folder, with respect to the base directory.
* @property size Total size of the folder.
* @property subdirs Array of subfolders that this folder contains.
* @property files Array of files that this folder contains.
* @property parentDir Directory that contains this folder.
*/
open class RemoteDirectory(
name: String,
path: String,
size: Long,
var subdirs: Array<RemoteDirectory>,
var files: Array<RemoteFile>,
parentDir: RemoteDirectory?
) : RemoteItem(name, path, size, ItemType.DIRECTORY, parentDir) {
// Fields
val items: Array<RemoteItem>
get() {
val items = ArrayList<RemoteItem>()
for (folder in subdirs) {
items.add(folder)
}
for (file in files) {
items.add(file)
}
return items.toTypedArray()
}
/**
* Files that belong to this directory or any subdirectory.
*/
val constituentFiles: Array<RemoteFile>
get() {
val files = ArrayList<RemoteFile>()
for (folder in subdirs) {
files.addAll(folder.constituentFiles)
}
for (file in this.files) {
files.add(file)
}
return files.toTypedArray()
}
/**
* Synced files that belong to this directory or any subdirectory.
*/
val syncedConstituentFiles: Array<RemoteFile>
get() {
val allFiles = constituentFiles
val syncedFiles = ArrayList<RemoteFile>()
for (file in allFiles) {
if (Pathing.doesFileExist(file.path)) {
syncedFiles.add(file)
}
}
return syncedFiles.toTypedArray()
}
// Methods
override fun isSynced(): Boolean {
// If the folder is empty then we will call it synced
if (files.isEmpty() && subdirs.isEmpty()) {
return true
}
// Check whether the files are synced
for (file: RemoteFile in files) {
if (file.syncStatus == SyncStatus.NOT_SYNCED) {
return false
}
}
// Then check whether the folders are synced
for (folder: RemoteDirectory in subdirs) {
if (!folder.isSynced()) {
return false
}
}
// All items are synced, so the folder is synced
return true
}
override fun markForLocalDeletion(state: Boolean) {
super.markForLocalDeletion(state)
for (file in files) {
file.markForLocalDeletion(state)
}
for (folder in subdirs) {
folder.markForLocalDeletion(state)
}
}
override fun markForServerDeletion(state: Boolean) {
super.markForServerDeletion(state)
for (file in files) {
file.markForServerDeletion(state)
}
for (folder in subdirs) {
folder.markForServerDeletion(state)
}
}
private fun addFile(file: RemoteFile) {
val filesList = files.toMutableList()
filesList.add(file)
files = filesList.toTypedArray()
setSize(size + file.size)
}
fun addFile(
name: String,
path: String,
size: Long
) {
addFile(
RemoteFile(
name,
path,
size,
this
)
)
}
private fun addFolder(directory: RemoteDirectory) {
val subdirList = subdirs.toMutableList()
subdirList.add(directory)
subdirs = subdirList.toTypedArray()
}
fun addFolder(
name: String,
path: String
) {
addFolder(
RemoteDirectory(
name,
path,
0,
emptyArray(),
emptyArray(),
this
)
)
}
fun removeFile(file: RemoteFile) {
val filesList = files.toMutableList()
filesList.remove(file)
files = filesList.toTypedArray()
setSize(size - file.size)
}
fun removeFolder(dir: RemoteDirectory) {
val subdirList = subdirs.toMutableList()
subdirList.remove(dir)
subdirs = subdirList.toTypedArray()
}
companion object {
/**
* Converts an obtained JSON object.
*
* @param json JSON object that represents the folder.
* @return Representative object.
*/
fun fromJSON(json: JSONObject): RemoteDirectory {
// First create the directory object that we will return
val directory = RemoteDirectory(
json.getString("name"),
json.getString("path"),
json.getLong("size"),
emptyArray(),
emptyArray(),
null
)
// Get any items that the folder may contain
val items = json.getJSONArray("items")
val numItems = items.length()
val subdirs = ArrayList<RemoteDirectory>()
val files = ArrayList<RemoteFile>()
var item: JSONObject
var itemType: String
for (i in 0..<numItems) {
item = items.getJSONObject(i)
itemType = item.getString("type")
if (itemType == "file") {
val file = RemoteFile.fromJSON(item)
file.parentDir = directory
files.add(file)
} else {
val subdir = fromJSON(item)
subdir.parentDir = directory
subdirs.add(subdir)
}
}
// Finally we can update the arrays for the files and subdirectories
directory.files = files.toTypedArray()
directory.subdirs = subdirs.toTypedArray()
return directory
}
}
}
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/data/RemoteItems.kt
|
1676759486
|
/*
* Copyright (c) 2024 PhotonicGluon.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package site.overwrite.encryptedfilesapp.data
import site.overwrite.encryptedfilesapp.file.Pathing
import java.io.File
import java.math.RoundingMode
enum class FileUnit(val symbol: String, val value: Long) {
UNIT("B", 1),
KILOBYTE("KB", 1_000),
MEGABYTE("MB", 1_000_000),
GIGABYTE("GB", 1_000_000_000),
KIBIBYTE("KiB", 1_024),
MEBIBYTE("MiB", 1_048_576), // 1024^2
GIBIBYTE("GiB", 1_073_741_824); // 1024^3
companion object {
/**
* Chooses the appropriate file unit for formatting the file size.
*
* @param rawSize Raw file size.
* @param altUnits Use IEC 80000-13:2008 format instead of SI format (i.e., kibibytes,
* mebibytes, gibibytes instead of kilobytes, megabytes, gigabytes)
*/
fun chooseUnit(rawSize: Long, altUnits: Boolean = false): FileUnit {
if (altUnits) {
if (rawSize >= GIBIBYTE.value) {
return GIBIBYTE
}
if (rawSize >= MEBIBYTE.value) {
return MEBIBYTE
}
if (rawSize >= KIBIBYTE.value) {
return KIBIBYTE
}
return UNIT
} else {
if (rawSize >= GIGABYTE.value) {
return GIGABYTE
}
if (rawSize >= MEGABYTE.value) {
return MEGABYTE
}
if (rawSize >= KILOBYTE.value) {
return KILOBYTE
}
return UNIT
}
}
}
}
class FileSizeUtils {
companion object {
/**
* Gets the size of the item at the specified path.
*
* @param itemPath Path to the item. Assumed to be valid.
* @return Size of the item.
*/
fun getItemSize(itemPath: String): Long {
return File(Pathing.getItemPath(itemPath)).length()
}
/**
* Nicely formats the file size.
*
* @param rawSize Size of the item as a long.
* @param precision Number of decimal places to format the file size.
* @return Formatted file size.
*/
fun formatFileSize(rawSize: Long, precision: Int = 2): String {
if (rawSize < 0) return "0 B"
val unit = FileUnit.chooseUnit(rawSize, altUnits = false)
val roundedSize = if (unit == FileUnit.UNIT) {
rawSize.toBigDecimal()
} else {
val reducedSize = rawSize.toBigDecimal().divide(unit.value.toBigDecimal())
reducedSize.setScale(precision, RoundingMode.HALF_EVEN)
}
return "$roundedSize ${unit.symbol}"
}
}
}
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/data/FileSizeUtils.kt
|
3421497808
|
/*
* Copyright (c) 2024 PhotonicGluon.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package site.overwrite.encryptedfilesapp.data
import java.io.Serializable
data class Credentials(
var serverURL: String = "",
var username: String = "",
var password: String = ""
) : Serializable {
fun checkCredentialsIsEmpty(): CredentialCheckResult {
if (serverURL.isBlank()) {
return CredentialCheckResult.INVALID_URL
}
if (username.isBlank()) {
return CredentialCheckResult.INVALID_USERNAME
}
if (password.isEmpty()) {
return CredentialCheckResult.INVALID_PASSWORD
}
return CredentialCheckResult.VALID
}
}
enum class CredentialCheckResult {
PENDING,
TIMEOUT,
INVALID_URL,
INVALID_USERNAME,
INVALID_PASSWORD,
VALID
}
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/data/Credentials.kt
|
3365498311
|
package sq.mayv.aegyptus
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("sq.mayv.aegyptus", appContext.packageName)
}
}
|
Aegyptus/app/src/androidTest/java/sq/mayv/aegyptus/ExampleInstrumentedTest.kt
|
1997343561
|
package sq.mayv.aegyptus
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
|
Aegyptus/app/src/test/java/sq/mayv/aegyptus/ExampleUnitTest.kt
|
45214637
|
package sq.mayv.aegyptus.dto
import com.google.gson.annotations.SerializedName
data class SavePlace(
@SerializedName("id") val placeId: Int
)
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/dto/SavePlace.kt
|
3272565182
|
package sq.mayv.aegyptus.dto
class SignUpDto(
val email: String,
val name: String,
val password: String
)
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/dto/SignUpDto.kt
|
1231349176
|
package sq.mayv.aegyptus.dto
class SignInDto(
val email: String,
val password: String
)
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/dto/SignInDto.kt
|
879767589
|
package sq.mayv.aegyptus.ui.navigation
import androidx.compose.animation.AnimatedContentTransitionScope
import androidx.compose.animation.core.tween
import androidx.compose.runtime.Composable
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.navigation
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import sq.mayv.aegyptus.ui.screens.main.MainScreen
import sq.mayv.aegyptus.ui.screens.place.PlaceScreen
import sq.mayv.aegyptus.ui.screens.recover_password.RecoverPasswordScreen
import sq.mayv.aegyptus.ui.screens.search.SearchScreen
import sq.mayv.aegyptus.ui.screens.signin.SignInScreen
import sq.mayv.aegyptus.ui.screens.signup.SignUpScreen
import sq.mayv.aegyptus.ui.screens.welcome.WelcomeScreen
@Composable
fun AppNavigation(startDestination: String = AppScreens.WelcomeScreen.name) {
val navigationController = rememberNavController()
val transitionSpeed = 300
NavHost(navController = navigationController, startDestination = startDestination) {
navigation(
startDestination = AppScreens.SignInScreen.name,
route = "Auth"
) {
composable(
AppScreens.SignInScreen.name,
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(transitionSpeed)
)
}, exitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(transitionSpeed)
)
}, popEnterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(transitionSpeed)
)
}, popExitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(transitionSpeed)
)
}) {
SignInScreen(navController = navigationController)
}
composable(
AppScreens.RecoverPasswordScreen.name,
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(transitionSpeed)
)
}, exitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(transitionSpeed)
)
}, popEnterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(transitionSpeed)
)
}, popExitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(transitionSpeed)
)
}) {
RecoverPasswordScreen(navController = navigationController)
}
composable(
AppScreens.SignUpScreen.name,
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(transitionSpeed)
)
}, exitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(transitionSpeed)
)
}, popEnterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(transitionSpeed)
)
}, popExitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(transitionSpeed)
)
}) {
SignUpScreen(navController = navigationController)
}
}
composable(
AppScreens.WelcomeScreen.name,
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(transitionSpeed)
)
}, exitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(transitionSpeed)
)
}, popEnterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(transitionSpeed)
)
}, popExitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(transitionSpeed)
)
}) {
WelcomeScreen(navController = navigationController)
}
navigation(
startDestination = AppScreens.MainScreen.name,
route = "Main"
) {
composable(
AppScreens.MainScreen.name,
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(transitionSpeed)
)
}, exitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(transitionSpeed)
)
}, popEnterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(transitionSpeed)
)
}, popExitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(transitionSpeed)
)
}) {
MainScreen(rootNavController = navigationController)
}
}
composable(
AppScreens.PlaceScreen.name.plus("{placeId}"),
arguments = listOf(navArgument("placeId") { type = NavType.IntType }),
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(transitionSpeed)
)
}, exitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(transitionSpeed)
)
}, popEnterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(transitionSpeed)
)
}, popExitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(transitionSpeed)
)
}) {
val placeId = it.arguments?.getInt("placeId") ?: 4
PlaceScreen(navController = navigationController, placeId = placeId)
}
composable(
AppScreens.SearchScreen.name.plus("{searchQuery}"),
arguments = listOf(navArgument("searchQuery") { type = NavType.StringType }),
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(transitionSpeed)
)
}, exitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(transitionSpeed)
)
}, popEnterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(transitionSpeed)
)
}, popExitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(transitionSpeed)
)
}) {
val searchQuery = it.arguments?.getString("searchQuery") ?: ""
SearchScreen(navController = navigationController, searchQuery = searchQuery)
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/navigation/AppNavigation.kt
|
3658354881
|
package sq.mayv.aegyptus.ui.navigation
enum class AppScreens {
Auth,
Main,
WelcomeScreen,
PlaceScreen,
SearchScreen,
HomeScreen,
MainScreen,
SignInScreen,
SignUpScreen,
RecoverPasswordScreen;
companion object {
fun fromRoute(route: String): AppScreens = when (route.substringBefore('/')) {
SignInScreen.name -> SignInScreen
SignUpScreen.name -> SignUpScreen
HomeScreen.name -> HomeScreen
WelcomeScreen.name -> WelcomeScreen
else -> throw IllegalArgumentException("Route $route is not Recognised.")
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/navigation/AppScreens.kt
|
3998699120
|
package sq.mayv.aegyptus.ui.screens.home
import android.content.SharedPreferences
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.mayv.ctgate.data.Resource
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import sq.mayv.aegyptus.model.Category
import sq.mayv.aegyptus.model.Coordinates
import sq.mayv.aegyptus.model.Place
import sq.mayv.aegyptus.repository.CategoriesRepository
import sq.mayv.aegyptus.repository.FavoritesRepository
import sq.mayv.aegyptus.repository.PlacesRepository
import sq.mayv.aegyptus.ui.screens.home.viewstate.CategoriesViewState
import sq.mayv.aegyptus.ui.screens.home.viewstate.PlacesViewState
import sq.mayv.aegyptus.usecase.LocationUseCase
import sq.mayv.aegyptus.util.CategoryItem
import sq.mayv.aegyptus.util.PreferenceHelper.nearbyThreshold
import sq.mayv.aegyptus.util.PreferenceHelper.token
import javax.inject.Inject
@HiltViewModel
class HomeViewModel @Inject constructor(
private val placesRepository: PlacesRepository,
private val favoritesRepository: FavoritesRepository,
private val categoriesRepository: CategoriesRepository,
private val preferences: SharedPreferences,
private val locationUseCase: LocationUseCase
) :
ViewModel() {
private val _nearbyViewState: MutableStateFlow<PlacesViewState> =
MutableStateFlow(PlacesViewState.Loading)
val nearbyViewState = _nearbyViewState.asStateFlow()
private val _mostVisitedViewState: MutableStateFlow<PlacesViewState> =
MutableStateFlow(PlacesViewState.Loading)
val mostVisitedViewState = _mostVisitedViewState.asStateFlow()
private val _categoriesViewState: MutableStateFlow<CategoriesViewState> =
MutableStateFlow(CategoriesViewState.Loading)
val categoriesViewState = _categoriesViewState.asStateFlow()
private val _nearbyData = MutableStateFlow(Resource<List<Place>>())
private val _mostVisitedData = MutableStateFlow(Resource<List<Place>>())
private val _categoriesData = MutableStateFlow(Resource<List<Category>>())
var isAddingFavorite by mutableStateOf(false)
var addedSuccessfuly by mutableStateOf(false)
var isRemovingFavorite by mutableStateOf(false)
var removedSuccessfuly by mutableStateOf(false)
fun getNearbyPlaces() {
viewModelScope.launch(Dispatchers.IO) {
if (_nearbyViewState.value != PlacesViewState.Loading) {
_nearbyViewState.value = PlacesViewState.Loading
}
locationUseCase.invoke().collect { latLng ->
if (_nearbyViewState.value != PlacesViewState.Loading) {
_nearbyViewState.value = PlacesViewState.Loading
}
_nearbyData.value =
placesRepository.getNearbyPlaces(
coordinates = Coordinates(latLng?.latitude ?: 0.00, latLng?.longitude ?: 0.00),
maxDistance = preferences.nearbyThreshold,
authToken = preferences.token
)
val statusCode = _nearbyData.value.statusCode
val isNearbySuccessful = statusCode == 200 || statusCode == 201
if (!isNearbySuccessful) {
_nearbyViewState.value = PlacesViewState.Failure
} else {
_nearbyViewState.value =
PlacesViewState.Success(_nearbyData.value.data ?: listOf())
}
}
}
}
fun getMostVisitedPlaces() {
viewModelScope.launch(Dispatchers.IO) {
if (_mostVisitedViewState.value != PlacesViewState.Loading) {
_mostVisitedViewState.value = PlacesViewState.Loading
}
_mostVisitedData.value =
placesRepository.getMostVisitedPlaces(preferences.token)
val statusCode = _mostVisitedData.value.statusCode
val isMostVisitedSuccessful = statusCode == 200 || statusCode == 201
if (!isMostVisitedSuccessful) {
_mostVisitedViewState.value = PlacesViewState.Failure
} else {
_mostVisitedViewState.value =
PlacesViewState.Success(_mostVisitedData.value.data ?: listOf())
}
}
}
fun getCategories() {
viewModelScope.launch(Dispatchers.IO) {
if (_categoriesViewState.value != CategoriesViewState.Loading) {
_categoriesViewState.value = CategoriesViewState.Loading
}
_categoriesData.value =
categoriesRepository.getAll()
val statusCode = _categoriesData.value.statusCode
val isCategoriesSuccessful = statusCode == 200 || statusCode == 201
if (!isCategoriesSuccessful) {
_categoriesViewState.value = CategoriesViewState.Failure
} else {
_categoriesViewState.value =
CategoriesViewState.Success(
CategoryItem.getCategoryItems(
_categoriesData.value.data ?: listOf()
)
)
}
}
}
fun addToFavorites(placeId: Int) {
viewModelScope.launch(Dispatchers.IO) {
isAddingFavorite = true
val value = favoritesRepository.addToFavorite(placeId, preferences.token)
val statusCode = value.statusCode
addedSuccessfuly = statusCode == 200 || statusCode == 201
isAddingFavorite = false
}
}
fun removeFromFavorites(placeId: Int) {
viewModelScope.launch(Dispatchers.IO) {
isRemovingFavorite = true
val value = favoritesRepository.removeFromFavorites(placeId, preferences.token)
val statusCode = value.statusCode
removedSuccessfuly = statusCode == 200 || statusCode == 201
isRemovingFavorite = false
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/home/HomeViewModel.kt
|
1785906253
|
package sq.mayv.aegyptus.ui.screens.home.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
import sq.mayv.aegyptus.extension.shimmer
@Composable
fun HomePlacesListShimmer() {
Column(
modifier = Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(15.dp)
) {
Box(
modifier = Modifier
.padding(horizontal = 15.dp)
.height(30.dp)
.width(90.dp)
.clip(RoundedCornerShape(5.dp))
.shimmer(),
)
LazyRow(
userScrollEnabled = false
) {
items(4) {
Box(
modifier = Modifier
.padding(horizontal = 8.dp)
.width(230.dp)
.height(190.dp)
.clip(RoundedCornerShape(10.dp))
.shimmer()
)
}
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/home/components/HomePlacesListShimmer.kt
|
3051325130
|
package sq.mayv.aegyptus.ui.screens.home.components
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.core.EaseIn
import androidx.compose.animation.core.EaseOut
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
import com.bumptech.glide.integration.compose.GlideImage
import sq.mayv.aegyptus.R
import sq.mayv.aegyptus.model.Place
@OptIn(ExperimentalGlideComposeApi::class)
@Composable
fun HomePlacesListItem(
place: Place,
onItemClick: (Int) -> Unit,
onSaveClick: (Int, Boolean) -> Unit
) {
var isFavorite by remember { mutableStateOf(place.isFavorite) }
Card(
modifier = Modifier
.padding(horizontal = 8.dp)
.width(230.dp)
.height(190.dp)
.clickable {
onItemClick(place.id)
},
shape = RoundedCornerShape(10.dp),
colors = CardDefaults.cardColors(
containerColor = Color.White
),
elevation = CardDefaults.cardElevation(15.dp)
) {
Column {
Box {
Card(
modifier = Modifier
.fillMaxWidth()
.height(130.dp),
shape = RoundedCornerShape(10.dp)
) {
val split = place.images.split('|')
GlideImage(
model = split[0],
contentDescription = "",
contentScale = ContentScale.Crop
)
}
IconButton(
modifier = Modifier.align(Alignment.TopEnd),
onClick = {
onSaveClick(place.id, isFavorite)
isFavorite = !isFavorite
}
) {
Card(
modifier = Modifier
.size(26.dp),
shape = RoundedCornerShape(5.dp),
colors = CardDefaults.cardColors(
containerColor = Color.White
),
) {
AnimatedContent(
targetState = isFavorite,
label = "",
transitionSpec = {
fadeIn(
animationSpec = tween(250, easing = EaseIn)
).togetherWith(
fadeOut(
animationSpec = tween(250, easing = EaseOut)
)
)
}
) { condition ->
Box(modifier = Modifier.fillMaxSize()) {
Icon(
modifier = Modifier.align(Alignment.Center),
painter = if (condition) painterResource(id = R.drawable.ic_heart_filled) else painterResource(
id = R.drawable.ic_heart
),
contentDescription = "",
tint = if (condition) Color.Red else colorResource(id = R.color.primary)
)
}
}
}
}
}
Text(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 5.dp),
text = place.name,
color = Color.Black,
textAlign = TextAlign.Center,
fontSize = 12.sp,
overflow = TextOverflow.Ellipsis
)
if (place.distanceInMeters != -1) {
Text(
modifier = Modifier.fillMaxWidth(),
text = "${place.distanceInMeters} meters away",
color = colorResource(id = R.color.orange),
textAlign = TextAlign.Center,
fontSize = 12.sp
)
}
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/home/components/HomePlacesListItem.kt
|
4236892442
|
package sq.mayv.aegyptus.ui.screens.home.components
import androidx.annotation.DrawableRes
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Icon
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import sq.mayv.aegyptus.R
@Composable
fun CategoriesListItem(@DrawableRes icon: Int, title: String) {
Card(
modifier = Modifier
.padding(horizontal = 8.dp)
.size(100.dp),
shape = RoundedCornerShape(10.dp),
colors = CardDefaults.cardColors(
containerColor = Color.White
),
elevation = CardDefaults.cardElevation(15.dp)
) {
Column {
Box(
modifier = Modifier
.fillMaxWidth()
.height(70.dp),
) {
Icon(
modifier = Modifier
.align(Alignment.Center)
.size(38.dp),
painter = painterResource(id = icon),
contentDescription = "",
tint = colorResource(id = R.color.primary)
)
}
Text(
modifier = Modifier.fillMaxWidth(),
text = title,
color = Color.Black,
textAlign = TextAlign.Center,
fontSize = 12.sp
)
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/home/components/CategoriesListItem.kt
|
2313901962
|
package sq.mayv.aegyptus.ui.screens.home.components
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.core.EaseIn
import androidx.compose.animation.core.EaseOut
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import sq.mayv.aegyptus.components.OutlinedMessageView
import sq.mayv.aegyptus.model.Place
@Composable
fun HomePlacesListView(
places: List<Place>,
emptyMessage: String,
onItemClick: (Int) -> Unit,
onSaveClick: (Int, Boolean) -> Unit
) {
AnimatedContent(
targetState = places.isEmpty(),
label = "",
transitionSpec = {
fadeIn(
animationSpec = tween(600, easing = EaseIn)
).togetherWith(
fadeOut(
animationSpec = tween(600, easing = EaseOut)
)
)
}
) {isEmpty ->
if(!isEmpty) {
LazyRow {
items(items = places, key = { it.id }) { place ->
HomePlacesListItem(
place = place,
onItemClick = { onItemClick(it) },
onSaveClick = { id, isFavorite ->
place.isFavorite = !place.isFavorite
onSaveClick(id, isFavorite)
}
)
}
}
} else {
OutlinedMessageView(message = emptyMessage)
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/home/components/HomePlacesListView.kt
|
2267484968
|
package sq.mayv.aegyptus.ui.screens.home.components
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import sq.mayv.aegyptus.util.CategoryItem
@Composable
fun CategoriesListView(categories: List<CategoryItem>) {
LazyRow(
modifier = Modifier.fillMaxWidth(),
contentPadding = PaddingValues(bottom = 100.dp)
) {
items(items = categories) { category ->
CategoriesListItem(category.icon, category.title)
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/home/components/CategoriesListView.kt
|
2818687270
|
package sq.mayv.aegyptus.ui.screens.home.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
import sq.mayv.aegyptus.extension.shimmer
@Composable
fun CategoriesListShimmer() {
Column(
modifier = Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(15.dp)
) {
Box(
modifier = Modifier
.padding(horizontal = 15.dp)
.height(30.dp)
.width(120.dp)
.clip(RoundedCornerShape(5.dp))
.shimmer(),
)
LazyRow(
userScrollEnabled = false
) {
items(4) {
Box(
modifier = Modifier
.padding(horizontal = 8.dp)
.size(100.dp)
.clip(RoundedCornerShape(10.dp))
.shimmer()
)
}
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/home/components/CategoriesListShimmer.kt
|
1974336455
|
package sq.mayv.aegyptus.ui.screens.home
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.core.EaseIn
import androidx.compose.animation.core.EaseOut
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import sq.mayv.aegyptus.components.OutlinedMessageView
import sq.mayv.aegyptus.components.SearchTextField
import sq.mayv.aegyptus.ui.navigation.AppScreens
import sq.mayv.aegyptus.ui.screens.home.components.CategoriesListShimmer
import sq.mayv.aegyptus.ui.screens.home.components.CategoriesListView
import sq.mayv.aegyptus.ui.screens.home.components.HomePlacesListShimmer
import sq.mayv.aegyptus.ui.screens.home.components.HomePlacesListView
import sq.mayv.aegyptus.ui.screens.home.viewstate.CategoriesViewState
import sq.mayv.aegyptus.ui.screens.home.viewstate.PlacesViewState
@Composable
fun HomeScreen(
navController: NavController,
viewModel: HomeViewModel = hiltViewModel(),
rootNavController: NavController
) {
LaunchedEffect(key1 = true) {
viewModel.getNearbyPlaces()
viewModel.getMostVisitedPlaces()
viewModel.getCategories()
}
val nearbyViewState by viewModel.nearbyViewState.collectAsStateWithLifecycle()
val mostVisitedViewState by viewModel.mostVisitedViewState.collectAsStateWithLifecycle()
val categoriesViewState by viewModel.categoriesViewState.collectAsStateWithLifecycle()
var searchQuery by remember { mutableStateOf("") }
var trailingIconVisibility by remember { mutableStateOf(false) }
Surface(
modifier = Modifier.fillMaxSize(),
color = Color.White
) {
Column(
modifier = Modifier
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.padding(top = 30.dp),
verticalArrangement = Arrangement.spacedBy(35.dp)
) {
SearchTextField(
modifier = Modifier
.padding(horizontal = 25.dp)
.fillMaxWidth(),
search = searchQuery,
trailingIconVisibility = trailingIconVisibility,
onValueChange = { value ->
searchQuery = value
if (searchQuery.isNotEmpty()) {
if (!trailingIconVisibility) {
trailingIconVisibility = true
}
} else {
trailingIconVisibility = false
}
},
onSearchClick = {
rootNavController.navigate(AppScreens.SearchScreen.name.plus(searchQuery))
},
onTrailingIconClick = {
searchQuery = ""
trailingIconVisibility = false
}
)
AnimatedContent(
targetState = nearbyViewState,
label = "Shimmer Transition",
transitionSpec = {
fadeIn(
animationSpec = tween(600, easing = EaseIn)
).togetherWith(
fadeOut(
animationSpec = tween(600, easing = EaseOut)
)
)
}
) { viewState ->
when (viewState) {
PlacesViewState.Loading -> {
HomePlacesListShimmer()
}
PlacesViewState.Failure -> {
OutlinedMessageView(
message = "Failed to load nearby places!",
textColor = Color.Red,
outline = BorderStroke(1.dp, Color.Red)
)
}
is PlacesViewState.Success -> {
Column(
modifier = Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(15.dp)
) {
Text(
modifier = Modifier
.padding(horizontal = 15.dp),
text = "Nearby",
fontSize = 22.sp,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center,
)
HomePlacesListView(
places = viewState.places,
emptyMessage = "There is no nearby places to your location, try increasing the nearby threshold from the settings.",
onItemClick = {
rootNavController.navigate(AppScreens.PlaceScreen.name.plus(it))
},
onSaveClick = { id, isFavorite ->
if (!viewModel.isAddingFavorite && !viewModel.isRemovingFavorite) {
if (!isFavorite) {
viewModel.addToFavorites(id)
} else {
viewModel.removeFromFavorites(id)
}
}
}
)
}
}
}
}
AnimatedContent(
targetState = mostVisitedViewState,
label = "Shimmer Transition",
transitionSpec = {
fadeIn(
animationSpec = tween(600, easing = EaseIn)
).togetherWith(
fadeOut(
animationSpec = tween(600, easing = EaseOut)
)
)
}
) { viewState ->
when (viewState) {
PlacesViewState.Loading -> {
HomePlacesListShimmer()
}
PlacesViewState.Failure -> {
OutlinedMessageView(
message = "Failed to load most visited places!",
textColor = Color.Red,
outline = BorderStroke(1.dp, Color.Red)
)
}
is PlacesViewState.Success -> {
Column(
modifier = Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(15.dp)
) {
Text(
modifier = Modifier
.padding(horizontal = 15.dp),
text = "Most Visited",
fontSize = 22.sp,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center,
)
HomePlacesListView(
places = viewState.places,
emptyMessage = "We haven't added most visited places to your governorate yet.",
onItemClick = {
rootNavController.navigate(AppScreens.PlaceScreen.name.plus(it))
},
onSaveClick = { id, isFavorite ->
if (!viewModel.isAddingFavorite && !viewModel.isRemovingFavorite) {
if (!isFavorite) {
viewModel.addToFavorites(id)
} else {
viewModel.removeFromFavorites(id)
}
}
}
)
}
}
}
}
AnimatedContent(
targetState = categoriesViewState,
label = "Shimmer Transition",
transitionSpec = {
fadeIn(
animationSpec = tween(600, easing = EaseIn)
).togetherWith(
fadeOut(
animationSpec = tween(600, easing = EaseOut)
)
)
}
) { viewState ->
when (viewState) {
CategoriesViewState.Loading -> {
CategoriesListShimmer()
}
CategoriesViewState.Failure -> {
OutlinedMessageView(
message = "Failed to load categories!",
textColor = Color.Red,
outline = BorderStroke(1.dp, Color.Red)
)
}
is CategoriesViewState.Success -> {
Column(
modifier = Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(15.dp)
) {
Text(
modifier = Modifier
.padding(horizontal = 15.dp),
text = "Categories",
fontSize = 22.sp,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center,
)
CategoriesListView(categories = viewState.categories)
}
}
}
}
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/home/HomeScreen.kt
|
3518579734
|
package sq.mayv.aegyptus.ui.screens.home.viewstate
import sq.mayv.aegyptus.model.Place
sealed interface PlacesViewState {
data object Loading : PlacesViewState
data class Success(val places: List<Place>) : PlacesViewState
data object Failure : PlacesViewState
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/home/viewstate/PlacesViewState.kt
|
3412834661
|
package sq.mayv.aegyptus.ui.screens.home.viewstate
import sq.mayv.aegyptus.util.CategoryItem
sealed interface CategoriesViewState {
data object Loading : CategoriesViewState
data class Success(val categories: List<CategoryItem>) : CategoriesViewState
data object Failure : CategoriesViewState
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/home/viewstate/CategoriesViewState.kt
|
2508115762
|
package sq.mayv.aegyptus.ui.screens.splash
import android.content.SharedPreferences
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import sq.mayv.aegyptus.ui.navigation.AppScreens
import sq.mayv.aegyptus.util.PreferenceHelper.firstLaunch
import sq.mayv.aegyptus.util.PreferenceHelper.token
import javax.inject.Inject
@HiltViewModel
class SplashViewModel @Inject constructor(preferences: SharedPreferences) : ViewModel() {
private val _isLoading: MutableState<Boolean> = mutableStateOf(true)
val isLoading: State<Boolean> = _isLoading
private val _startDestination: MutableState<String> =
mutableStateOf(AppScreens.WelcomeScreen.name)
val startDestination: State<String> = _startDestination
init {
if (!preferences.firstLaunch) {
if (preferences.token.isNotEmpty()) {
_startDestination.value = AppScreens.Main.name
} else {
_startDestination.value = AppScreens.Auth.name
}
} else {
preferences.firstLaunch = false
}
_isLoading.value = false
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/splash/SplashViewModel.kt
|
2199594249
|
package sq.mayv.aegyptus.ui.screens.signup
import android.util.Patterns
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import sq.mayv.aegyptus.R
import sq.mayv.aegyptus.components.PasswordTextInputField
import sq.mayv.aegyptus.components.TextInputField
import sq.mayv.aegyptus.components.TopBarTitleArrow
import sq.mayv.aegyptus.dto.SignUpDto
import sq.mayv.aegyptus.ui.navigation.AppScreens
import sq.mayv.aegyptus.ui.screens.signup.components.SignupBottomBar
import java.util.regex.Pattern
@Composable
fun SignUpScreen(
navController: NavController,
viewModel: SignUpViewModel = hiltViewModel()
) {
val coroutineScope = rememberCoroutineScope()
var name by remember { mutableStateOf("") }
var nameMessage by remember { mutableStateOf("Please enter your name") }
var nameMessageVisibility by remember { mutableStateOf(false) }
var email by remember { mutableStateOf("") }
var emailMessage by remember { mutableStateOf("Please enter an email") }
var emailMessageVisibility by remember { mutableStateOf(false) }
var password by remember { mutableStateOf("") }
var passwordMessage by remember { mutableStateOf("Please enter a password") }
var passwordMessageVisibility by remember { mutableStateOf(false) }
var confirmPassword by remember { mutableStateOf("") }
var confirmPasswordMessage by remember { mutableStateOf("Please confirm your password ") }
var confirmPasswordMessageVisibility by remember { mutableStateOf(false) }
val data by viewModel.signUpData.collectAsState()
var signInClicked by remember { mutableStateOf(false) }
LaunchedEffect(key1 = data.statusCode) {
if (viewModel.isSignUpSuccessful) {
navController.popBackStack()
navController.navigate(AppScreens.Main.name)
}
}
Scaffold(
modifier = Modifier.fillMaxSize(),
topBar = {
TopBarTitleArrow(
navController = navController,
title = "Sign Up",
)
},
bottomBar = {
SignupBottomBar(
isLoading = viewModel.isSignUpLoading,
onSignUpClick = {
coroutineScope.launch(Dispatchers.IO) {
if (!viewModel.isSignUpLoading) {
if (name.isNotEmpty() || email.isNotEmpty() || password.isNotEmpty() || confirmPassword.isNotEmpty()) {
if (!isEmailValid(email) || !isPasswordValid(password)) {
if (!isEmailValid(email)) {
emailMessage = "The email you entered is not valid"
emailMessageVisibility = true
}
if (!isPasswordValid(password)) {
passwordMessage =
"Must have at least one uppercase character.\nMust have at least one number.\nMust be at least 8 characters."
passwordMessageVisibility = true
}
} else {
if (password != confirmPassword) {
confirmPasswordMessage = "Passwords do not match"
confirmPasswordMessageVisibility = true
} else {
val body =
SignUpDto(
name = name,
email = email,
password = password
)
viewModel.signUp(body = body)
}
}
} else {
if (name.isEmpty()) {
nameMessageVisibility = true
}
if (email.isEmpty()) {
emailMessageVisibility = true
}
if (password.isEmpty()) {
passwordMessageVisibility = true
}
if (confirmPassword.isEmpty()) {
confirmPasswordMessageVisibility = true
}
}
}
}
},
onLoginNowClick = {
if (!viewModel.isSignUpLoading) {
if (!signInClicked) {
signInClicked = true
navController.popBackStack()
}
}
}
)
}
) {
Column(
modifier = Modifier
.padding(it)
.padding(bottom = 35.dp)
.fillMaxSize()
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
TextInputField(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 35.dp, vertical = 15.dp),
value = name,
onValueChange = { value ->
name = value
if (nameMessage.isNotEmpty()) {
nameMessageVisibility = value == ""
}
},
label = "Name",
message = nameMessage,
messageModifier = Modifier
.fillMaxWidth()
.padding(horizontal = 35.dp),
messageVisibility = nameMessageVisibility,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Email,
autoCorrect = false
)
)
TextInputField(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 35.dp, vertical = 15.dp),
value = email,
onValueChange = { value ->
email = value
if (emailMessage.isNotEmpty()) {
emailMessageVisibility = value == ""
}
},
label = "Email",
message = emailMessage,
messageModifier = Modifier
.fillMaxWidth()
.padding(horizontal = 35.dp),
messageVisibility = emailMessageVisibility,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Email,
autoCorrect = false
)
)
PasswordTextInputField(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 35.dp, vertical = 15.dp),
value = password,
onValueChange = { value ->
password = value
if (passwordMessage.isNotEmpty()) {
passwordMessageVisibility = value == ""
}
},
label = "Password",
message = passwordMessage,
errorModifier = Modifier
.fillMaxWidth()
.padding(horizontal = 35.dp),
messageVisibility = passwordMessageVisibility
)
PasswordTextInputField(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 35.dp, vertical = 15.dp),
value = confirmPassword,
onValueChange = { value ->
confirmPassword = value
if (confirmPasswordMessage.isNotEmpty()) {
confirmPasswordMessageVisibility = value == ""
}
},
label = "Confirm Password",
message = confirmPasswordMessage,
errorModifier = Modifier
.fillMaxWidth()
.padding(horizontal = 35.dp),
messageVisibility = confirmPasswordMessageVisibility
)
Text(
text = if (data.statusCode in (400..500)) data.exception.message.toString() else "",
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 35.dp)
.padding(vertical = 25.dp)
.alpha(if (data.statusCode != 200 || data.statusCode != 201) 1f else 0f),
color = colorResource(id = R.color.gold),
textAlign = TextAlign.Center
)
}
}
}
private fun isEmailValid(email: String): Boolean {
return Patterns.EMAIL_ADDRESS.matcher(email).matches()
}
private fun isPasswordValid(password: String): Boolean {
// Must have at least one uppercase character.
// Must have at least one number.
// Must be at least 8 characters.
return Pattern.compile("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}\$")
.matcher(password).matches()
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/signup/SignUpScreen.kt
|
3657868057
|
package sq.mayv.aegyptus.ui.screens.signup.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.Divider
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import sq.mayv.aegyptus.components.LoadingRoundedButton
import sq.mayv.aegyptus.components.OutlinedRoundedButton
@Composable
fun SignupBottomBar(
isLoading: Boolean = false,
onSignUpClick: () -> Unit,
onLoginNowClick: () -> Unit
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 25.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(15.dp)
) {
LoadingRoundedButton(
modifier = Modifier
.fillMaxWidth()
.height(45.dp)
.padding(horizontal = 35.dp),
text = "Sign Up",
fontSize = 18,
isLoading = isLoading
) {
onSignUpClick()
}
Row(verticalAlignment = Alignment.CenterVertically) {
Divider(modifier = Modifier.width(70.dp), color = Color.LightGray)
Text(text = "or", modifier = Modifier.padding(horizontal = 10.dp))
Divider(modifier = Modifier.width(70.dp), color = Color.LightGray)
}
OutlinedRoundedButton(
modifier = Modifier
.fillMaxWidth()
.height(45.dp)
.padding(horizontal = 35.dp),
text = "Already a member? Login now",
fontSize = 14
) {
onLoginNowClick()
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/signup/components/SignupBottomBar.kt
|
3954192847
|
package sq.mayv.aegyptus.ui.screens.signup
import android.content.SharedPreferences
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.mayv.ctgate.data.Resource
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import sq.mayv.aegyptus.dto.SignUpDto
import sq.mayv.aegyptus.model.Auth
import sq.mayv.aegyptus.repository.AuthRepository
import sq.mayv.aegyptus.util.PreferenceHelper.token
import javax.inject.Inject
@HiltViewModel
class SignUpViewModel @Inject constructor(
private val authRepository: AuthRepository,
private val preferences: SharedPreferences
) :
ViewModel() {
private val _signUpData = MutableStateFlow(Resource<Auth>())
val signUpData: StateFlow<Resource<Auth>> = _signUpData
var isSignUpLoading by mutableStateOf(false)
var isSignUpSuccessful by mutableStateOf(false)
fun signUp(body: SignUpDto) {
viewModelScope.launch(Dispatchers.IO) {
isSignUpLoading = true
_signUpData.value = authRepository.signUp(body)
val statusCode = _signUpData.value.statusCode
if (statusCode == 200 || statusCode == 201) {
preferences.token = _signUpData.value.data!!.authorizationToken
isSignUpSuccessful = true
}
isSignUpLoading = false
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/signup/SignUpViewModel.kt
|
3676401983
|
package sq.mayv.aegyptus.ui.screens.favorites
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.core.EaseIn
import androidx.compose.animation.core.EaseOut
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import sq.mayv.aegyptus.ui.navigation.AppScreens
import sq.mayv.aegyptus.ui.screens.favorites.components.FavoritesErrorView
import sq.mayv.aegyptus.ui.screens.favorites.components.FavoritesListShimmer
import sq.mayv.aegyptus.ui.screens.favorites.components.FavoritesListView
import sq.mayv.aegyptus.ui.screens.favorites.viewstate.FavoritesViewState
@Composable
fun FavoritesScreen(
navController: NavController,
viewModel: FavoritesViewModel = hiltViewModel(),
rootNavController: NavController
) {
LaunchedEffect(key1 = true) {
viewModel.getAllFavorites()
}
val viewState by viewModel.viewState.collectAsStateWithLifecycle()
Surface(
modifier = Modifier.fillMaxSize(),
color = Color.White
) {
AnimatedContent(
targetState = viewState,
label = "",
transitionSpec = {
fadeIn(
animationSpec = tween(600, easing = EaseIn)
).togetherWith(
fadeOut(
animationSpec = tween(600, easing = EaseOut)
)
)
}
) {
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
when (it) {
FavoritesViewState.Loading -> {
FavoritesListShimmer()
}
FavoritesViewState.Failure -> {
FavoritesErrorView()
}
is FavoritesViewState.Success -> {
FavoritesListView(
favorites = it.places,
onItemClick = {
rootNavController.navigate(
AppScreens.PlaceScreen.name.plus(
it
)
)
}
)
}
}
}
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/favorites/FavoritesScreen.kt
|
2960701587
|
package sq.mayv.aegyptus.ui.screens.favorites.components
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.core.EaseIn
import androidx.compose.animation.core.EaseOut
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import sq.mayv.aegyptus.components.MessageView
import sq.mayv.aegyptus.model.Place
@Composable
fun FavoritesListView(
favorites: List<Place>,
onItemClick: (Int) -> Unit
) {
AnimatedContent(
targetState = favorites.isEmpty(),
label = "",
transitionSpec = {
fadeIn(
animationSpec = tween(600, easing = EaseIn)
).togetherWith(
fadeOut(
animationSpec = tween(600, easing = EaseOut)
)
)
}
) { isEmpty ->
if (!isEmpty) {
LazyColumn(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(15.dp),
contentPadding = PaddingValues(top = 15.dp, bottom = 90.dp),
) {
items(favorites, key = { it.id }) { favorite ->
FavoritesListItem(
favorite = favorite,
onItemClick = { onItemClick(it) }
)
}
}
} else {
MessageView(message = "You haven't added favorites yet.")
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/favorites/components/FavoritesListView.kt
|
2647050047
|
package sq.mayv.aegyptus.ui.screens.favorites.components
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
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.layout.ContentScale
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.PlatformTextStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
import com.bumptech.glide.integration.compose.GlideImage
import sq.mayv.aegyptus.R
import sq.mayv.aegyptus.model.Place
@OptIn(ExperimentalFoundationApi::class, ExperimentalGlideComposeApi::class)
@Composable
fun FavoritesListItem(
favorite: Place,
onItemClick: (Int) -> Unit
) {
val images = favorite.images.split('|')
val pagerState = rememberPagerState(initialPage = 0, pageCount = { images.size })
Box(
modifier = Modifier
.padding(horizontal = 15.dp)
.fillMaxWidth()
.height(150.dp)
.clickable {
onItemClick(favorite.id)
},
) {
Card(
modifier = Modifier
.padding(vertical = 10.dp)
.fillMaxSize(),
shape = RoundedCornerShape(topStart = 10.dp, bottomStart = 10.dp),
colors = CardDefaults.cardColors(
containerColor = Color.White
),
elevation = CardDefaults.cardElevation(15.dp)
) {
Column(
modifier = Modifier
.padding(start = 10.dp, end = 160.dp, bottom = 10.dp)
.fillMaxWidth()
) {
Text(
text = favorite.name,
fontSize = 14.sp,
color = Color.Black,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
text = favorite.about,
fontSize = 12.sp,
color = colorResource(id = R.color.description),
overflow = TextOverflow.Ellipsis,
style = TextStyle(
platformStyle = PlatformTextStyle(
includeFontPadding = false
)
)
)
}
}
Card(
modifier = Modifier
.size(150.dp)
.align(Alignment.CenterEnd),
shape = RoundedCornerShape(10.dp),
elevation = CardDefaults.cardElevation(15.dp)
) {
Surface {
HorizontalPager(
modifier = Modifier
.size(150.dp),
state = pagerState,
outOfBoundsPageCount = 1,
verticalAlignment = Alignment.Top
) { position ->
GlideImage(
modifier = Modifier.size(150.dp),
model = images[position],
contentDescription = "",
contentScale = ContentScale.Crop
)
}
// Pager Indicator
Row(
Modifier
.wrapContentHeight()
.fillMaxWidth()
.padding(vertical = 15.dp),
horizontalArrangement = Arrangement.Center
) {
repeat(pagerState.pageCount) { iteration ->
val width by animateDpAsState(
targetValue = if (pagerState.currentPage == iteration) 15.dp else 5.dp,
animationSpec = tween(
durationMillis = 100,
),
label = "Indicator Width Animation"
)
Box(
modifier = Modifier
.padding(3.dp)
.height(5.dp)
.width(width)
.clip(RoundedCornerShape(3.dp))
.background(colorResource(id = R.color.gold))
)
}
}
}
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/favorites/components/FavoritesListItem.kt
|
2137895442
|
package sq.mayv.aegyptus.ui.screens.favorites.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import sq.mayv.aegyptus.R
import sq.mayv.aegyptus.components.LottieAnimationView
@Composable
fun FavoritesErrorView() {
Column(
modifier = Modifier
.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Card(
modifier = Modifier
.width(300.dp)
.wrapContentHeight(),
shape = RoundedCornerShape(10.dp),
contentColor = Color.White,
elevation = 15.dp
) {
Column(
modifier = Modifier
.padding(vertical = 20.dp)
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
LottieAnimationView(
modifier = Modifier.size(200.dp),
lottie = R.raw.mummy,
iterateForEver = false
)
Text(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 15.dp),
text = "Failed to load data",
fontSize = 16.sp,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center,
color = Color.Red
)
}
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/favorites/components/FavoritesErrorView.kt
|
4227345087
|
package sq.mayv.aegyptus.ui.screens.favorites.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
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.unit.dp
import sq.mayv.aegyptus.extension.shimmer
@Composable
fun FavoritesListShimmer() {
Column(
modifier = Modifier.padding(top = 20.dp),
verticalArrangement = Arrangement.spacedBy(15.dp)
) {
repeat(4) {
Box(
modifier = Modifier
.padding(horizontal = 15.dp)
.fillMaxWidth()
.height(150.dp),
) {
Box(
modifier = Modifier
.padding(vertical = 10.dp)
.clip(RoundedCornerShape(topStart = 10.dp, bottomStart = 10.dp))
.fillMaxSize()
.shimmer(),
)
Card(
modifier = Modifier.align(Alignment.CenterEnd),
elevation = CardDefaults.cardElevation(15.dp)
) {
Box(
modifier = Modifier
.width(150.dp)
.height(150.dp)
.clip(RoundedCornerShape(10.dp))
.shimmer(),
)
}
}
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/favorites/components/FavoritesListShimmer.kt
|
1284813117
|
package sq.mayv.aegyptus.ui.screens.favorites.viewstate
import sq.mayv.aegyptus.model.Place
sealed interface FavoritesViewState {
data object Loading : FavoritesViewState
data class Success(val places: List<Place>) : FavoritesViewState
data object Failure : FavoritesViewState
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/favorites/viewstate/FavoritesViewState.kt
|
3110718813
|
package sq.mayv.aegyptus.ui.screens.favorites
import android.content.SharedPreferences
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.mayv.ctgate.data.Resource
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import sq.mayv.aegyptus.model.Place
import sq.mayv.aegyptus.repository.FavoritesRepository
import sq.mayv.aegyptus.ui.screens.favorites.viewstate.FavoritesViewState
import sq.mayv.aegyptus.util.PreferenceHelper.token
import javax.inject.Inject
@HiltViewModel
class FavoritesViewModel @Inject constructor(
private val favoritesRepository: FavoritesRepository,
private val preferences: SharedPreferences
) :
ViewModel() {
private val _viewState: MutableStateFlow<FavoritesViewState> =
MutableStateFlow(FavoritesViewState.Loading)
val viewState = _viewState.asStateFlow()
private val _favoritesData = MutableStateFlow(Resource<List<Place>>())
fun getAllFavorites() {
viewModelScope.launch(Dispatchers.IO) {
if (_viewState.value != FavoritesViewState.Loading) {
_viewState.value = FavoritesViewState.Loading
}
_favoritesData.value =
favoritesRepository.getAllFavorites(preferences.token)
val statusCode = _favoritesData.value.statusCode
val isSuccessful = statusCode == 200 || statusCode == 201
if(!isSuccessful) {
_viewState.value = FavoritesViewState.Failure
} else {
_viewState.value = FavoritesViewState.Success(_favoritesData.value.data ?: listOf())
}
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/favorites/FavoritesViewModel.kt
|
3525188884
|
package sq.mayv.aegyptus.ui.screens.recover_password
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import sq.mayv.aegyptus.components.LoadingRoundedButton
import sq.mayv.aegyptus.components.TextInputField
import sq.mayv.aegyptus.components.TopBarTitleArrow
@Composable
fun RecoverPasswordScreen(navController: NavController) {
val coroutineScope = rememberCoroutineScope()
var isLoading by remember { mutableStateOf(false) }
Scaffold(
modifier = Modifier.fillMaxSize(),
topBar = {
TopBarTitleArrow(
navController = navController,
title = "Recover Password"
)
},
bottomBar = {
Row(
modifier = Modifier
.fillMaxWidth()
.height(70.dp),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
LoadingRoundedButton(
modifier = Modifier
.fillMaxWidth()
.height(45.dp)
.padding(horizontal = 35.dp),
text = "Confirm",
fontSize = 18,
isLoading = isLoading
) {
coroutineScope.launch {
isLoading = true
delay(4000)
navController.popBackStack()
}
}
}
}
) {
Column(
modifier = Modifier
.padding(it)
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
) {
var email by remember { mutableStateOf("") }
var emailMessageVisibility by remember { mutableStateOf(false) }
TextInputField(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 35.dp, vertical = 25.dp),
value = email,
onValueChange = { value ->
email = value
emailMessageVisibility = value != ""
},
label = "Email",
message = "If this email exists in our database you will receive a password resetting link immediately.",
messageModifier = Modifier
.fillMaxWidth()
.padding(horizontal = 35.dp),
messageVisibility = emailMessageVisibility,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Email,
autoCorrect = false
)
)
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/recover_password/RecoverPasswordScreen.kt
|
2783313940
|
package sq.mayv.aegyptus.ui.screens.welcome
import androidx.compose.runtime.Composable
import androidx.navigation.NavController
import sq.mayv.aegyptus.ui.screens.welcome.components.WelcomeMainSurface
@Composable
fun WelcomeScreen(navController: NavController) {
WelcomeMainSurface(navController)
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/welcome/WelcomeScreen.kt
|
3698020128
|
package sq.mayv.aegyptus.ui.screens.welcome.components
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.pager.PagerState
import androidx.compose.material.ButtonDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.unit.dp
import sq.mayv.aegyptus.R
import sq.mayv.aegyptus.components.RoundedButton
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun PagerFinishButton(
modifier: Modifier,
pagesNum: Int,
pagerState: PagerState,
text: String,
fontSize: Int = 22,
onClicked: () -> Unit
) {
Row(
modifier = modifier
.padding(horizontal = 25.dp),
verticalAlignment = Alignment.Top,
horizontalArrangement = Arrangement.Center
) {
AnimatedVisibility(
modifier = Modifier.fillMaxWidth(),
visible = pagerState.currentPage == pagesNum - 1
) {
RoundedButton(
modifier = Modifier
.fillMaxWidth(),
onClicked = { onClicked() },
text = text,
fontSize = fontSize,
colors = ButtonDefaults.buttonColors(
backgroundColor = colorResource(id = R.color.primary),
contentColor = Color.White
)
)
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/welcome/components/PagerFinishButton.kt
|
1648286229
|
package sq.mayv.aegyptus.ui.screens.welcome.components
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.sp
import sq.mayv.aegyptus.R
@Composable
fun WelcomeTitleText(
modifier: Modifier = Modifier,
text: String,
color: Color = Color.White,
fontSize: Int = 18,
fontWeight: FontWeight = FontWeight.Normal,
textAlign: TextAlign = TextAlign.Center,
fontFamily: FontFamily = FontFamily(Font(R.font.egyptian_nights, FontWeight.Bold))
) {
Text(
modifier = modifier,
text = text,
color = color,
fontSize = fontSize.sp,
fontWeight = fontWeight,
textAlign = textAlign,
fontFamily = fontFamily
)
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/welcome/components/WelcomeTitleText.kt
|
297156229
|
package sq.mayv.aegyptus.ui.screens.welcome.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import sq.mayv.aegyptus.components.LottieAnimationView
import sq.mayv.aegyptus.util.OnboardingPage
@Composable
fun PagerScreen(onboardingPage: OnboardingPage) {
Column(
modifier = Modifier
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top
) {
LottieAnimationView(
modifier = Modifier
.fillMaxWidth(0.75f)
.fillMaxHeight(0.75f),
lottie = onboardingPage.lottie
)
WelcomeTitleText(
modifier = Modifier
.fillMaxWidth(),
text = onboardingPage.header,
color = Color.Black,
fontSize = 30,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center
)
Text(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 40.dp)
.padding(top = 20.dp),
text = onboardingPage.description,
fontSize = MaterialTheme.typography.subtitle1.fontSize,
fontWeight = FontWeight.Medium,
textAlign = TextAlign.Center
)
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/welcome/components/PagerScreen.kt
|
2840558127
|
package sq.mayv.aegyptus.ui.screens.welcome.components
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import sq.mayv.aegyptus.R
import sq.mayv.aegyptus.ui.navigation.AppScreens
import sq.mayv.aegyptus.util.OnboardingPage
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun WelcomeMainSurface(navController: NavController) {
val pages = listOf(
OnboardingPage.FirstPage,
OnboardingPage.ThirdPage,
OnboardingPage.SecondPage
)
val pagerState = rememberPagerState(initialPage = 0, pageCount = { pages.size })
Scaffold(
modifier = Modifier.fillMaxSize(),
bottomBar = {
Column(
modifier = Modifier
.fillMaxWidth()
.height(70.dp)
.padding(bottom = 15.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
PagerFinishButton(
modifier = Modifier
.fillMaxWidth(),
text = "Let's start exploring",
fontSize = 22,
pagesNum = pages.size,
pagerState = pagerState,
onClicked = {
navController.popBackStack()
navController.navigate(AppScreens.Auth.name)
}
)
}
},
) {
Column(
modifier = Modifier
.padding(it)
.fillMaxSize()
.verticalScroll(rememberScrollState())
) {
HorizontalPager(
modifier = Modifier
.padding(bottom = 25.dp)
.weight(10f),
state = pagerState,
verticalAlignment = Alignment.Top
) { position ->
PagerScreen(onboardingPage = pages[position])
}
// Pager Indicator
Row(
Modifier
.wrapContentHeight()
.fillMaxWidth()
.padding(vertical = 15.dp),
horizontalArrangement = Arrangement.Center
) {
repeat(pagerState.pageCount) { iteration ->
val width by animateDpAsState(
targetValue = if (pagerState.currentPage == iteration) 18.dp else 8.dp,
animationSpec = tween(
durationMillis = 100,
),
label = "Indicator Width Animation"
)
Box(
modifier = Modifier
.padding(3.dp)
.height(8.dp)
.width(width)
.clip(RoundedCornerShape(3.dp))
.background(colorResource(id = R.color.primary))
)
}
}
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/welcome/components/WelcomeMainSurface.kt
|
3979440617
|
package sq.mayv.aegyptus.ui.screens.search
import android.content.SharedPreferences
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.mayv.ctgate.data.Resource
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import sq.mayv.aegyptus.model.Category
import sq.mayv.aegyptus.model.Place
import sq.mayv.aegyptus.repository.CategoriesRepository
import sq.mayv.aegyptus.repository.FavoritesRepository
import sq.mayv.aegyptus.repository.PlacesRepository
import sq.mayv.aegyptus.util.PreferenceHelper.token
import javax.inject.Inject
@HiltViewModel
class SearchViewModel @Inject constructor(
private val placesRepository: PlacesRepository,
private val favoritesRepository: FavoritesRepository,
private val categoriesRepository: CategoriesRepository,
private val preferences: SharedPreferences
) :
ViewModel() {
private val _placesData = MutableStateFlow(Resource<List<Place>>())
val placesData: StateFlow<Resource<List<Place>>> = _placesData
var isLoading by mutableStateOf(true)
var isSuccessful by mutableStateOf(false)
private val _categoriesData = MutableStateFlow(Resource<List<Category>>())
val categoriesData: StateFlow<Resource<List<Category>>> = _categoriesData
var isCategoriesLoading by mutableStateOf(true)
var isCategoriesSuccessful by mutableStateOf(false)
var isAddingFavorite by mutableStateOf(false)
var addedSuccessfuly by mutableStateOf(false)
var isRemovingFavorite by mutableStateOf(false)
var removedSuccessfuly by mutableStateOf(false)
fun getAllCategories() {
viewModelScope.launch(Dispatchers.IO) {
if (!isCategoriesLoading) {
isCategoriesLoading = true
}
_categoriesData.value =
categoriesRepository.getAll()
val statusCode = _categoriesData.value.statusCode
isCategoriesSuccessful = statusCode == 200 || statusCode == 201
isCategoriesLoading = false
}
}
fun search(query: String) {
viewModelScope.launch(Dispatchers.IO) {
if (!isLoading) {
isLoading = true
}
_placesData.value =
placesRepository.search(query = query, authToken = preferences.token)
val statusCode = _placesData.value.statusCode
isSuccessful = statusCode == 200 || statusCode == 201
isLoading = false
}
}
fun addToFavorites(placeId: Int) {
viewModelScope.launch(Dispatchers.IO) {
isAddingFavorite = true
val value = favoritesRepository.addToFavorite(placeId, preferences.token)
val statusCode = value.statusCode
addedSuccessfuly = statusCode == 200 || statusCode == 201
isAddingFavorite = false
}
}
fun removeFromFavorites(placeId: Int) {
viewModelScope.launch(Dispatchers.IO) {
isRemovingFavorite = true
val value = favoritesRepository.removeFromFavorites(placeId, preferences.token)
val statusCode = value.statusCode
removedSuccessfuly = statusCode == 200 || statusCode == 201
isRemovingFavorite = false
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/search/SearchViewModel.kt
|
3810193383
|
package sq.mayv.aegyptus.ui.screens.search.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import sq.mayv.aegyptus.model.Place
@Composable
fun PlacesListView(
places: List<Place>,
onItemClick: (Int) -> Unit,
onSaveClick: (Int, Boolean) -> Unit
) {
LazyColumn(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(15.dp),
contentPadding = PaddingValues(top = 15.dp, bottom = 25.dp),
) {
items(places) { favorite ->
PlacesListItem(
place = favorite,
onItemClick = { onItemClick(it) },
onSaveClick = { placeId, isFavorite ->
onSaveClick(placeId, isFavorite)
}
)
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/search/components/PlacesListView.kt
|
485690226
|
package sq.mayv.aegyptus.ui.screens.search.components
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.core.EaseIn
import androidx.compose.animation.core.EaseOut
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
import com.bumptech.glide.integration.compose.GlideImage
import sq.mayv.aegyptus.R
import sq.mayv.aegyptus.model.Place
@OptIn(ExperimentalGlideComposeApi::class)
@Composable
fun PlacesListItem(
place: Place,
onItemClick: (Int) -> Unit,
onSaveClick: (Int, Boolean) -> Unit
) {
val image = place.images.split('|')[0]
var isFavorite by remember { mutableStateOf(place.isFavorite) }
Card(
modifier = Modifier
.padding(horizontal = 20.dp)
.fillMaxWidth()
.height(250.dp)
.clickable {
onItemClick(place.id)
},
shape = RoundedCornerShape(10.dp),
colors = CardDefaults.cardColors(
containerColor = Color.White
),
elevation = CardDefaults.cardElevation(15.dp)
) {
Column {
Box {
Card(
modifier = Modifier
.padding(5.dp)
.fillMaxWidth()
.height(190.dp),
shape = RoundedCornerShape(10.dp)
) {
GlideImage(
model = image,
contentDescription = "",
contentScale = ContentScale.Crop
)
}
IconButton(
modifier = Modifier.align(Alignment.TopEnd),
onClick = {
onSaveClick(place.id, isFavorite)
isFavorite = !isFavorite
}
) {
Card(
modifier = Modifier
.size(26.dp),
shape = RoundedCornerShape(5.dp),
colors = CardDefaults.cardColors(
containerColor = Color.White
),
) {
AnimatedContent(
targetState = isFavorite,
label = "",
transitionSpec = {
fadeIn(
animationSpec = tween(250, easing = EaseIn)
).togetherWith(
fadeOut(
animationSpec = tween(250, easing = EaseOut)
)
)
}
) { condition ->
Box(modifier = Modifier.fillMaxSize()) {
Icon(
modifier = Modifier.align(Alignment.Center),
painter = if (condition) painterResource(id = R.drawable.ic_heart_filled) else painterResource(
id = R.drawable.ic_heart
),
contentDescription = "",
tint = if (condition) Color.Red else colorResource(id = R.color.primary)
)
}
}
}
}
}
Text(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 5.dp),
text = place.name,
color = Color.Black,
textAlign = TextAlign.Center,
fontSize = 12.sp,
overflow = TextOverflow.Ellipsis
)
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/search/components/PlacesListItem.kt
|
3990188299
|
package sq.mayv.aegyptus.ui.screens.search.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import sq.mayv.aegyptus.extension.shimmer
@Composable
fun PlacesListShimmer() {
Column(
modifier = Modifier.padding(top = 20.dp),
verticalArrangement = Arrangement.spacedBy(15.dp)
) {
repeat(4) {
Card(
modifier = Modifier
.padding(horizontal = 20.dp)
.fillMaxWidth()
.height(250.dp),
shape = RoundedCornerShape(15.dp),
colors = CardDefaults.cardColors(
containerColor = Color.Transparent,
contentColor = Color.Transparent
),
elevation = CardDefaults.cardElevation(15.dp)
) {
Box(
modifier = Modifier
.fillMaxSize()
.shimmer()
)
}
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/search/components/PlacesListShimmer.kt
|
411466894
|
package sq.mayv.aegyptus.ui.screens.search.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Text
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import sq.mayv.aegyptus.R
import sq.mayv.aegyptus.components.SearchTextField
import sq.mayv.aegyptus.model.Category
@Composable
fun SearchTopBar(
navController: NavController,
searchQuery: String,
onSearchClick: (String) -> Unit,
categories: List<Category>
) {
val categoriesList = categories.toMutableList()
categoriesList.add(0, Category(0, "All"))
Column(
modifier = Modifier.fillMaxWidth()
) {
Row(
modifier = Modifier
.padding(end = 20.dp)
.fillMaxWidth()
.height(80.dp),
verticalAlignment = Alignment.CenterVertically
) {
IconButton(onClick = {
navController.popBackStack()
}) {
Icon(
painter = painterResource(id = R.drawable.ic_back_arrow),
contentDescription = "Back Arrow",
tint = Color.Black
)
}
var searchQuery by remember { mutableStateOf(searchQuery) }
var trailingIconVisibility by remember { mutableStateOf(true) }
SearchTextField(
modifier = Modifier
.fillMaxWidth(),
search = searchQuery,
trailingIconVisibility = trailingIconVisibility,
onValueChange = { value ->
searchQuery = value
if (searchQuery.isNotEmpty()) {
if (!trailingIconVisibility) {
trailingIconVisibility = true
}
} else {
trailingIconVisibility = false
}
},
onSearchClick = {
onSearchClick(searchQuery)
},
onTrailingIconClick = {
searchQuery = ""
trailingIconVisibility = false
}
)
}
LazyRow(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(15.dp),
contentPadding = PaddingValues(horizontal = 15.dp)
) {
items(items = categoriesList, key = { it.id }) {
Card(
colors = CardDefaults.cardColors(
containerColor = Color.LightGray
),
shape = RoundedCornerShape(5.dp)
) {
Text(
modifier = Modifier.padding(horizontal = 8.dp),
text = it.category,
color = Color.Black,
fontSize = 16.sp
)
}
}
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/search/components/SearchTopBar.kt
|
1855073932
|
package sq.mayv.aegyptus.ui.screens.search.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import sq.mayv.aegyptus.R
import sq.mayv.aegyptus.components.LottieAnimationView
@Composable
fun SearchErrorView() {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Card(
modifier = Modifier
.width(300.dp)
.wrapContentHeight(),
shape = RoundedCornerShape(10.dp),
contentColor = Color.White,
elevation = 15.dp
) {
Column(
modifier = Modifier
.padding(vertical = 20.dp)
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
LottieAnimationView(
modifier = Modifier.size(200.dp),
lottie = R.raw.mummy,
iterateForEver = false
)
Text(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 15.dp),
text = "Failed to load data",
fontSize = 16.sp,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center,
color = Color.Red
)
}
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/search/components/SearchErrorView.kt
|
499386257
|
package sq.mayv.aegyptus.ui.screens.search
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.core.EaseIn
import androidx.compose.animation.core.EaseOut
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Scaffold
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import sq.mayv.aegyptus.components.MessageView
import sq.mayv.aegyptus.ui.navigation.AppScreens
import sq.mayv.aegyptus.ui.screens.search.components.PlacesListShimmer
import sq.mayv.aegyptus.ui.screens.search.components.PlacesListView
import sq.mayv.aegyptus.ui.screens.search.components.SearchErrorView
import sq.mayv.aegyptus.ui.screens.search.components.SearchTopBar
@Composable
fun SearchScreen(
navController: NavController,
searchQuery: String,
viewModel: SearchViewModel = hiltViewModel()
) {
var query by remember { mutableStateOf(searchQuery) }
LaunchedEffect(key1 = query) {
viewModel.getAllCategories()
viewModel.search(query)
}
val categories by viewModel.categoriesData.collectAsState()
Scaffold(
modifier = Modifier.fillMaxSize(),
topBar = {
SearchTopBar(
navController = navController,
searchQuery = searchQuery,
categories = categories.data ?: listOf(),
onSearchClick = {
if (it.isNotEmpty()) {
query = it
}
}
)
}
) {
Surface(
modifier = Modifier
.padding(it)
.fillMaxSize(),
color = Color.White
) {
val places by viewModel.placesData.collectAsState()
AnimatedContent(
targetState = viewModel.isLoading,
label = "",
transitionSpec = {
fadeIn(
animationSpec = tween(600, easing = EaseIn)
).togetherWith(
fadeOut(
animationSpec = tween(600, easing = EaseOut)
)
)
}
) { isLoading ->
if (isLoading) {
PlacesListShimmer()
} else {
AnimatedContent(
targetState = viewModel.isSuccessful,
label = "",
transitionSpec = {
fadeIn(
animationSpec = tween(600, easing = EaseIn)
).togetherWith(
fadeOut(
animationSpec = tween(600, easing = EaseOut)
)
)
}
) { isSuccessful ->
if (isSuccessful) {
val size = places.data?.size ?: 0
AnimatedContent(
targetState = size > 0,
label = "",
transitionSpec = {
fadeIn(
animationSpec = tween(600, easing = EaseIn)
).togetherWith(
fadeOut(
animationSpec = tween(600, easing = EaseOut)
)
)
}
) { isEmpty ->
if (isEmpty) {
PlacesListView(
places = places.data ?: listOf(),
onItemClick = { placeId ->
navController.navigate(
AppScreens.PlaceScreen.name.plus(
placeId
)
)
},
onSaveClick = { placeId, isFavorite ->
}
)
} else {
MessageView(message = "There is no result for this search query.")
}
}
} else {
SearchErrorView()
}
}
}
}
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/search/SearchScreen.kt
|
3291759858
|
package sq.mayv.aegyptus.ui.screens.map.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import sq.mayv.aegyptus.R
import sq.mayv.aegyptus.components.LottieAnimationView
@Composable
fun MapErrorView() {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Card(
modifier = Modifier
.width(300.dp)
.wrapContentHeight(),
shape = RoundedCornerShape(10.dp),
contentColor = Color.White,
elevation = 15.dp
) {
Column(
modifier = Modifier
.padding(vertical = 20.dp)
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
LottieAnimationView(
modifier = Modifier.size(200.dp),
lottie = R.raw.mummy,
iterateForEver = false
)
Text(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 15.dp),
text = "Failed to load the map",
fontSize = 16.sp,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center,
color = Color.Red
)
}
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/map/components/MapErrorView.kt
|
227595014
|
package sq.mayv.aegyptus.ui.screens.map.components
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.navigation.NavController
import com.google.android.gms.maps.model.LatLng
import com.google.maps.android.compose.GoogleMap
import com.google.maps.android.compose.MapProperties
import com.google.maps.android.compose.MapType
import com.google.maps.android.compose.MapUiSettings
import com.google.maps.android.compose.Marker
import com.google.maps.android.compose.MarkerState
import com.google.maps.android.compose.rememberCameraPositionState
import sq.mayv.aegyptus.extension.centerOnLocation
import sq.mayv.aegyptus.model.Place
import sq.mayv.aegyptus.ui.navigation.AppScreens
import sq.mayv.aegyptus.ui.screens.map.MapViewModel
@Composable
fun Map(
rootNavController: NavController,
viewModel: MapViewModel,
places: List<Place>,
mapType: MapType,
trafficMode: Boolean
) {
val cameraState = rememberCameraPositionState()
val currentLocation by viewModel.currentLocation.collectAsState()
LaunchedEffect(key1 = currentLocation) {
cameraState.centerOnLocation(currentLocation)
}
GoogleMap(
modifier = Modifier.fillMaxSize(),
cameraPositionState = cameraState,
properties = MapProperties(
isMyLocationEnabled = true,
mapType = mapType,
isTrafficEnabled = trafficMode
),
uiSettings = MapUiSettings(
zoomControlsEnabled = false
)
) {
places.forEach { place ->
val latLng = place.coordinates.split(',')
Marker(
state = MarkerState(position = LatLng(latLng[0].toDouble(), latLng[1].toDouble())),
title = place.name,
snippet = "Click To View",
draggable = false,
onInfoWindowClick = {
rootNavController.navigate(AppScreens.PlaceScreen.name.plus(place.id))
}
)
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/map/components/Map.kt
|
680083947
|
package sq.mayv.aegyptus.ui.screens.map
import android.content.SharedPreferences
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.android.gms.maps.model.LatLng
import com.google.maps.android.compose.MapType
import com.mayv.ctgate.data.Resource
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import sq.mayv.aegyptus.model.Place
import sq.mayv.aegyptus.repository.PlacesRepository
import sq.mayv.aegyptus.ui.screens.map.viewstate.MapViewState
import sq.mayv.aegyptus.usecase.LocationUseCase
import sq.mayv.aegyptus.util.PreferenceHelper.mapType
import sq.mayv.aegyptus.util.PreferenceHelper.token
import sq.mayv.aegyptus.util.PreferenceHelper.trafficMode
import javax.inject.Inject
@HiltViewModel
class MapViewModel @Inject constructor(
private val placesRepository: PlacesRepository,
private val locationUseCase: LocationUseCase,
private val preferences: SharedPreferences
) : ViewModel() {
private val _placesData = MutableStateFlow(Resource<List<Place>>())
private val _viewState: MutableStateFlow<MapViewState> = MutableStateFlow(MapViewState.Loading)
val viewState = _viewState.asStateFlow()
private val _currentLocation = MutableStateFlow(LatLng(0.00, 0.00))
val currentLocation: StateFlow<LatLng> = _currentLocation
fun getAllPlaces() {
viewModelScope.launch(Dispatchers.IO) {
if (_viewState.value != MapViewState.Loading) {
_viewState.value = MapViewState.Loading
}
locationUseCase.invoke().collect { latLng ->
_placesData.value =
placesRepository.getAllPlaces(
governorateCode = 1,
authToken = preferences.token
)
val statusCode = _placesData.value.statusCode
val isPlacesSuccessful = statusCode == 200 || statusCode == 201
if (!isPlacesSuccessful) {
_viewState.value = MapViewState.Failure
} else {
_currentLocation.value = latLng ?: LatLng(0.00, 0.00)
_viewState.value = MapViewState.Success(
places = _placesData.value.data ?: listOf(),
mapType = getMapType(preferences.mapType),
trafficMode = preferences.trafficMode
)
}
}
}
}
private fun getMapType(id: Int): MapType {
return when(id) {
0 -> MapType.NONE
1 -> MapType.NORMAL
2 -> MapType.SATELLITE
3 -> MapType.TERRAIN
4 -> MapType.HYBRID
else -> MapType.NORMAL
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/map/MapViewModel.kt
|
2584602707
|
package sq.mayv.aegyptus.ui.screens.map.viewstate
import com.google.maps.android.compose.MapType
import sq.mayv.aegyptus.model.Place
sealed interface MapViewState {
data object Loading : MapViewState
data class Success(
val places: List<Place>,
val mapType: MapType,
val trafficMode: Boolean,
) : MapViewState
data object Failure : MapViewState
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/map/viewstate/MapViewState.kt
|
71345371
|
package sq.mayv.aegyptus.ui.screens.map
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.core.EaseIn
import androidx.compose.animation.core.EaseOut
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import sq.mayv.aegyptus.R
import sq.mayv.aegyptus.components.LottieAnimationView
import sq.mayv.aegyptus.ui.screens.map.components.Map
import sq.mayv.aegyptus.ui.screens.map.components.MapErrorView
import sq.mayv.aegyptus.ui.screens.map.viewstate.MapViewState
@Composable
fun MapScreen(
rootNavController: NavController,
viewModel: MapViewModel = hiltViewModel()
) {
LaunchedEffect(Unit) {
viewModel.getAllPlaces()
}
val viewState by viewModel.viewState.collectAsStateWithLifecycle()
AnimatedContent(
targetState = viewState,
label = "",
transitionSpec = {
fadeIn(
animationSpec = tween(600, easing = EaseIn)
).togetherWith(
fadeOut(
animationSpec = tween(600, easing = EaseOut)
)
)
}
) {
when (it) {
MapViewState.Loading -> {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
LottieAnimationView(
modifier = Modifier.size(120.dp),
lottie = R.raw.ankh_loading_black
)
}
}
MapViewState.Failure -> {
MapErrorView()
}
is MapViewState.Success -> {
Map(
rootNavController = rootNavController,
viewModel = viewModel,
places = it.places,
mapType = it.mapType,
trafficMode = it.trafficMode
)
}
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/map/MapScreen.kt
|
1875076962
|
package sq.mayv.aegyptus.ui.screens.signin.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.Divider
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import sq.mayv.aegyptus.components.LoadingRoundedButton
import sq.mayv.aegyptus.components.OutlinedRoundedButton
@Composable
fun LoginBottomBar(
isLoading: Boolean = false,
onSignInClick: () -> Unit,
onSignUpClick: () -> Unit
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 25.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(15.dp)
) {
LoadingRoundedButton(
modifier = Modifier
.fillMaxWidth()
.height(45.dp)
.padding(horizontal = 35.dp),
text = "Confirm",
fontSize = 18,
isLoading = isLoading
) {
onSignInClick()
}
Row(verticalAlignment = Alignment.CenterVertically) {
Divider(modifier = Modifier.width(70.dp), color = Color.LightGray)
Text(text = "or", modifier = Modifier.padding(horizontal = 10.dp))
Divider(modifier = Modifier.width(70.dp), color = Color.LightGray)
}
OutlinedRoundedButton(
modifier = Modifier
.fillMaxWidth()
.height(45.dp)
.padding(horizontal = 35.dp),
text = "Not a member? Register now",
fontSize = 14
) {
onSignUpClick()
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/signin/components/LoginBottomBar.kt
|
2918355767
|
package sq.mayv.aegyptus.ui.screens.signin
import android.content.SharedPreferences
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.mayv.ctgate.data.Resource
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import sq.mayv.aegyptus.dto.SignInDto
import sq.mayv.aegyptus.model.Auth
import sq.mayv.aegyptus.repository.AuthRepository
import sq.mayv.aegyptus.util.PreferenceHelper.token
import sq.mayv.aegyptus.util.PreferenceHelper.userEmail
import sq.mayv.aegyptus.util.PreferenceHelper.userName
import javax.inject.Inject
@HiltViewModel
class SignInViewModel @Inject constructor(
private val authRepository: AuthRepository,
private val preferences: SharedPreferences
) :
ViewModel() {
private val _signInData = MutableStateFlow(Resource<Auth>())
val signInData: StateFlow<Resource<Auth>> = _signInData
var isSignInLoading by mutableStateOf(false)
var isSignInSuccessful by mutableStateOf(false)
fun signIn(body: SignInDto) {
viewModelScope.launch(Dispatchers.IO) {
isSignInLoading = true
_signInData.value = authRepository.signIn(body)
val statusCode = _signInData.value.statusCode
if (statusCode == 200 || statusCode == 201) {
preferences.token = _signInData.value.data!!.authorizationToken
preferences.userName = _signInData.value.data!!.name
preferences.userEmail = _signInData.value.data!!.email
isSignInSuccessful = true
}
isSignInLoading = false
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/signin/SignInViewModel.kt
|
2227497368
|
package sq.mayv.aegyptus.ui.screens.signin
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import sq.mayv.aegyptus.R
import sq.mayv.aegyptus.components.PasswordTextInputField
import sq.mayv.aegyptus.components.TextInputField
import sq.mayv.aegyptus.components.TopBarTitleArrow
import sq.mayv.aegyptus.dto.SignInDto
import sq.mayv.aegyptus.ui.navigation.AppScreens
import sq.mayv.aegyptus.ui.screens.signin.components.LoginBottomBar
@Composable
fun SignInScreen(
navController: NavController,
viewModel: SignInViewModel = hiltViewModel()
) {
val coroutineScope = rememberCoroutineScope()
var email by remember { mutableStateOf("[email protected]") }
var password by remember { mutableStateOf("test123") }
var emailMessage by remember { mutableStateOf("") }
var passwordMessage by remember { mutableStateOf("") }
var emailMessageVisibility by remember { mutableStateOf(false) }
var passwordMessageVisibility by remember { mutableStateOf(false) }
val data = viewModel.signInData.collectAsState().value
var signUpClicked by remember { mutableStateOf(false) }
LaunchedEffect(key1 = data.statusCode) {
if (viewModel.isSignInSuccessful) {
navController.popBackStack()
navController.navigate(AppScreens.Main.name)
}
}
Scaffold(
modifier = Modifier.fillMaxSize(),
topBar = {
TopBarTitleArrow(
navController = navController,
title = "Sign In",
backArrowEnabled = false
)
},
bottomBar = {
LoginBottomBar(
isLoading = viewModel.isSignInLoading,
onSignInClick = {
coroutineScope.launch(Dispatchers.IO) {
if (!viewModel.isSignInLoading) {
if (email.isNotEmpty() || password.isNotEmpty()) {
val body = SignInDto(email = email, password = password)
viewModel.signIn(body = body)
} else {
if (email.isEmpty()) {
emailMessage = "Please enter the email."
emailMessageVisibility = true
}
if (password.isEmpty()) {
passwordMessage = "Please enter the password."
passwordMessageVisibility = true
}
}
}
}
},
onSignUpClick = {
if (!viewModel.isSignInLoading) {
if (!signUpClicked) {
signUpClicked = true
navController.navigate(AppScreens.SignUpScreen.name)
}
}
}
)
}
) {
Column(
modifier = Modifier
.padding(it)
.padding(bottom = 35.dp)
.fillMaxSize()
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
TextInputField(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 35.dp, vertical = 15.dp),
value = email,
onValueChange = { value ->
email = value
if (emailMessage.isNotEmpty()) {
emailMessageVisibility = value == ""
}
},
label = "Email",
message = emailMessage,
messageModifier = Modifier
.fillMaxWidth()
.padding(horizontal = 35.dp),
messageVisibility = emailMessageVisibility,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Email,
autoCorrect = false
)
)
PasswordTextInputField(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 35.dp, vertical = 15.dp),
value = password,
onValueChange = { value ->
password = value
if (passwordMessage.isNotEmpty()) {
passwordMessageVisibility = value == ""
}
},
label = "Password",
message = passwordMessage,
errorModifier = Modifier
.fillMaxWidth()
.padding(horizontal = 35.dp),
messageVisibility = passwordMessageVisibility
)
Text(
modifier = Modifier
.fillMaxWidth()
.padding(end = 35.dp, top = 15.dp)
.clickable {
if (!viewModel.isSignInLoading) {
navController.navigate(AppScreens.RecoverPasswordScreen.name)
}
},
text = "Forgot your password?",
textAlign = TextAlign.End,
fontWeight = FontWeight.Bold,
color = colorResource(id = R.color.blue_clickable_text)
)
Text(
text = if (data.statusCode in (400..500)) data.exception.message.toString() else "",
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 35.dp)
.padding(vertical = 25.dp)
.alpha(if (data.statusCode != 200 || data.statusCode != 201) 1f else 0f),
color = colorResource(id = R.color.gold),
textAlign = TextAlign.Center
)
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/signin/SignInScreen.kt
|
1210588917
|
package sq.mayv.aegyptus.ui.screens.profile
import android.content.SharedPreferences
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class ProfileViewModel @Inject constructor(
val preferences: SharedPreferences
) :
ViewModel() {
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/profile/ProfileViewModel.kt
|
2022789029
|
package sq.mayv.aegyptus.ui.screens.profile.components
import androidx.annotation.DrawableRes
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.ButtonColors
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import sq.mayv.aegyptus.R
@Composable
fun OutlinedProfileButton(
modifier: Modifier = Modifier,
text: String,
fontSize: Int = 20,
colors: ButtonColors = ButtonDefaults.buttonColors(
backgroundColor = Color.White,
contentColor = colorResource(id = R.color.primary)
),
borderColor: Color = colorResource(id = R.color.primary),
@DrawableRes trailingIcon: Int = R.drawable.ic_keyboard_arrow_right,
onClicked: () -> Unit
) {
Button(
modifier = modifier.height(60.dp),
colors = colors,
shape = RoundedCornerShape(10.dp),
onClick = { onClicked() },
border = BorderStroke(2.dp, borderColor)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Text(
modifier = Modifier.weight(9f),
text = text,
fontSize = fontSize.sp,
textAlign = TextAlign.Start
)
Icon(
modifier = Modifier.weight(1f),
painter = painterResource(id = trailingIcon),
contentDescription = ""
)
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/profile/components/OutlinedProfileButton.kt
|
724694004
|
package sq.mayv.aegyptus.ui.screens.profile
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import sq.mayv.aegyptus.R
import sq.mayv.aegyptus.components.OutlinedRoundedButton
import sq.mayv.aegyptus.ui.navigation.AppScreens
import sq.mayv.aegyptus.ui.screens.profile.components.OutlinedProfileButton
import sq.mayv.aegyptus.util.PreferenceHelper.token
@Composable
fun ProfileScreen(
navController: NavController,
viewModel: ProfileViewModel = hiltViewModel(),
rootNavController: NavController
) {
Surface(
modifier = Modifier.fillMaxSize(), color = Color.White
) {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(10.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Box(
modifier = Modifier
.padding(top = 15.dp)
.size(160.dp)
.border(
border = BorderStroke(
2.dp,
color = colorResource(id = R.color.primary)
), shape = CircleShape
)
) {
Image(
modifier = Modifier
.size(130.dp)
.align(Alignment.Center),
painter = painterResource(id = R.drawable.pharaoh),
contentDescription = "",
contentScale = ContentScale.FillBounds
)
}
Text(
modifier = Modifier.fillMaxWidth(),
text = "Mahmoud Salah",
textAlign = TextAlign.Center,
fontSize = 28.sp
)
Text(
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 40.dp),
text = "[email protected]",
fontSize = 22.sp,
textAlign = TextAlign.Center
)
OutlinedProfileButton(
modifier = Modifier
.padding(top = 20.dp)
.padding(horizontal = 40.dp)
.fillMaxWidth(),
text = "Profile"
) {
}
OutlinedProfileButton(
modifier = Modifier
.padding(top = 20.dp)
.padding(horizontal = 40.dp)
.fillMaxWidth(),
text = "Settings"
) {
}
OutlinedProfileButton(
modifier = Modifier
.padding(top = 20.dp)
.padding(horizontal = 40.dp)
.fillMaxWidth(),
text = "Privacy Policy"
) {
}
OutlinedRoundedButton(
modifier = Modifier
.padding(top = 40.dp)
.padding(horizontal = 40.dp)
.fillMaxWidth(),
text = "Sign Out",
colors = ButtonDefaults.buttonColors(
backgroundColor = Color.White, contentColor = Color.Red
),
borderColor = Color.Red,
fontSize = 20
) {
viewModel.preferences.token = ""
// Using root nav controller to navigate in the root navhost.
rootNavController.popBackStack()
rootNavController.navigate(AppScreens.Auth.name)
}
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/profile/ProfileScreen.kt
|
1535634165
|
package sq.mayv.aegyptus.ui.screens.place
import android.content.SharedPreferences
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.mayv.ctgate.data.Resource
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import sq.mayv.aegyptus.model.Place
import sq.mayv.aegyptus.repository.FavoritesRepository
import sq.mayv.aegyptus.repository.PlacesRepository
import sq.mayv.aegyptus.util.PreferenceHelper.token
import javax.inject.Inject
@HiltViewModel
class PlaceViewModel @Inject constructor(
private val placesRepository: PlacesRepository,
private val favoritesRepository: FavoritesRepository,
private val preferences: SharedPreferences
) :
ViewModel() {
private val _placeData = MutableStateFlow(Resource<Place>())
val placeData: StateFlow<Resource<Place>> = _placeData
var isPlaceLoading by mutableStateOf(false)
var isSuccessful by mutableStateOf(false)
var isAddingFavorite by mutableStateOf(false)
var addedSuccessfuly by mutableStateOf(false)
var isRemovingFavorite by mutableStateOf(false)
var removedSuccessfuly by mutableStateOf(false)
fun getPlaceInfo(placeId: Int) {
viewModelScope.launch(Dispatchers.IO) {
isPlaceLoading = true
_placeData.value =
placesRepository.getPlace(placeId = placeId, authToken = preferences.token)
Log.i("TAG", "getPlaceInfo: ${_placeData.value.data}")
val statusCode = _placeData.value.statusCode
Log.i("TAG", "getPlaceInfo: $statusCode")
isSuccessful = statusCode == 200 || statusCode == 201
isPlaceLoading = false
}
}
fun addToFavorites(placeId: Int) {
viewModelScope.launch(Dispatchers.IO) {
isAddingFavorite = true
val value = favoritesRepository.addToFavorite(placeId, preferences.token)
val statusCode = value.statusCode
addedSuccessfuly = statusCode == 200 || statusCode == 201
isAddingFavorite = false
}
}
fun removeFromFavorites(placeId: Int) {
viewModelScope.launch(Dispatchers.IO) {
isRemovingFavorite = true
val value = favoritesRepository.removeFromFavorites(placeId, preferences.token)
val statusCode = value.statusCode
removedSuccessfuly = statusCode == 200 || statusCode == 201
isRemovingFavorite = false
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/place/PlaceViewModel.kt
|
348852897
|
package sq.mayv.aegyptus.ui.screens.place
import android.annotation.SuppressLint
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.core.EaseIn
import androidx.compose.animation.core.EaseOut
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Surface
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import sq.mayv.aegyptus.R
import sq.mayv.aegyptus.ui.screens.place.components.PlaceDataShimmer
import sq.mayv.aegyptus.ui.screens.place.components.PlaceDataView
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun PlaceScreen(
navController: NavController,
placeId: Int,
viewModel: PlaceViewModel = hiltViewModel()
) {
LaunchedEffect(key1 = placeId) {
viewModel.getPlaceInfo(placeId)
}
val place = viewModel.placeData.collectAsState()
Scaffold(
modifier = Modifier.fillMaxSize(),
topBar = {
AnimatedContent(
targetState = !viewModel.isPlaceLoading && viewModel.isSuccessful,
label = "",
transitionSpec = {
fadeIn(
animationSpec = tween(600, easing = EaseIn)
).togetherWith(
fadeOut(
animationSpec = tween(600, easing = EaseOut)
)
)
}
) { condition ->
Box(modifier = Modifier.fillMaxWidth()) {
IconButton(
modifier = Modifier
.size(50.dp)
.align(Alignment.TopStart)
.padding(start = 10.dp),
onClick = {
navController.popBackStack()
}
) {
Icon(
modifier = Modifier.size(25.dp),
painter = painterResource(id = R.drawable.ic_back_arrow),
contentDescription = "Back Arrow Icon",
tint = Color.White
)
}
if (condition) {
var isFavorite by remember {
mutableStateOf(
place.value.data?.isFavorite ?: false
)
}
IconButton(
modifier = Modifier
.padding(10.dp)
.align(Alignment.TopEnd)
.size(30.dp),
onClick = {
if (!viewModel.isAddingFavorite && !viewModel.isRemovingFavorite) {
if (!isFavorite) {
viewModel.addToFavorites(placeId)
} else {
viewModel.removeFromFavorites(placeId)
}
isFavorite = !isFavorite
}
}
) {
Card(
modifier = Modifier.fillMaxSize(),
shape = RoundedCornerShape(5.dp),
colors = CardDefaults.cardColors(containerColor = Color.White)
) {
AnimatedContent(
targetState = isFavorite,
label = "",
transitionSpec = {
fadeIn(
animationSpec = tween(250, easing = EaseIn)
).togetherWith(
fadeOut(
animationSpec = tween(250, easing = EaseOut)
)
)
}
) { condition ->
Box(modifier = Modifier.fillMaxSize()) {
Icon(
modifier = Modifier
.align(Alignment.Center)
.size(25.dp),
painter = if (condition) painterResource(id = R.drawable.ic_heart_filled) else painterResource(
id = R.drawable.ic_heart
),
contentDescription = "Save Place Icon",
tint = if (condition) Color.Red else colorResource(id = R.color.primary)
)
}
}
}
}
}
}
}
}
) {
Surface(
modifier = Modifier
.fillMaxSize(),
color = Color.White
) {
val images = place.value.data?.images?.split("|") ?: listOf("")
val pagerState = rememberPagerState(initialPage = 0, pageCount = { images.size })
AnimatedContent(
targetState = !viewModel.isPlaceLoading && viewModel.isSuccessful,
label = "",
transitionSpec = {
fadeIn(
animationSpec = tween(600, easing = EaseIn)
).togetherWith(
fadeOut(
animationSpec = tween(600, easing = EaseOut)
)
)
}
) { condition ->
if (condition) {
PlaceDataView(
place = place.value.data,
pagerState = pagerState,
navController = navController
)
} else {
PlaceDataShimmer()
}
}
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/place/PlaceScreen.kt
|
2584290231
|
package sq.mayv.aegyptus.ui.screens.place.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
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.unit.dp
import sq.mayv.aegyptus.extension.shimmer
@Composable
fun PlaceDataShimmer() {
Box(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight(align = Alignment.Top, unbounded = true),
) {
PlaceImageShimmer()
}
Card(
modifier = Modifier
.padding(top = 280.dp)
.fillMaxWidth(),
colors = CardDefaults.cardColors(
containerColor = Color.White
),
shape = RoundedCornerShape(20.dp)
) {
Column(
modifier = Modifier
.padding(top = 15.dp)
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(20.dp)
) {
Box(
modifier = Modifier
.width(80.dp)
.height(15.dp)
.clip(RoundedCornerShape(10.dp))
.shimmer()
)
PlaceCategoryShimmer()
PlaceInfoShimmer()
Box(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp)
.height(130.dp)
.clip(RoundedCornerShape(10.dp))
.shimmer()
)
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/place/components/PlaceDataShimmer.kt
|
4030168598
|
package sq.mayv.aegyptus.ui.screens.place.components
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
import sq.mayv.aegyptus.extension.shimmer
@Composable
fun PlaceInfoShimmer() {
Row(
modifier = Modifier.fillMaxWidth()
) {
Row(
modifier = Modifier
.padding(horizontal = 20.dp)
.weight(1f)
) {
Box(
modifier = Modifier
.height(25.dp)
.fillMaxWidth()
.clip(RoundedCornerShape(10.dp))
.shimmer()
)
}
Row(
modifier = Modifier
.padding(horizontal = 20.dp)
.weight(1f)
) {
Box(
modifier = Modifier
.height(25.dp)
.fillMaxWidth()
.clip(RoundedCornerShape(10.dp))
.shimmer()
)
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/place/components/PlaceInfoShimmer.kt
|
3467849222
|
package sq.mayv.aegyptus.ui.screens.place.components
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
import com.bumptech.glide.integration.compose.GlideImage
@OptIn(ExperimentalFoundationApi::class, ExperimentalGlideComposeApi::class)
@Composable
fun PlaceImageView(
pagerState: PagerState,
images: List<String>
) {
HorizontalPager(
modifier = Modifier
.fillMaxWidth()
.height(300.dp),
state = pagerState,
outOfBoundsPageCount = 1
) { position ->
GlideImage(
modifier = Modifier.fillMaxSize(),
model = images[position],
contentDescription = "",
contentScale = ContentScale.FillBounds
)
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/place/components/PlaceImageView.kt
|
1870173653
|
package sq.mayv.aegyptus.ui.screens.place.components
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.material.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import sq.mayv.aegyptus.R
@Composable
fun PlaceInfoView(location: String, time: String) {
Row(
modifier = Modifier.fillMaxWidth()
) {
Box(
modifier = Modifier
.weight(1f)
.fillMaxWidth()
.padding(start = 20.dp)
) {
Row(
modifier = Modifier
.wrapContentWidth()
.align(Alignment.Center),
) {
Icon(
painter = painterResource(id = R.drawable.ic_location),
contentDescription = "",
tint = colorResource(id = R.color.primary)
)
Text(
modifier = Modifier.padding(start = 5.dp),
text = location,
fontSize = 14.sp,
color = colorResource(id = R.color.description)
)
}
}
Box(
modifier = Modifier
.weight(1f)
.padding(end = 20.dp)
) {
Row(
modifier = Modifier
.wrapContentWidth()
.align(Alignment.Center),
) {
Icon(
painter = painterResource(id = R.drawable.ic_time),
contentDescription = "",
tint = colorResource(id = R.color.primary)
)
Text(
modifier = Modifier.padding(start = 5.dp),
text = time,
fontSize = 14.sp,
color = colorResource(id = R.color.description)
)
}
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/place/components/PlaceInfoView.kt
|
2899731063
|
package sq.mayv.aegyptus.ui.screens.place.components
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import sq.mayv.aegyptus.extension.shimmer
@Composable
fun PlaceImageShimmer() {
Box(
modifier = Modifier
.fillMaxWidth()
.height(300.dp)
.shimmer()
)
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/place/components/PlaceImageShimmer.kt
|
381369495
|
package sq.mayv.aegyptus.ui.screens.place.components
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
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.res.colorResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import sq.mayv.aegyptus.R
import sq.mayv.aegyptus.model.Category
import sq.mayv.aegyptus.model.Place
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun PlaceDataView(
place: Place?,
pagerState: PagerState,
navController: NavController
) {
val images = place?.images?.split("|")
?: listOf("https://i.ibb.co/3NFhvrD/546943212-caitbay-5.jpg")
Box(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight(align = Alignment.Top, unbounded = true),
) {
PlaceImageView(
pagerState = pagerState,
images = images
)
Text(
modifier = Modifier
.align(Alignment.BottomStart)
.padding(bottom = 35.dp)
.padding(horizontal = 15.dp),
text = place?.name ?: "Failed to load the name",
color = Color.White,
textAlign = TextAlign.Center,
fontWeight = FontWeight.Bold
)
}
Card(
modifier = Modifier
.padding(top = 280.dp)
.fillMaxWidth(),
colors = CardDefaults.cardColors(
containerColor = Color.White
),
shape = RoundedCornerShape(20.dp)
) {
Row(
Modifier
.wrapContentHeight()
.fillMaxWidth()
.padding(vertical = 15.dp),
horizontalArrangement = Arrangement.Center
) {
repeat(pagerState.pageCount) { iteration ->
val width by animateDpAsState(
targetValue = if (pagerState.currentPage == iteration) 15.dp else 5.dp,
animationSpec = tween(
durationMillis = 100,
),
label = "Indicator Width Animation"
)
Box(
modifier = Modifier
.padding(3.dp)
.height(5.dp)
.width(width)
.clip(RoundedCornerShape(3.dp))
.background(colorResource(id = R.color.primary))
)
}
}
Column(
modifier = Modifier
.padding(top = 20.dp, bottom = 15.dp)
.fillMaxWidth()
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(20.dp)
) {
PlaceCategoryView(category = place?.category ?: Category())
PlaceInfoView(
location = place?.address ?: "Failed to load",
time = place?.time ?: "Failed to load"
)
Text(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp),
text = place?.about ?: "Failed to load",
color = Color.Black
)
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/place/components/PlaceDataView.kt
|
3235196764
|
package sq.mayv.aegyptus.ui.screens.place.components
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Icon
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import sq.mayv.aegyptus.R
import sq.mayv.aegyptus.model.Category
import sq.mayv.aegyptus.util.CategoryItem
@Composable
fun PlaceCategoryView(category: Category) {
val categoryItem = CategoryItem.getCategoryItem(category = category)
Card(
modifier = Modifier.size(45.dp),
shape = CircleShape,
border = BorderStroke(
width = 1.dp,
color = colorResource(id = R.color.primary)
),
colors = CardDefaults.cardColors(
containerColor = Color.Transparent
)
) {
Box(
modifier = Modifier.fillMaxSize()
) {
Icon(
modifier = Modifier
.size(35.dp)
.align(Alignment.Center),
painter = painterResource(id = categoryItem.icon),
contentDescription = "",
tint = colorResource(id = R.color.primary)
)
}
}
Text(
text = categoryItem.title,
color = colorResource(id = R.color.description)
)
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/place/components/PlaceCategoryView.kt
|
17423177
|
package sq.mayv.aegyptus.ui.screens.place.components
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
import sq.mayv.aegyptus.extension.shimmer
@Composable
fun PlaceCategoryShimmer() {
Box(
modifier = Modifier
.size(45.dp)
.clip(CircleShape)
.shimmer(),
)
Box(
modifier = Modifier
.width(120.dp)
.height(30.dp)
.clip(RoundedCornerShape(10.dp))
.shimmer()
)
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/place/components/PlaceCategoryShimmer.kt
|
2157735143
|
package sq.mayv.aegyptus.ui.screens.main
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import sq.mayv.aegyptus.data.PermissionEvent
import sq.mayv.aegyptus.ui.screens.main.viewstate.MainViewState
import javax.inject.Inject
@HiltViewModel
class MainViewModel @Inject constructor() : ViewModel() {
private val _viewState: MutableStateFlow<MainViewState> =
MutableStateFlow(MainViewState.CheckingPermissions)
val viewState = _viewState.asStateFlow()
fun handleViewState(event: PermissionEvent) {
when (event) {
PermissionEvent.Granted -> {
_viewState.value = MainViewState.GrantedPermissions
}
PermissionEvent.Revoked -> {
_viewState.value = MainViewState.RevokedPermissions
}
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/main/MainViewModel.kt
|
3332527453
|
package sq.mayv.aegyptus.ui.screens.main.components
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.BottomNavigation
import androidx.compose.material.BottomNavigationItem
import androidx.compose.material.Card
import androidx.compose.material.Icon
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.navigation.compose.currentBackStackEntryAsState
import sq.mayv.aegyptus.R
import sq.mayv.aegyptus.util.BottomNavItem
@Composable
fun BottomNavigationBar(navController: NavController, bottomNavItems: List<BottomNavItem>) {
Card(
modifier = Modifier
.padding(horizontal = 30.dp)
.padding(bottom = 30.dp),
shape = RoundedCornerShape(10.dp),
backgroundColor = Color.White,
elevation = 20.dp
) {
BottomNavigation(
modifier = Modifier,
backgroundColor = Color.White
) {
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
bottomNavItems.forEach { item ->
BottomNavigationItem(
selected = currentRoute == item.route,
onClick = {
if (currentRoute != item.route) {
navController.popBackStack()
navController.navigate(item.route)
}
},
icon = {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
Icon(
imageVector = ImageVector.vectorResource(id = item.drawable),
contentDescription = null,
tint = if (currentRoute == item.route) colorResource(id = R.color.primary) else Color.Gray
)
AnimatedVisibility(visible = currentRoute == item.route) {
Card(
modifier = Modifier
.padding(top = 5.dp)
.size(8.dp),
backgroundColor = colorResource(id = R.color.primary),
contentColor = colorResource(id = R.color.primary),
shape = CircleShape,
content = {}
)
}
}
},
)
}
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/main/components/BottomNavigationBar.kt
|
3401361124
|
package sq.mayv.aegyptus.ui.screens.main.components
import androidx.compose.runtime.Composable
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import sq.mayv.aegyptus.ui.screens.favorites.FavoritesScreen
import sq.mayv.aegyptus.ui.screens.home.HomeScreen
import sq.mayv.aegyptus.ui.screens.map.MapScreen
import sq.mayv.aegyptus.ui.screens.profile.ProfileScreen
import sq.mayv.aegyptus.util.BottomNavItem
@Composable
fun MainNavigationHost(rootNavController: NavController, navController: NavHostController) {
NavHost(navController = navController, startDestination = BottomNavItem.Home.route) {
composable(BottomNavItem.Home.route) {
HomeScreen(
rootNavController = rootNavController,
navController = navController
)
}
composable(BottomNavItem.Map.route) {
MapScreen(rootNavController = rootNavController)
}
composable(BottomNavItem.Favorite.route) {
FavoritesScreen(rootNavController = rootNavController, navController = navController)
}
composable(BottomNavItem.Profile.route) {
ProfileScreen(rootNavController = rootNavController, navController = navController)
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/main/components/MainNavigationHost.kt
|
2237454207
|
package sq.mayv.aegyptus.ui.screens.main.components
import android.annotation.SuppressLint
import androidx.compose.material.Scaffold
import androidx.compose.runtime.Composable
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import sq.mayv.aegyptus.util.BottomNavItem
@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
fun MainView(
rootNavController: NavController,
) {
val navController = rememberNavController()
Scaffold(
bottomBar = {
BottomNavigationBar(
navController = navController,
bottomNavItems = listOf(
BottomNavItem.Home,
BottomNavItem.Map,
BottomNavItem.Favorite,
BottomNavItem.Profile
)
)
}
) {
MainNavigationHost(
rootNavController = rootNavController,
navController = navController
)
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/main/components/MainView.kt
|
435616682
|
package sq.mayv.aegyptus.ui.screens.main.viewstate
sealed interface MainViewState {
data object CheckingPermissions : MainViewState
data object GrantedPermissions : MainViewState
data object RevokedPermissions : MainViewState
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/main/viewstate/MainViewState.kt
|
906227005
|
package sq.mayv.aegyptus.ui.screens.main
import android.Manifest
import android.annotation.SuppressLint
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.core.EaseIn
import androidx.compose.animation.core.EaseOut
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.rememberMultiplePermissionsState
import sq.mayv.aegyptus.MainActivity
import sq.mayv.aegyptus.components.LottieAnimationView
import sq.mayv.aegyptus.components.MessageView
import sq.mayv.aegyptus.data.PermissionEvent
import sq.mayv.aegyptus.extension.hasLocationPermission
import sq.mayv.aegyptus.extension.openAppSettings
import sq.mayv.aegyptus.ui.screens.main.components.MainView
import sq.mayv.aegyptus.ui.screens.main.viewstate.MainViewState
import sq.mayv.aegyptus.util.LocationPermissionTextProvider
import sq.mayv.aegyptus.util.PermissionDialog
@OptIn(ExperimentalPermissionsApi::class)
@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
fun MainScreen(
rootNavController: NavController,
viewModel: MainViewModel = hiltViewModel()
) {
val context = LocalContext.current as MainActivity
val permissionState = rememberMultiplePermissionsState(
permissions = listOf(
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
)
)
val settingsResults =
rememberLauncherForActivityResult(contract = ActivityResultContracts.StartActivityForResult(),
onResult = {
if (permissionState.allPermissionsGranted) {
viewModel.handleViewState(PermissionEvent.Granted)
}
}
)
val viewState by viewModel.viewState.collectAsStateWithLifecycle()
LaunchedEffect(!context.hasLocationPermission()) {
permissionState.launchMultiplePermissionRequest()
}
when {
permissionState.allPermissionsGranted -> {
LaunchedEffect(Unit) {
viewModel.handleViewState(PermissionEvent.Granted)
}
}
permissionState.shouldShowRationale -> {
PermissionDialog(permissionTextProvider = LocationPermissionTextProvider(),
onDismiss = {},
onOkClick = {
permissionState.launchMultiplePermissionRequest()
}
)
}
!permissionState.allPermissionsGranted && !permissionState.shouldShowRationale -> {
LaunchedEffect(Unit) {
viewModel.handleViewState(PermissionEvent.Revoked)
}
}
}
AnimatedContent(
targetState = viewState,
label = "ViewState Animation",
transitionSpec = {
fadeIn(
animationSpec = tween(600, easing = EaseIn)
).togetherWith(
fadeOut(
animationSpec = tween(600, easing = EaseOut)
)
)
}) {
when (it) {
MainViewState.CheckingPermissions -> {
Surface(
modifier = Modifier.fillMaxSize(),
color = Color.White
) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = androidx.compose.ui.Alignment.Center
) {
LottieAnimationView(
modifier = Modifier.size(100.dp),
lottie = sq.mayv.aegyptus.R.raw.ankh_loading_black
)
}
}
}
MainViewState.RevokedPermissions -> {
Surface(
modifier = Modifier.fillMaxSize(),
color = Color.White
) {
MessageView(message = "Aegyptus needs the location permissions.",
buttonEnabled = true,
buttonMessage = "Allow Permissions",
onButtonClick = { context.openAppSettings(settingsResults) }
)
}
}
MainViewState.GrantedPermissions -> {
MainView(rootNavController = rootNavController)
}
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/screens/main/MainScreen.kt
|
1259808397
|
package sq.mayv.aegyptus.ui.theme
import androidx.compose.ui.graphics.Color
//val Purple80 = Color(0xFFD0BCFF)
//val PurpleGrey80 = Color(0xFFCCC2DC)
//val Pink80 = Color(0xFFEFB8C8)
//
//val Purple40 = Color(0xFF6650a4)
//val PurpleGrey40 = Color(0xFF625b71)
//val Pink40 = Color(0xFF7D5260)
val Primary = Color(0xFF2687EE)
val Secondary = Color(0xFFF3994A)
val Tertiary = Color(0xFFE76D3C)
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/theme/Color.kt
|
3105336356
|
package sq.mayv.aegyptus.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Primary,
secondary = Secondary,
tertiary = Tertiary,
onPrimary = Color.White,
onSecondary = Color.Black,
onTertiary = Color.Black,
)
private val LightColorScheme = lightColorScheme(
primary = Primary,
secondary = Secondary,
tertiary = Tertiary,
onPrimary = Color.White,
onSecondary = Color.Black,
onTertiary = Color.Black,
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun AegyptusTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = false,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = Color(0xFF2687EE).toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/theme/Theme.kt
|
3033134756
|
package sq.mayv.aegyptus.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
)
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/ui/theme/Type.kt
|
293865896
|
package sq.mayv.aegyptus.repository
import com.mayv.ctgate.data.Resource
import sq.mayv.aegyptus.dto.SavePlace
import sq.mayv.aegyptus.model.Place
import sq.mayv.aegyptus.model.Response
import sq.mayv.aegyptus.network.Api
import javax.inject.Inject
class FavoritesRepository @Inject constructor(
private val api: Api
) {
suspend fun getAllFavorites(authToken: String): Resource<List<Place>> {
val resource = Resource<List<Place>>()
try {
val response = api.getAllFavorites(authToken = authToken)
resource.statusCode = response.code()
if (response.isSuccessful) {
resource.data = response.body()
} else {
resource.exception =
if (response.code() == 404) Exception("There is no connection to the server!")
else if (response.code() == 401) Exception("You are not authorized")
else if (response.code() == 400) Exception("Bad Request Exception")
else Exception("Internal Server Error")
}
} catch (exception: Exception) {
resource.exception = exception
resource.statusCode = 400
}
return resource
}
suspend fun addToFavorite(placeId: Int, authToken: String): Resource<Response> {
val resource = Resource<Response>()
try {
val response = api.addToFavorites(body = SavePlace(placeId), authToken = authToken)
resource.statusCode = response.code()
if (response.isSuccessful) {
resource.data = response.body()
} else {
resource.exception =
if (response.code() == 404) Exception("There is no connection to the server!")
else if (response.code() == 401) Exception("You are not authorized")
else if (response.code() == 400) Exception("Bad Request Exception")
else Exception("Internal Server Error")
}
} catch (exception: Exception) {
resource.exception = exception
resource.statusCode = 400
}
return resource
}
suspend fun removeFromFavorites(placeId: Int, authToken: String): Resource<Response> {
val resource = Resource<Response>()
try {
val response = api.removeFromFavorites(placeId = placeId, authToken = authToken)
resource.statusCode = response.code()
if (response.isSuccessful) {
resource.data = response.body()
} else {
resource.exception =
if (response.code() == 404) Exception("There is no connection to the server!")
else if (response.code() == 409) Exception("Unauthorized Connection")
else if (response.code() == 401) Exception("You are not authorized")
else if (response.code() == 400) Exception("Bad Request Exception")
else Exception("Internal Server Error")
}
} catch (exception: Exception) {
resource.exception = exception
resource.statusCode = 400
}
return resource
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/repository/FavoritesRepository.kt
|
1663064428
|
package sq.mayv.aegyptus.repository
import com.mayv.ctgate.data.Resource
import sq.mayv.aegyptus.model.Category
import sq.mayv.aegyptus.network.Api
import javax.inject.Inject
class CategoriesRepository @Inject constructor(
private val api: Api
) {
suspend fun getAll(): Resource<List<Category>> {
val placeResource = Resource<List<Category>>()
try {
val response = api.getAllCategories()
placeResource.statusCode = response.code()
if (response.isSuccessful) {
placeResource.data = response.body()
} else {
placeResource.exception =
if (response.code() == 404) Exception("There is no connection to the server!")
else if (response.code() == 401) Exception("You are not authorized")
else if (response.code() == 400) Exception("Bad Request Exception")
else Exception("Internal Server Error")
}
} catch (exception: Exception) {
placeResource.exception = exception
placeResource.statusCode = 400
}
return placeResource
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/repository/CategoriesRepository.kt
|
1717025087
|
package sq.mayv.aegyptus.repository
import com.mayv.ctgate.data.Resource
import sq.mayv.aegyptus.dto.SignInDto
import sq.mayv.aegyptus.dto.SignUpDto
import sq.mayv.aegyptus.model.Auth
import sq.mayv.aegyptus.network.Api
import javax.inject.Inject
class AuthRepository @Inject constructor(private val api: Api) {
suspend fun signIn(signInBody: SignInDto): Resource<Auth> {
val authResource = Resource<Auth>()
try {
val response = api.signIn(signInBody)
authResource.statusCode = response.code()
if (response.isSuccessful) {
authResource.data = response.body()
} else {
authResource.exception =
if (response.code() == 404) Exception("There is no connection to the server!") else if (response.code() == 409) Exception(
"This email does not exist"
) else if (response.code() == 401) Exception("You have entered a wrong password") else if (response.code() == 400) Exception(
"Bad Request Exception"
) else Exception(
"Internal Server Error"
)
}
} catch (exception: Exception) {
authResource.exception = exception
authResource.statusCode = 400
}
return authResource
}
suspend fun signUp(signUpBody: SignUpDto): Resource<Auth> {
val authResource = Resource<Auth>()
try {
val response = api.signUp(signUpBody)
authResource.statusCode = response.code()
if (response.isSuccessful) {
authResource.data = response.body()
} else {
authResource.exception =
if (response.code() == 404) Exception("There is no connection to the server!") else if (response.code() == 409) Exception(
"This email already in use"
) else if (response.code() == 400) Exception(
"Bad Request Exception"
) else Exception(
"Internal Server Error"
)
}
} catch (exception: Exception) {
authResource.exception = exception
authResource.statusCode = 400
}
return authResource
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/repository/AuthRepository.kt
|
217434201
|
package sq.mayv.aegyptus.repository
import com.mayv.ctgate.data.Resource
import sq.mayv.aegyptus.model.Coordinates
import sq.mayv.aegyptus.model.Place
import sq.mayv.aegyptus.network.Api
import javax.inject.Inject
class PlacesRepository @Inject constructor(
private val api: Api
) {
suspend fun getPlace(placeId: Int, authToken: String): Resource<Place> {
val placeResource = Resource<Place>()
try {
val response = api.getPlaceInfo(id = placeId, authToken = authToken)
placeResource.statusCode = response.code()
if (response.isSuccessful) {
placeResource.data = response.body()
} else {
placeResource.exception =
if (response.code() == 404) Exception("There is no connection to the server!")
else if (response.code() == 401) Exception("You are not authorized")
else if (response.code() == 400) Exception("Bad Request Exception")
else Exception("Internal Server Error")
}
} catch (exception: Exception) {
placeResource.exception = exception
placeResource.statusCode = 400
}
return placeResource
}
suspend fun getAllPlaces(governorateCode: Int, authToken: String): Resource<List<Place>> {
val placeResource = Resource<List<Place>>()
try {
val response = api.getAllPlaces(governorate = governorateCode, authToken = authToken)
placeResource.statusCode = response.code()
if (response.isSuccessful) {
placeResource.data = response.body()
} else {
placeResource.exception =
if (response.code() == 404) Exception("There is no connection to the server!")
else if (response.code() == 401) Exception("You are not authorized")
else if (response.code() == 400) Exception("Bad Request Exception")
else Exception("Internal Server Error")
}
} catch (exception: Exception) {
placeResource.exception = exception
placeResource.statusCode = 400
}
return placeResource
}
suspend fun getNearbyPlaces(
coordinates: Coordinates,
maxDistance: Int,
authToken: String
): Resource<List<Place>> {
val placesResource = Resource<List<Place>>()
try {
val response = api.getNearbyPlaces(
latitude = coordinates.latitude,
longitude = coordinates.longitude,
maxDistance = maxDistance,
authToken = authToken
)
placesResource.statusCode = response.code()
if (response.isSuccessful) {
placesResource.data = response.body()
} else {
placesResource.exception =
if (response.code() == 404) Exception("There is no connection to the server!")
else if (response.code() == 401) Exception("You are not authorized")
else if (response.code() == 400) Exception("Bad Request Exception")
else Exception("Internal Server Error")
}
} catch (exception: Exception) {
placesResource.exception = exception
placesResource.statusCode = 400
}
return placesResource
}
suspend fun getMostVisitedPlaces(authToken: String): Resource<List<Place>> {
val placesResource = Resource<List<Place>>()
try {
val response = api.getMostVisitedPlaces(governorateCode = 1, authToken = authToken)
placesResource.statusCode = response.code()
if (response.isSuccessful) {
placesResource.data = response.body()
} else {
placesResource.exception =
if (response.code() == 404) Exception("There is no connection to the server!")
else if (response.code() == 401) Exception("You are not authorized")
else if (response.code() == 400) Exception("Bad Request Exception")
else Exception("Internal Server Error")
}
} catch (exception: Exception) {
placesResource.exception = exception
placesResource.statusCode = 400
}
return placesResource
}
suspend fun search(query: String, authToken: String): Resource<List<Place>> {
val placesResource = Resource<List<Place>>()
try {
val response = api.search(query = query, authToken = authToken)
placesResource.statusCode = response.code()
if (response.isSuccessful) {
placesResource.data = response.body()
} else {
placesResource.exception =
if (response.code() == 404) Exception("There is no connection to the server!")
else if (response.code() == 401) Exception("You are not authorized")
else if (response.code() == 400) Exception("Bad Request Exception")
else Exception("Internal Server Error")
}
} catch (exception: Exception) {
placesResource.exception = exception
placesResource.statusCode = 400
}
return placesResource
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/repository/PlacesRepository.kt
|
4200773285
|
package sq.mayv.aegyptus
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import android.window.OnBackInvokedDispatcher
import androidx.activity.ComponentActivity
import androidx.activity.addCallback
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.ViewModelProvider
import dagger.hilt.android.AndroidEntryPoint
import sq.mayv.aegyptus.ui.navigation.AppNavigation
import sq.mayv.aegyptus.ui.screens.splash.SplashViewModel
import sq.mayv.aegyptus.ui.theme.AegyptusTheme
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
private var pressedTime: Long = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val splashViewModel: SplashViewModel = ViewModelProvider(this)[SplashViewModel::class.java]
installSplashScreen().setKeepOnScreenCondition {
splashViewModel.isLoading.value
}
setContent {
AegyptusTheme {
AppMain(splashViewModel.startDestination.value)
}
}
if (Build.VERSION.SDK_INT >= 33) {
onBackInvokedDispatcher.registerOnBackInvokedCallback(
OnBackInvokedDispatcher.PRIORITY_DEFAULT
) {
if (pressedTime + 2000 > System.currentTimeMillis()) {
finish()
} else {
Toast.makeText(
this@MainActivity,
"Press back again to exit",
Toast.LENGTH_SHORT
).show()
}
pressedTime = System.currentTimeMillis()
}
} else {
onBackPressedDispatcher.addCallback(this) {
if (pressedTime + 2000 > System.currentTimeMillis()) {
finish()
} else {
Toast.makeText(
this@MainActivity,
"Press back again to exit",
Toast.LENGTH_SHORT
).show()
}
pressedTime = System.currentTimeMillis()
}
}
}
}
@Composable
private fun AppMain(startDestination: String) {
Surface(modifier = Modifier.fillMaxSize()) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
AppNavigation(startDestination)
}
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/MainActivity.kt
|
1995198233
|
package sq.mayv.aegyptus.di
import android.content.Context
import android.content.SharedPreferences
import com.google.android.gms.location.LocationServices
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import sq.mayv.aegyptus.data.ILocationService
import sq.mayv.aegyptus.data.LocationService
import sq.mayv.aegyptus.network.Api
import sq.mayv.aegyptus.repository.AuthRepository
import sq.mayv.aegyptus.repository.CategoriesRepository
import sq.mayv.aegyptus.repository.FavoritesRepository
import sq.mayv.aegyptus.repository.PlacesRepository
import sq.mayv.aegyptus.util.PreferenceHelper
import sq.mayv.aegyptus.util.PreferenceHelper.baseUrl
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
fun provideAuthRepository(api: Api) = AuthRepository(api)
@Provides
fun provideFavoritesRepository(api: Api) = FavoritesRepository(api)
@Provides
fun providePlacesRepository(api: Api) = PlacesRepository(api)
@Provides
fun provideCategoriesRepository(api: Api) = CategoriesRepository(api)
@Singleton
@Provides
fun provideLocationClient(
@ApplicationContext context: Context
): ILocationService = LocationService(
context,
LocationServices.getFusedLocationProviderClient(context)
)
@Provides
fun providePreferences(@ApplicationContext context: Context): SharedPreferences {
return PreferenceHelper.getPreference(context)
}
@Singleton
@Provides
fun provideApi(preferences: SharedPreferences): Api {
val baseUrl = preferences.baseUrl
val client = OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.MINUTES).build()
return Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
.create(Api::class.java)
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/di/AppModule.kt
|
3991287063
|
package sq.mayv.aegyptus.extension
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.unit.IntSize
fun Modifier.shimmer(): Modifier = composed {
var size by remember {
mutableStateOf(IntSize.Zero)
}
val transition = rememberInfiniteTransition(label = "Transition")
val startOffset by transition.animateFloat(
initialValue = (-1 * size.width.toFloat()) - 10,
targetValue = (size.width.toFloat() + 10),
animationSpec = infiniteRepeatable(
animation = tween(1500)
),
label = "Start Offset"
)
background(
brush = Brush.linearGradient(
colors = listOf(
Color(0xFFd9d9d9),
Color.White,
Color(0xFFd9d9d9)
),
start = Offset(startOffset, (size.height.toFloat() / 2)),
end = Offset(startOffset + size.width.toFloat(), (size.height.toFloat() / 2))
)
)
.onGloballyPositioned {
size = it.size
}
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/extension/shimmer.kt
|
2194201025
|
package sq.mayv.aegyptus.extension
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import androidx.core.content.ContextCompat
fun Context.hasLocationPermission(): Boolean {
return ContextCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
) == PackageManager.PERMISSION_GRANTED
}
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/extension/hasLocationPermission.kt
|
3538677160
|
package sq.mayv.aegyptus.extension
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.model.LatLng
import com.google.maps.android.compose.CameraPositionState
suspend fun CameraPositionState.centerOnLocation(
location: LatLng
) = animate(
update = CameraUpdateFactory.newLatLngZoom(
location,
15f
),
durationMs = 1500
)
|
Aegyptus/app/src/main/java/sq/mayv/aegyptus/extension/centerOnLocation.kt
|
3857643647
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.