path
stringlengths 4
297
| contentHash
stringlengths 1
10
| content
stringlengths 0
13M
|
---|---|---|
starwars-app/app/src/main/java/com/rishi/groww/assignment/starwars/view/fragment/FilterBottomSheet.kt | 3507766949 | package com.rishi.groww.assignment.starwars.view.fragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.rishi.groww.assignment.starwars.R
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [FilterBottomSheet.newInstance] factory method to
* create an instance of this fragment.
*/
class FilterBottomSheet : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_filter_bottom_sheet, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment FilterBottomSheet.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
FilterBottomSheet().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} |
starwars-app/app/src/main/java/com/rishi/groww/assignment/starwars/application/StarWarsApplication.kt | 1348300968 | package com.rishi.groww.assignment.starwars.application
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
import timber.log.Timber
@HiltAndroidApp
class StarWarsApplication : Application() {
override fun onCreate() {
super.onCreate()
Timber.plant(Timber.DebugTree())
}
} |
Android_TA_Travelapp3/app/src/androidTest/java/de/syntax_institut/android_ta_travelapp/ExampleInstrumentedTest.kt | 3170405034 | package de.syntax_institut.android_ta_travelapp
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* 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("de.syntax_institut.android_ta_travelapp", appContext.packageName)
}
} |
Android_TA_Travelapp3/app/src/test/java/de/syntax_institut/android_ta_travelapp/ExampleUnitTest.kt | 2072461623 | package de.syntax_institut.android_ta_travelapp
import org.junit.Test
import org.junit.Assert.*
/**
* 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)
}
} |
Android_TA_Travelapp3/app/src/main/java/de/syntax_institut/android_ta_travelapp/MainActivity.kt | 2270549039 | package de.syntax_institut.android_ta_travelapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} |
Android-Video-Call-Live-Streaming-Zegocloud/app/src/androidTest/java/com/codingambitions/zegocloudexample1/ExampleInstrumentedTest.kt | 945519210 | package com.codingambitions.zegocloudexample1
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* 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("com.codingambitions.zegocloudexample1", appContext.packageName)
}
} |
Android-Video-Call-Live-Streaming-Zegocloud/app/src/test/java/com/codingambitions/zegocloudexample1/ExampleUnitTest.kt | 3725130702 | package com.codingambitions.zegocloudexample1
import org.junit.Test
import org.junit.Assert.*
/**
* 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)
}
} |
Android-Video-Call-Live-Streaming-Zegocloud/app/src/main/java/com/codingambitions/zegocloudexample1/ui/theme/Color.kt | 2638063288 | package com.codingambitions.zegocloudexample1.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) |
Android-Video-Call-Live-Streaming-Zegocloud/app/src/main/java/com/codingambitions/zegocloudexample1/ui/theme/Theme.kt | 4119475413 | package com.codingambitions.zegocloudexample1.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 DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* 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 ZegoCloudExample1Theme(
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 -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} |
Android-Video-Call-Live-Streaming-Zegocloud/app/src/main/java/com/codingambitions/zegocloudexample1/ui/theme/Type.kt | 1074369083 | package com.codingambitions.zegocloudexample1.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
)
*/
) |
Android-Video-Call-Live-Streaming-Zegocloud/app/src/main/java/com/codingambitions/zegocloudexample1/MainActivity.kt | 3328616451 | package com.codingambitions.zegocloudexample1
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.codingambitions.zegocloudexample1.ui.theme.ZegoCloudExample1Theme
import com.zegocloud.uikit.prebuilt.call.ZegoUIKitPrebuiltCallFragment
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ZegoCloudExample1Theme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
TextButton(onClick = {
startActivity(Intent(this, CallActivity::class.java))
}) {
Text(text = "Start Video Call")
}
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
ZegoCloudExample1Theme {
Greeting("Android")
}
} |
Android-Video-Call-Live-Streaming-Zegocloud/app/src/main/java/com/codingambitions/zegocloudexample1/CallActivity.kt | 1967761769 | package com.codingambitions.zegocloudexample1
import android.Manifest
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.textfield.TextInputLayout
import com.permissionx.guolindev.PermissionX
import com.tencent.mmkv.MMKV
import com.zegocloud.uikit.plugin.invitation.ZegoInvitationType
import com.zegocloud.uikit.prebuilt.call.ZegoUIKitPrebuiltCallConfig
import com.zegocloud.uikit.prebuilt.call.ZegoUIKitPrebuiltCallService
import com.zegocloud.uikit.prebuilt.call.event.CallEndListener
import com.zegocloud.uikit.prebuilt.call.event.ErrorEventsListener
import com.zegocloud.uikit.prebuilt.call.event.SignalPluginConnectListener
import com.zegocloud.uikit.prebuilt.call.invite.ZegoUIKitPrebuiltCallInvitationConfig
import com.zegocloud.uikit.prebuilt.call.invite.internal.ZegoCallInvitationData
import com.zegocloud.uikit.prebuilt.call.invite.internal.ZegoUIKitPrebuiltCallConfigProvider
import com.zegocloud.uikit.prebuilt.call.invite.widget.ZegoSendCallInvitationButton
import com.zegocloud.uikit.service.defines.ZegoUIKitUser
import com.zegocloud.uikit.service.express.IExpressEngineEventHandler
import im.zego.zegoexpress.constants.ZegoRoomStateChangedReason
import org.json.JSONObject
import timber.log.Timber
import kotlin.random.Random
class CallActivity : AppCompatActivity() {
private lateinit var userID: String
private lateinit var userName: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_call)
val yourUserID = findViewById<TextView>(R.id.your_user_id)
val yourUserName = findViewById<TextView>(R.id.your_user_name)
userID = Random.nextInt(100000, 999999).toString()
userName = "User_${userID}"
yourUserID.text = getString(R.string.your_user_id, userID)
yourUserName.text = getString(R.string.your_user_name, userName)
val appID: Long = BuildConfig.appID.toLong()
val appSign: String = BuildConfig.appSign
initCallInviteService(appID, appSign, userID, userName)
initVoiceButton()
initVideoButton()
//setLogoutButtonListener()
}
private fun initVideoButton() {
val newVideoCall = findViewById<ZegoSendCallInvitationButton>(R.id.new_video_call)
newVideoCall.setIsVideoCall(true)
//for notification sound
newVideoCall.resourceID = "zego_data"
newVideoCall.setOnClickListener { view ->
val inputLayout = findViewById<TextInputLayout>(R.id.target_user_id)
val targetUserID = inputLayout.editText?.text.toString()
val split = targetUserID.split(",")
val users = ArrayList<ZegoUIKitUser>()
for (userID in split) {
println("userID=$userID")
val userName = "User_${userID}"
users.add(ZegoUIKitUser(userID, userName))
}
newVideoCall.setInvitees(users)
}
}
private fun initVoiceButton() {
val newVoiceCall = findViewById<ZegoSendCallInvitationButton>(R.id.new_voice_call)
newVoiceCall.setIsVideoCall(false)
newVoiceCall.resourceID = "zego_data"
val inputLayout = findViewById<TextInputLayout>(R.id.target_user_id)
val targetUserID = inputLayout.editText?.text.toString()
val split = targetUserID.split(",")
val users = ArrayList<ZegoUIKitUser>()
for (userID in split) {
println("userID=$userID")
val userName = "User_${userID}"
users.add(ZegoUIKitUser(userID, userName))
}
newVoiceCall.setInvitees(users)
}
private fun initCallInviteService(
appID: Long,
appSign: String,
userID: String,
userName: String
) {
val callInvitationConfig = ZegoUIKitPrebuiltCallInvitationConfig().apply {
provider =
ZegoUIKitPrebuiltCallConfigProvider { invitationData -> getConfig(invitationData) }
}
ZegoUIKitPrebuiltCallService.events.errorEventsListener =
ErrorEventsListener { errorCode, message -> Timber.d("onError() called with: errorCode = [$errorCode], message = [$message]") }
ZegoUIKitPrebuiltCallService.events.invitationEvents.pluginConnectListener =
SignalPluginConnectListener { state, event, extendedData -> Timber.d("onSignalPluginConnectionStateChanged() called with: state = [$state], event = [$event], extendedData = [$extendedData]") }
ZegoUIKitPrebuiltCallService.init(
application,
appID,
appSign,
userID,
userName,
callInvitationConfig
)
ZegoUIKitPrebuiltCallService.events.callEvents.callEndListener =
CallEndListener { callEndReason, jsonObject -> Timber.d("onCallEnd() called with: callEndReason = [$callEndReason], jsonObject = [$jsonObject]") }
ZegoUIKitPrebuiltCallService.events.callEvents.setExpressEngineEventHandler(object :
IExpressEngineEventHandler() {
override fun onRoomStateChanged(
roomID: String,
reason: ZegoRoomStateChangedReason,
errorCode: Int,
extendedData: JSONObject
) {
Timber.d("onRoomStateChanged() called with: roomID = [$roomID], reason = [$reason], errorCode = [$errorCode], extendedData = [$extendedData]")
}
})
}
override fun onBackPressed() {
super.onBackPressed()
val builder = AlertDialog.Builder(this@CallActivity)
builder.setTitle("Sign Out")
builder.setMessage("Are you sure to Sign Out?After Sign out you can't receive offline calls")
builder.setNegativeButton(R.string.call_cancel) { dialog, _ -> dialog.dismiss() }
builder.setPositiveButton(R.string.call_ok) { dialog, _ ->
dialog.dismiss()
signOut()
finish()
}
builder.create().show()
}
private fun getConfig(invitationData: ZegoCallInvitationData): ZegoUIKitPrebuiltCallConfig {
val isVideoCall = invitationData.type == ZegoInvitationType.VIDEO_CALL.value
val isGroupCall = invitationData.invitees.size > 1
return when {
isVideoCall && isGroupCall -> ZegoUIKitPrebuiltCallConfig.groupVideoCall()
!isVideoCall && isGroupCall -> ZegoUIKitPrebuiltCallConfig.groupVoiceCall()
!isVideoCall -> ZegoUIKitPrebuiltCallConfig.oneOnOneVoiceCall()
else -> ZegoUIKitPrebuiltCallConfig.oneOnOneVideoCall()
}
}
override fun onDestroy() {
super.onDestroy()
ZegoUIKitPrebuiltCallService.endCall()
}
private fun setLogoutButtonListener() {
findViewById<TextView>(R.id.user_logout).setOnClickListener {
val builder = AlertDialog.Builder(this@CallActivity)
builder.setTitle("Sign Out")
builder.setMessage("Are you sure to Sign Out?After Sign out you can't receive offline calls")
builder.setNegativeButton(R.string.call_cancel) { dialog, _ -> dialog.dismiss() }
builder.setPositiveButton(R.string.call_ok) { dialog, _ ->
dialog.dismiss()
signOut()
finish()
}
builder.create().show()
}
}
private fun signOut() {
MMKV.defaultMMKV().remove("user_id")
MMKV.defaultMMKV().remove("user_name")
ZegoUIKitPrebuiltCallService.unInit()
}
fun offlineUsePermission() {
PermissionX.init(this).permissions(Manifest.permission.SYSTEM_ALERT_WINDOW)
.onExplainRequestReason { scope, deniedList ->
val message =
"We need your consent for the following permissions in order to use the offline call function properly"
scope.showRequestReasonDialog(deniedList, message, "Allow", "Deny")
}.request { _, _, _ -> }
}
} |
CCL3-stash/app/src/androidTest/java/com/cc221012_cc221016/stash/ExampleInstrumentedTest.kt | 22070981 | package com.cc221012_cc221016.stash
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* 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("com.cc221012_cc221016.stash", appContext.packageName)
}
} |
CCL3-stash/app/src/test/java/com/cc221012_cc221016/stash/ExampleUnitTest.kt | 2181090182 | package com.cc221012_cc221016.stash
import org.junit.Test
import org.junit.Assert.*
/**
* 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)
}
} |
CCL3-stash/app/src/main/java/com/cc221012_cc221016/stash/ui/state/MainViewState.kt | 852151661 | package com.cc221012_cc221016.stash.ui.state
import com.cc221012_cc221016.stash.data.Entries
import com.cc221012_cc221016.stash.data.Users
import com.cc221012_cc221016.stash.ui.views.Screen
data class MainViewState(
val entries: List<Entries> = emptyList(),
val users: List<Users> = emptyList(),
val selectedScreen: Screen = Screen.First,
val openDialog: Boolean = false,
var isUserAuthenticated: Boolean = false
) |
CCL3-stash/app/src/main/java/com/cc221012_cc221016/stash/ui/theme/Color.kt | 3079724024 | package com.cc221012_cc221016.stash.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) |
CCL3-stash/app/src/main/java/com/cc221012_cc221016/stash/ui/theme/Theme.kt | 2954913637 | package com.cc221012_cc221016.stash.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 DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* 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 stashTheme(
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 -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} |
CCL3-stash/app/src/main/java/com/cc221012_cc221016/stash/ui/theme/Type.kt | 3877634197 | package com.cc221012_cc221016.stash.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
)
*/
) |
CCL3-stash/app/src/main/java/com/cc221012_cc221016/stash/ui/views/MainViews.kt | 3692978474 | package com.cc221012_cc221016.stash.ui.views
import android.util.Log
import android.widget.Toast
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.platform.LocalContext
import com.cc221012_cc221016.stash.models.MainViewModel
import com.cc221012_cc221016.stash.ui.views.composables.AddEntryView
import com.cc221012_cc221016.stash.ui.views.composables.EditEntryView
import com.cc221012_cc221016.stash.ui.views.composables.HomeView
import com.cc221012_cc221016.stash.ui.views.composables.LoginRegisterView
import com.cc221012_cc221016.stash.ui.views.composables.ShowEntryView
sealed class Screen {
object First: Screen()
}
@Composable
fun MainView(mainViewModel: MainViewModel) {
val mainViewState by mainViewModel.mainViewState.collectAsState()
val users by mainViewModel.initialGetUsers().collectAsState(emptyList())
Log.d("MainView", "MainView: $mainViewState")
Log.d("MainView", "Got Users: $users")
val context = LocalContext.current
val selectedEntry by mainViewModel.selectedEntry.collectAsState()
val currentScreen by mainViewModel.currentScreen.collectAsState()
if (mainViewState.isUserAuthenticated) {
when (currentScreen) {
"Home" -> HomeView(
mainViewModel = mainViewModel,
navigateToShowEntry = { entry ->
mainViewModel.setSelectedEntry(entry)
mainViewModel.setCurrentScreen("ShowEntry")
},
onAddEntryClick = {
mainViewModel.setCurrentScreen("AddEntry")
}
)
"ShowEntry" -> selectedEntry?.let { entry ->
ShowEntryView(
entryId = entry.entryID,
onBack = { mainViewModel.setCurrentScreen("Home") },
onDeleteEntry = { entryToDelete ->
mainViewModel.deleteEntry(entryToDelete)
mainViewModel.setCurrentScreen("Home")
Toast.makeText(context, "Entry deleted", Toast.LENGTH_LONG).show()
},
onEditEntry = { entryToEdit ->
mainViewModel.setSelectedEntry(entryToEdit)
mainViewModel.setCurrentScreen("EditEntry")
},
mainViewModel = mainViewModel
)
}
"AddEntry" -> AddEntryView(
mainViewModel = mainViewModel,
onBack = { mainViewModel.setCurrentScreen("Home") },
navigateToShowEntry = { entry ->
mainViewModel.setSelectedEntry(entry)
mainViewModel.setCurrentScreen("ShowEntry")
}
)
"EditEntry" -> selectedEntry?.let { entry ->
EditEntryView(
entry = entry,
onBack = { mainViewModel.setCurrentScreen("ShowEntry") },
onSave = { updatedEntry ->
mainViewModel.updateEntry(updatedEntry)
mainViewModel.setSelectedEntry(updatedEntry)
mainViewModel.setCurrentScreen("ShowEntry")
}
)
}
}
} else {
if (users.isNotEmpty()) {
LoginRegisterView(users[0], mainViewModel)
} else {
LoginRegisterView(null, mainViewModel)
}
}
}
|
CCL3-stash/app/src/main/java/com/cc221012_cc221016/stash/ui/views/composables/ShowEntryView.kt | 157497453 | package com.cc221012_cc221016.stash.ui.views.composables
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.gestures.detectTapGestures
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.material.IconButton
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.outlined.Email
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.res.vectorResource
import com.cc221012_cc221016.stash.R
import com.cc221012_cc221016.stash.data.Entries
import com.cc221012_cc221016.stash.models.MainViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ShowEntryView(
entryId: Int,
onBack: () -> Unit,
mainViewModel: MainViewModel,
onEditEntry: (Entries) -> Unit,
onDeleteEntry: (Entries) -> Unit
) {
val passwordVisibility = remember { mutableStateOf(false) }
//val entryName = remember { mutableStateOf("Instagram") }
//val url = remember { mutableStateOf("https://www.instagram.com/") }
//val email = remember { mutableStateOf("[email protected]") }
//val password = remember { mutableStateOf("password123") }
val focusManager = LocalFocusManager.current
val context = LocalContext.current
val menuExpanded = remember { mutableStateOf(false) }
val showDialog = remember { mutableStateOf(false) }
val entryState = remember { mutableStateOf<Entries?>(null) }
val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val openInBrowserLauncher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { }
LaunchedEffect(entryId) {
entryState.value = mainViewModel.getEntryById(entryId)
}
val entry = entryState.value
BackHandler {
onBack() // Define what should happen when back is pressed
}
MaterialTheme(colorScheme = colorScheme){
if (entry != null) {
Box(
modifier = Modifier
.fillMaxSize()
.pointerInput(Unit) {
detectTapGestures(onTap = { focusManager.clearFocus() })
}
) {
Column(
modifier = Modifier
.fillMaxSize(),
verticalArrangement = Arrangement.Top
) {
TopAppBar(
title = { Text(entry.entryName) },
navigationIcon = {
IconButton(onClick = { onBack() }) {
Icon(Icons.Filled.ArrowBack, contentDescription = "Back")
}
},
actions = {
IconButton(onClick = { menuExpanded.value = true }) {
Icon(
imageVector = ImageVector.vectorResource(id = R.drawable.three_dot_options),
contentDescription = "Options Icon"
)
}
DropdownMenu(
expanded = menuExpanded.value,
onDismissRequest = { menuExpanded.value = false }
) {
DropdownMenuItem(
onClick = {
menuExpanded.value = false
onEditEntry(entry) // Navigate to the EditEntryView
},
text = { Text("Edit Entry") },
leadingIcon = {
Icon(
Icons.Filled.Edit,
contentDescription = "Edit Icon"
)
}
)
DropdownMenuItem(
onClick = { showDialog.value = true },
text = { Text("Delete Entry") },
leadingIcon = {
Icon(
Icons.Filled.Delete,
contentDescription = "Delete Icon"
)
}
)
}
if (showDialog.value) {
AlertDialog(
onDismissRequest = { showDialog.value = false },
title = { Text("Delete Credentials?") },
text = { Text("This action cannot be undone.") },
confirmButton = {
TextButton(
onClick = {
onDeleteEntry(entry) // Delete the entry
showDialog.value = false
menuExpanded.value = false
onBack() // Navigate back after deletion
}
) {
Text("Delete", color = colorScheme.error)
}
},
dismissButton = {
TextButton(
onClick = {
showDialog.value = false
menuExpanded.value = false
}
) {
Text("Cancel", color = colorScheme.primary)
}
}
)
}
},
modifier = Modifier.fillMaxWidth()
)
ListItem(
headlineText = { Text("URL") },
supportingText = { Text(entry.entryUrl) },
leadingContent = {
Icon(
imageVector = ImageVector.vectorResource(id = R.drawable.link),
contentDescription = "URL Icon"
)
},
trailingContent = {
Row {
IconButton(onClick = {
val formattedUrl = formatUrl(entry.entryUrl)
if (formattedUrl != null){
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(formattedUrl))
openInBrowserLauncher.launch(intent)
} else {
Toast.makeText(context, "Invalid URL.", Toast.LENGTH_LONG).show()
}
}) {
Icon(
imageVector = ImageVector.vectorResource(id = R.drawable.open_in_new),
contentDescription = "Open in Browser Icon"
)
}
IconButton(onClick = {
val clip = ClipData.newPlainText("URL", entry.entryUrl)
clipboardManager.setPrimaryClip(clip)
Toast.makeText(context, "URL copied", Toast.LENGTH_LONG).show()
}) {
Icon(
imageVector = ImageVector.vectorResource(id = R.drawable.content_copy),
contentDescription = "Copy Icon"
)
}
}
}
)
Divider()
ListItem(
headlineText = { Text("Email / Username") },
supportingText = { Text(entry.entryUsername) },
leadingContent = {
Icon(
Icons.Outlined.Email,
contentDescription = "Email Icon"
)
},
trailingContent = {
IconButton(onClick = {
val clip = ClipData.newPlainText("Email / Username", entry.entryUsername)
clipboardManager.setPrimaryClip(clip)
Toast.makeText(context, "Email / Username copied", Toast.LENGTH_LONG).show()
}) {
Icon(
imageVector = ImageVector.vectorResource(id = R.drawable.content_copy),
contentDescription = "Copy Icon"
)
}
}
)
Divider()
ListItem(
headlineText = { Text("Password") },
supportingText = { Text(if (passwordVisibility.value) entry.entryPassword else "••••••••") },
leadingContent = {
Icon(
imageVector = ImageVector.vectorResource(id = R.drawable.key),
contentDescription = "Key Icon"
)
},
trailingContent = {
Row {
IconButton(onClick = {
passwordVisibility.value = !passwordVisibility.value
}) {
Icon(
imageVector = if (passwordVisibility.value) ImageVector.vectorResource(
id = R.drawable.visibility_on
) else ImageVector.vectorResource(id = R.drawable.visibility_off),
contentDescription = if (passwordVisibility.value) "Hide password" else "Show password"
)
}
IconButton(onClick = {
val clip = ClipData.newPlainText("Password", entry.entryPassword)
clipboardManager.setPrimaryClip(clip)
Toast.makeText(context, "Password copied", Toast.LENGTH_LONG).show()
}) {
Icon(
imageVector = ImageVector.vectorResource(id = R.drawable.content_copy),
contentDescription = "Copy Icon"
)
}
}
}
)
Divider()
}
}
} else {
// Show progress indicator while loading
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
CircularProgressIndicator()
}
}
}
}
fun formatUrl(url: String): String? {
val urlRegex = "^(http://www.|https://www.|http://|https://)?[a-z0-9]+([-.]{1}[a-z0-9]+)*\\.[a-z]{2,5}(:[0-9]{1,5})?(/.*)?$".toRegex()
return if (urlRegex.matches(url)) {
if (!url.startsWith("http://") && !url.startsWith("https://")) {
"http://$url"
} else {
url
}
} else {
null
}
}
|
CCL3-stash/app/src/main/java/com/cc221012_cc221016/stash/ui/views/composables/EditEntryView.kt | 1151467591 | package com.cc221012_cc221016.stash.ui.views.composables
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
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.rememberScrollState
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.IconButton
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.outlined.Email
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
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.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import com.cc221012_cc221016.stash.R
import com.cc221012_cc221016.stash.data.Entries
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EditEntryView(entry: Entries, onBack: () -> Unit, onSave: (Entries) -> Unit) {
val passwordVisibility = remember { mutableStateOf(false) }
// Initialize state with actual entry data
val nameValue = rememberSaveable { mutableStateOf(entry.entryName) }
val urlValue = rememberSaveable { mutableStateOf(entry.entryUrl) }
val emailValue = rememberSaveable { mutableStateOf(entry.entryUsername) }
val passwordValue = rememberSaveable { mutableStateOf(entry.entryPassword) }
val context = LocalContext.current
var isNameEmpty by remember { mutableStateOf(false) }
var isEmailEmpty by remember { mutableStateOf(false) }
var isPasswordEmpty by remember { mutableStateOf(false) }
val focusManager = LocalFocusManager.current
val nameFocusRequester = remember { FocusRequester() }
val urlFocusRequester = remember { FocusRequester() }
val emailFocusRequester = remember { FocusRequester() }
val passwordFocusRequester = remember { FocusRequester() }
BackHandler {
onBack() // Go back to previous screen
}
MaterialTheme(colorScheme = colorScheme){
Box(
modifier = Modifier
.fillMaxSize()
) {
Column(
modifier = Modifier
.fillMaxSize(),
verticalArrangement = Arrangement.Top
) {
TopAppBar(
title = { Text("Edit Entry") },
navigationIcon = {
IconButton(onClick = { onBack() }) {
Icon(Icons.Filled.ArrowBack, contentDescription = "Back")
}
},
modifier = Modifier.fillMaxWidth()
)
}
Column(
modifier = Modifier
.padding(16.dp)
.padding(top = 50.dp)
.padding(bottom = 50.dp)
.verticalScroll(rememberScrollState()),
) {
OutlinedTextField(
value = nameValue.value,
onValueChange = { newValue ->
nameValue.value = newValue
isNameEmpty = newValue.isEmpty()
},
label = { Text("Name") },
isError = nameValue.value.isEmpty(),
modifier = Modifier.fillMaxWidth().focusRequester(nameFocusRequester),
leadingIcon = {
Icon(
imageVector = ImageVector.vectorResource(id = R.drawable.star),
contentDescription = "Star Icon"
)
},
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
keyboardActions = KeyboardActions(onNext = { urlFocusRequester.requestFocus() }),
)
if (isNameEmpty) Text("Required")
Spacer(modifier = Modifier.height(16.dp))
OutlinedTextField(
value = urlValue.value,
onValueChange = { urlValue.value = it },
label = { Text("URL") },
modifier = Modifier.fillMaxWidth().focusRequester(urlFocusRequester),
leadingIcon = {
Icon(
imageVector = ImageVector.vectorResource(id = R.drawable.link),
contentDescription = "URL Icon"
)
},
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
keyboardActions = KeyboardActions(onNext = { emailFocusRequester.requestFocus() }),
)
Spacer(modifier = Modifier.height(16.dp))
OutlinedTextField(
value = emailValue.value,
onValueChange = { newValue ->
emailValue.value = newValue
isEmailEmpty = newValue.isEmpty()
},
supportingText = { if (isEmailEmpty) Text("Required") },
label = { Text("Email / Username") },
isError = emailValue.value.isEmpty(),
modifier = Modifier.fillMaxWidth().focusRequester(emailFocusRequester),
leadingIcon = {
Icon(
Icons.Outlined.Email,
contentDescription = "Email Icon"
)
},
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
keyboardActions = KeyboardActions(onNext = { passwordFocusRequester.requestFocus() }),
)
Spacer(modifier = Modifier.height(16.dp))
OutlinedTextField(
value = passwordValue.value,
onValueChange = { newValue ->
passwordValue.value = newValue
isPasswordEmpty = newValue.isEmpty()
},
supportingText = { if (isPasswordEmpty) Text("Required") },
label = { Text("Password") },
isError = passwordValue.value.isEmpty(),
modifier = Modifier.fillMaxWidth().focusRequester(passwordFocusRequester),
visualTransformation = if (passwordVisibility.value) VisualTransformation.None else PasswordVisualTransformation(),
leadingIcon = {
Icon(
imageVector = ImageVector.vectorResource(id = R.drawable.key),
contentDescription = "Key Icon"
)
},
trailingIcon = {
IconButton(onClick = {
passwordVisibility.value = !passwordVisibility.value
}) {
Icon(
imageVector = if (passwordVisibility.value) ImageVector.vectorResource(
id = R.drawable.visibility_on
) else ImageVector.vectorResource(id = R.drawable.visibility_off),
contentDescription = if (passwordVisibility.value) "Hide password" else "Show password"
)
}
},
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() }),
)
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
.align(Alignment.BottomCenter)
)
{
Spacer(Modifier.weight(1f))
Button(
onClick = {
// Check if any of the fields are empty
if (nameValue.value.isEmpty() || emailValue.value.isEmpty() || passwordValue.value.isEmpty()) {
Toast.makeText(context, "Please fill in all mandatory fields", Toast.LENGTH_LONG).show()
return@Button // Exit the onClick function
}
// Construct updated entry from user input
val updatedEntry = Entries(
entryName = nameValue.value,
entryUsername = emailValue.value,
entryPassword = passwordValue.value,
entryUrl = urlValue.value,
entryID = entry.entryID // Preserve the original ID
)
onSave(updatedEntry) // Save the updated entry
Toast.makeText(context, "Entry updated", Toast.LENGTH_LONG).show()
},
colors = ButtonDefaults.buttonColors(
containerColor = colorScheme.primary,
contentColor = colorScheme.onPrimary
),
modifier = Modifier
.fillMaxWidth()
) {
Text("Update Entry")
}
}
}
}
} |
CCL3-stash/app/src/main/java/com/cc221012_cc221016/stash/ui/views/composables/AddEntryView.kt | 351388252 | package com.cc221012_cc221016.stash.ui.views.composables
import android.util.Log
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
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.rememberScrollState
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.IconButton
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.outlined.Email
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
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.saveable.rememberSaveable
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.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import com.cc221012_cc221016.stash.R
import com.cc221012_cc221016.stash.data.Entries
import com.cc221012_cc221016.stash.models.MainViewModel
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddEntryView(
mainViewModel: MainViewModel,
onBack: () -> Unit,
navigateToShowEntry: (Entries) -> Unit
) {
val passwordVisibility = rememberSaveable { mutableStateOf(false) }
val nameValue = rememberSaveable { mutableStateOf("") }
val urlValue = rememberSaveable { mutableStateOf("") }
val emailValue = rememberSaveable { mutableStateOf("") }
val passwordValue = rememberSaveable { mutableStateOf("") }
val scope = rememberCoroutineScope()
var isNameEmpty by remember { mutableStateOf(false) }
var isEmailEmpty by remember { mutableStateOf(false) }
var isPasswordEmpty by remember { mutableStateOf(false) }
val focusManager = LocalFocusManager.current
val nameFocusRequester = remember { FocusRequester() }
val urlFocusRequester = remember { FocusRequester() }
val emailFocusRequester = remember { FocusRequester() }
val passwordFocusRequester = remember { FocusRequester() }
val context = LocalContext.current
val colorScheme = colorScheme
BackHandler {
onBack()
}
MaterialTheme(colorScheme = colorScheme){
Box(
modifier = Modifier
.fillMaxSize()
) {
Column(
modifier = Modifier
.fillMaxWidth(),
verticalArrangement = Arrangement.Top
){
TopAppBar(
title = { Text("Add Entry") },
navigationIcon = {
IconButton(onClick = { onBack() }) {
Icon(Icons.Filled.ArrowBack, contentDescription = "Back")
}
},
modifier = Modifier.fillMaxWidth()
)
}
Column(
modifier = Modifier
.padding(16.dp)
.padding(top = 50.dp)
.padding(bottom = 50.dp)
.verticalScroll(rememberScrollState()),
) {
OutlinedTextField(
value = nameValue.value,
onValueChange = { nameValue.value = it },
isError = isNameEmpty,
supportingText = { if (isNameEmpty) Text("Required") },
label = { Text("Name") },
modifier = Modifier.fillMaxWidth().focusRequester(nameFocusRequester),
leadingIcon = {
Icon(
imageVector = ImageVector.vectorResource(id = R.drawable.star),
contentDescription = "Star Icon"
)
},
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
keyboardActions = KeyboardActions(onNext = { urlFocusRequester.requestFocus() }),
)
Spacer(modifier = Modifier.height(16.dp))
OutlinedTextField(
value = urlValue.value,
onValueChange = { urlValue.value = it },
label = { Text("URL") },
modifier = Modifier.fillMaxWidth().focusRequester(urlFocusRequester),
leadingIcon = {
Icon(
imageVector = ImageVector.vectorResource(id = R.drawable.link),
contentDescription = "URL Icon"
)
},
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
keyboardActions = KeyboardActions(onNext = { emailFocusRequester.requestFocus() }),
)
Spacer(modifier = Modifier.height(16.dp))
OutlinedTextField(
value = emailValue.value,
onValueChange = { emailValue.value = it },
isError = isEmailEmpty,
supportingText = { if (isEmailEmpty) Text("Required") },
label = { Text("Email / Username") },
modifier = Modifier.fillMaxWidth().focusRequester(emailFocusRequester),
leadingIcon = {
Icon(
Icons.Outlined.Email,
contentDescription = "Email Icon"
)
},
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
keyboardActions = KeyboardActions(onNext = { passwordFocusRequester.requestFocus() }),
)
Spacer(modifier = Modifier.height(16.dp))
OutlinedTextField(
value = passwordValue.value,
onValueChange = { passwordValue.value = it },
isError = isPasswordEmpty,
supportingText = { if (isPasswordEmpty) Text("Required") },
label = { Text("Password") },
modifier = Modifier.fillMaxWidth().focusRequester(passwordFocusRequester),
visualTransformation = if (passwordVisibility.value) VisualTransformation.None else PasswordVisualTransformation(),
leadingIcon = {
Icon(
imageVector = ImageVector.vectorResource(id = R.drawable.key),
contentDescription = "Key Icon"
)
},
trailingIcon = {
IconButton(onClick = {
passwordVisibility.value = !passwordVisibility.value
}) {
Icon(
imageVector = if (passwordVisibility.value) ImageVector.vectorResource(
id = R.drawable.visibility_on
) else ImageVector.vectorResource(id = R.drawable.visibility_off),
contentDescription = if (passwordVisibility.value) "Hide password" else "Show password"
)
}
},
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() }),
)
}
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.align(Alignment.BottomCenter)
){
Button(
onClick = {
if (nameValue.value.isEmpty() || emailValue.value.isEmpty() || passwordValue.value.isEmpty()) {
Toast.makeText(context, "Please fill out all mandatory fields.", Toast.LENGTH_LONG).show()
isNameEmpty = nameValue.value.isEmpty()
isEmailEmpty = emailValue.value.isEmpty()
isPasswordEmpty = passwordValue.value.isEmpty()
} else {
scope.launch {
try {
val newEntry = Entries(
entryName = nameValue.value,
entryUsername = emailValue.value,
entryPassword = passwordValue.value,
entryUrl = urlValue.value
)
val entryId = mainViewModel.saveEntry(newEntry)
val savedEntry = mainViewModel.getEntryById(entryId.toInt())
navigateToShowEntry(savedEntry)
Toast.makeText(context, "Created new entry", Toast.LENGTH_LONG).show()
} catch (e: Exception) {
Log.e("AddEntryView", "Error: ${e.message}")
Toast.makeText(context, "Error saving entry", Toast.LENGTH_LONG).show()
}
}
}
},
colors = ButtonDefaults.buttonColors(
containerColor = colorScheme.primary,
contentColor = colorScheme.onPrimary
),
modifier = Modifier.fillMaxWidth(1f)
) {
Text("Save Entry")
}
}
}
}
} |
CCL3-stash/app/src/main/java/com/cc221012_cc221016/stash/ui/views/composables/LoginRegisterView.kt | 1347917140 | package com.cc221012_cc221016.stash.ui.views.composables
import android.widget.Toast
import androidx.compose.animation.Crossfade
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.Image
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Icon
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
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.rememberCoroutineScope
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.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
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.TextFieldValue
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import com.cc221012_cc221016.stash.R
import com.cc221012_cc221016.stash.data.Users
import com.cc221012_cc221016.stash.models.MainViewModel
import kotlinx.coroutines.launch
fun isPasswordValid(password: String): Boolean {
val passwordRegex = "^(?=.*[0-9])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,}$".toRegex()
return passwordRegex.matches(password)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LoginRegisterView(user: Users?, viewModel: MainViewModel) {
var password by remember { mutableStateOf(TextFieldValue("")) }
var masterPassword by remember { mutableStateOf(TextFieldValue("")) }
var repeatMasterPassword by remember { mutableStateOf(TextFieldValue("")) }
val coroutineScope = rememberCoroutineScope()
val focusRequester = remember { FocusRequester() }
var isPasswordInvalid by remember { mutableStateOf(false) }
val context = LocalContext.current
Box(contentAlignment = Alignment.Center) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "Stash",
style = MaterialTheme.typography.displayLarge,
modifier = Modifier.padding(top = 100.dp)
)
Image(
painter = painterResource(id = R.drawable.shield),
contentDescription = "Login Icon",
modifier = Modifier
.align(Alignment.CenterHorizontally)
.padding(top = 10.dp)
.size(200.dp),
colorFilter = ColorFilter.tint(Color.White)
)
Column(modifier = Modifier.weight(1f)) {
if (user != null) {
var isPasswordIncorrect by remember { mutableStateOf(false) }
var passwordVisibility by remember { mutableStateOf(false) }
Box(modifier = Modifier.fillMaxSize()) {
Column(
verticalArrangement = Arrangement.Top, // Center the contents vertically
horizontalAlignment = Alignment.CenterHorizontally, // Center the contents horizontally
modifier = Modifier
.fillMaxSize()
.padding(top = 25.dp) // Fill the maximum size
) {
Text(
text = "Please log in using your Masterpassword",
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.padding(bottom = 16.dp)
)
OutlinedTextField(
value = password,
singleLine = true,
onValueChange = { newPassword ->
if (newPassword.text.length <= 50) {
password = newPassword
}
},
label = { Text(text = "Master Password") },
visualTransformation = if (passwordVisibility) VisualTransformation.None else PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = {
isPasswordIncorrect = if (password.text == user.userPassword) {
viewModel.authenticateUser()
false
} else {
true
}
}),
isError = isPasswordIncorrect,
supportingText = { if (isPasswordIncorrect) Text(text = "Incorrect Password") },
trailingIcon = {
IconButton(onClick = { passwordVisibility = !passwordVisibility }) {
Icon(
imageVector = if (passwordVisibility) ImageVector.vectorResource(
id = R.drawable.visibility_on
) else ImageVector.vectorResource(id = R.drawable.visibility_off),
contentDescription = if (passwordVisibility) "Hide password" else "Show password",
tint = MaterialTheme.colorScheme.onSurface // Set the color of the icon
)
}
}
)
}
Column(
verticalArrangement = Arrangement.Top,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxSize()
.padding(top = 110.dp)
) {
Button(
onClick = {
if (password.text == user.userPassword) {
viewModel.authenticateUser()
isPasswordIncorrect = false
} else {
coroutineScope.launch {
isPasswordIncorrect = true
Toast.makeText(context, "Incorrect Password", Toast.LENGTH_LONG).show()
}
}
},
modifier = Modifier
.fillMaxWidth(0.67f)
.padding(top = 40.dp)
) {
Text(text = "Log In")
}
}
}
} else {
var newPWisFocused by remember { mutableStateOf(false) }
var repeatPWisFocused by remember { mutableStateOf(false) }
var masterPasswordVisibility by remember { mutableStateOf(false) }
var repeatMasterPasswordVisibility by remember { mutableStateOf(false) }
var showDialog by remember { mutableStateOf(true) }
if (showDialog) {
AlertDialog(
onDismissRequest = { showDialog = false },
title = { Text(text = "Getting started") },
text = {
val styledText = buildAnnotatedString {
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold, fontSize = MaterialTheme.typography.bodyMedium.fontSize)) {
append("🔒 Your Privacy Comes First: \n")
}
append("We respect your privacy. Your data is yours alone, we do not have access to any of your data.\n\n")
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold, fontSize = MaterialTheme.typography.bodyMedium.fontSize)) {
append("🔑 Create Your Master Password: \n")
}
append("This is the only key to your digital vault. Make it strong and unique. Remember, your master password is not stored anywhere and cannot be recovered if forgotten.\n\n")
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold, fontSize = MaterialTheme.typography.bodyMedium.fontSize)) {
append("⚠️ Don't Forget: \n")
}
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold, fontSize = MaterialTheme.typography.bodyMedium.fontSize, color = MaterialTheme.colorScheme.error)) {
append("If you lose your master password, you lose access to your vault. If you uninstall the app, you lose access to your vault.")
}
append(" There's no way to reset it, as we don't keep a copy. This ensures that only you have access to your passwords.")
}
Text(text = styledText)
},
confirmButton = {
Button(onClick = { showDialog = false }) {
Text("Okay")
}
}
)
}
Text(
text = "Create a Master Password to get started",
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.padding(bottom = 16.dp).align(Alignment.CenterHorizontally)
)
OutlinedTextField(
value = masterPassword,
singleLine = true,
onValueChange = { newMasterPassword -> if (newMasterPassword.text.length <= 50) masterPassword = newMasterPassword },
label = { Text(text = "New Master Password") },
visualTransformation = if (masterPasswordVisibility) VisualTransformation.None else PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Next),
keyboardActions = KeyboardActions(onNext = { focusRequester.requestFocus() }),
modifier = Modifier
.align(Alignment.CenterHorizontally)
.focusRequester(focusRequester)
.onFocusChanged { focusState ->
newPWisFocused = focusState.isFocused
},
trailingIcon = {
IconButton(onClick = { masterPasswordVisibility = !masterPasswordVisibility }) {
Icon(
imageVector = if (masterPasswordVisibility) ImageVector.vectorResource(
id = R.drawable.visibility_on) else ImageVector.vectorResource(
id = R.drawable.visibility_off),
contentDescription = if (masterPasswordVisibility) "Hide password" else "Show password",
tint = MaterialTheme.colorScheme.onSurface // Set the color of the icon
)
}
},
isError = if(newPWisFocused || isPasswordInvalid) {
!isPasswordValid(masterPassword.text)
} else {
false
},
supportingText = {
if(newPWisFocused)PasswordRequirements(masterPassword.text) else {
if (isPasswordInvalid) {
when {
masterPassword.text.isEmpty() -> Text(text = "Please enter a password")
!isPasswordValid(masterPassword.text) -> Text(text = "Password does not meet the requirements")
}
}
}
}
)
OutlinedTextField(
value = repeatMasterPassword,
singleLine = true,
onValueChange = { newRepeatMasterPassword -> if (newRepeatMasterPassword.text.length <= 50) repeatMasterPassword = newRepeatMasterPassword },
label = { Text(text = "Repeat Master Password") },
visualTransformation = if (repeatMasterPasswordVisibility) VisualTransformation.None else PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = {
if (isPasswordValid(masterPassword.text)) {
if (masterPassword.text == repeatMasterPassword.text) {
val newUser = Users(masterPassword.text)
viewModel.saveUser(newUser)
}
}
}),
trailingIcon = {
IconButton(onClick = { repeatMasterPasswordVisibility = !repeatMasterPasswordVisibility }) {
Icon(
imageVector = if (repeatMasterPasswordVisibility)ImageVector.vectorResource(
id = R.drawable.visibility_on
) else ImageVector.vectorResource(id = R.drawable.visibility_off),
contentDescription = if (repeatMasterPasswordVisibility) "Hide password" else "Show password",
tint = MaterialTheme.colorScheme.onSurface // Set the color of the icon
)
}
},
modifier = Modifier
.align(Alignment.CenterHorizontally)
.focusRequester(focusRequester)
.onFocusChanged { focusState ->
repeatPWisFocused = focusState.isFocused
},
isError = if(repeatPWisFocused || isPasswordInvalid) {
!isPasswordValid(repeatMasterPassword.text)
} else {
false
},
supportingText = {if (repeatPWisFocused || isPasswordInvalid){
when {
repeatMasterPassword.text.isEmpty() -> Text(text = "Please repeat password")
masterPassword.text != repeatMasterPassword.text -> Text(text = "Passwords do not match")
}
} }
)
Box {
Column(
verticalArrangement = Arrangement.Top,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxSize()
// .padding(top = 100.dp)
) {
Button(
onClick = {
if (isPasswordValid(masterPassword.text)) {
if (masterPassword.text == repeatMasterPassword.text) {
val newUser = Users(masterPassword.text)
viewModel.saveUser(newUser)
} else {
Toast.makeText(context, "Passwords do not match", Toast.LENGTH_LONG).show()
}
} else {
isPasswordInvalid = true
Toast.makeText(context, "Password does not meet the requirements", Toast.LENGTH_LONG).show()
}
},
modifier = Modifier
.fillMaxWidth(0.67f)
.padding(bottom = 16.dp)
) {
Text(text = "Sign Up with MasterPassword")
}
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.clickable { showDialog = true }
.align(Alignment.CenterHorizontally)
.padding(top = 8.dp)
) {
Text(
text = "Help",
color = MaterialTheme.colorScheme.primary,
textDecoration = TextDecoration.Underline,
style = MaterialTheme.typography.bodyMedium
)
}
}
}
}
}
}
}
}
@Composable
fun PasswordRequirements(password: String, modifier: Modifier = Modifier) {
val colorScheme = MaterialTheme.colorScheme
colorScheme.onSurface
colorScheme.primary
val hasMinLength = password.length >= 8
val hasNumber = password.any { it.isDigit() }
val hasSpecialChar = password.any { !it.isLetterOrDigit() }
val hasUppercase = password.any { it.isUpperCase() }
updateTransition(targetState = password, label = "transition")
val color: Color by animateColorAsState(targetValue = MaterialTheme.colorScheme.onSurface,
label = ""
)
Column(modifier = modifier) {
Crossfade(targetState = !hasMinLength, animationSpec = tween(durationMillis = 1000),
label = ""
) { isVisible ->
if (isVisible) {
RequirementItem(text = "At least 8 characters", requirementMet = hasMinLength, color = color)
}
}
Crossfade(targetState = !hasNumber, animationSpec = tween(durationMillis = 1000),
label = ""
) { isVisible ->
if (isVisible) {
RequirementItem(text = "At least one number", requirementMet = hasNumber, color = color)
}
}
Crossfade(targetState = !hasSpecialChar, animationSpec = tween(durationMillis = 1000),
label = ""
) { isVisible ->
if (isVisible) {
RequirementItem(text = "At least one special character", requirementMet = hasSpecialChar, color = color)
}
}
Crossfade(targetState = !hasUppercase, animationSpec = tween(durationMillis = 1000),
label = ""
) { isVisible ->
if (isVisible) {
RequirementItem(text = "At least one uppercase letter", requirementMet = hasUppercase, color = color)
}
}
}
}
@Composable
fun RequirementItem(text: String, requirementMet: Boolean, color: Color) {
val icon = if (requirementMet) Icons.Filled.Check else Icons.Filled.Close
val displayColor = if (requirementMet) MaterialTheme.colorScheme.primary else color
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = icon,
contentDescription = null,
tint = displayColor
)
Text(
text = text,
color = displayColor,
style = MaterialTheme.typography.bodySmall
)
}
} |
CCL3-stash/app/src/main/java/com/cc221012_cc221016/stash/ui/views/composables/HomeView.kt | 2726281507 | package com.cc221012_cc221016.stash.ui.views.composables
import android.annotation.SuppressLint
import android.content.ClipData
import android.content.Context
import android.util.Log
import android.webkit.URLUtil
import android.widget.Toast
import androidx.compose.foundation.Image
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.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.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.IconButton
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ExitToApp
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.outlined.Edit
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.Divider
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.OutlinedCard
import androidx.compose.material3.Text
import androidx.compose.material3.rememberDrawerState
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.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.unit.dp
import coil.compose.rememberAsyncImagePainter
import com.cc221012_cc221016.stash.R
import com.cc221012_cc221016.stash.data.Entries
import com.cc221012_cc221016.stash.models.MainViewModel
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeView(mainViewModel: MainViewModel, navigateToShowEntry: (Entries) -> Unit, onAddEntryClick: () -> Unit) {
val colorScheme = colorScheme
val mainViewState by mainViewModel.mainViewState.collectAsState()
Log.d("HomeView", "Recomposing with entries: ${mainViewState.entries}")
val context = LocalContext.current
val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager
val scope = rememberCoroutineScope()
val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
MaterialTheme(colorScheme = colorScheme) {
ModalNavigationDrawer(
drawerState = drawerState,
drawerContent = {
ModalDrawerSheet {
Column(
modifier = Modifier
.fillMaxSize()
.padding(vertical = 16.dp),
verticalArrangement = Arrangement.Top // Align top part to the top
) {
// Top part with title
Text(
text = "Stash",
style = MaterialTheme.typography.titleMedium,
modifier = Modifier
.align(Alignment.CenterHorizontally)
.padding(16.dp)
)
Divider()
// Spacer to push the "Log out" button to the bottom
Spacer(modifier = Modifier.weight(1f, fill = true))
// "Log Out" button at the bottom
NavigationDrawerItem(
label = { Text(text = "Log out") },
icon = { Icon(Icons.Default.ExitToApp, contentDescription = "Log Out") },
selected = false,
onClick = { mainViewModel.logOut() },
modifier = Modifier.align(Alignment.End)
)
}
}
},
gesturesEnabled = true
)
{
Box(
modifier = Modifier
.fillMaxSize()
) {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Top
) {
CenterAlignedTopAppBar(
title = {
Row(Modifier.fillMaxWidth()) {
Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
Text("Your Stash")
}
}
},
navigationIcon = {
IconButton(onClick = {
scope.launch {
drawerState.apply {
if (isClosed) open() else close()
}
}
}) {
Icon(Icons.Default.Menu, contentDescription = "Menu")
}
},
modifier = Modifier.fillMaxWidth()
)
}
Column(
modifier = Modifier
.padding(16.dp)
.padding(top = 50.dp)
) {
// Ensure LazyColumn is not in an unbounded vertically expandable container
if (mainViewState.entries.isEmpty()) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.TopCenter
) {
Icon(
painter = painterResource(id = R.drawable.passkey),
contentDescription = "Desired Icon",
modifier = Modifier.size(160.dp),
colorScheme.outline
)
Text(
"Nothing here yet...",
style = MaterialTheme.typography.titleLarge,
modifier = Modifier.align(Alignment.TopCenter).padding(top = 160.dp),
color = colorScheme.outline
)
Text(
"Add an entry to get started",
style = MaterialTheme.typography.titleLarge,
modifier = Modifier.align(Alignment.TopCenter).padding(top = 200.dp),
color = colorScheme.outline
)
}
} else {
LazyColumn {
items(mainViewState.entries) { entry ->
OutlinedCard(
onClick = { navigateToShowEntry(entry) },
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 16.dp)
) {
Row(
modifier = Modifier.padding(16.dp),
verticalAlignment = Alignment.CenterVertically,
) {
// Load and display the favicon or the initial letter
EntryItem(entry)
Spacer(modifier = Modifier.width(16.dp)) // Add spacing here
Column(
modifier = Modifier.weight(1f)
) {
Text(
text = entry.entryName,
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.padding(bottom = 8.dp)
)
Text(
text = entry.entryUsername,
style = MaterialTheme.typography.bodyMedium
)
// You can add more fields here as needed
}
IconButton(onClick = {
val clip = ClipData.newPlainText(
"password",
entry.entryPassword
)
clipboardManager.setPrimaryClip(clip)
Toast.makeText(context, "Password copied to clipboard", Toast.LENGTH_LONG).show()
}) {
Icon(
imageVector = ImageVector.vectorResource(id = R.drawable.content_copy),
contentDescription = "Copy Icon"
)
}
}
}
}
item {
Spacer(modifier = Modifier.height(60.dp))
}
}
}
}
ExtendedFloatingActionButton(
containerColor = MaterialTheme.colorScheme.primary,
contentColor = colorScheme.onPrimary,
onClick = {
onAddEntryClick()
},
icon = { Icon(Icons.Outlined.Edit, contentDescription = "Edit") },
text = { Text("Add entry") },
modifier = Modifier
.align(Alignment.BottomEnd)
.padding(16.dp)
)
}
}
}
}
fun isValidUrl(url: String): Boolean {
// Check if the URL already has a scheme
if (!url.contains(".")) {
return false
}
if (!url.startsWith("://") && !url.startsWith("https://")) {
// Append a default scheme if it's missing
return URLUtil.isValidUrl("http://$url")
}
// URL has a scheme, check it directly
return URLUtil.isValidUrl(url)
}
@SuppressLint("RememberReturnType")
@Composable
fun getFaviconUrl(url: String): String {
val processedUrl = if (url.startsWith("http://") || url.startsWith("https://")) {
url // URL already contains a protocol
} else {
"http://$url" // Add "http://" if URL does not have a protocol
}
return "https://t0.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=$processedUrl&size=64"
}
@Composable
fun EntryInitial(entryName: String) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.size(40.dp)
.background(colorScheme.primary, shape = CircleShape)
.padding(end = 8.dp)
) {
Text(
text = " " + entryName.take(1).uppercase() + " ",
style = MaterialTheme.typography.titleMedium,
color = colorScheme.onPrimary
)
}
}
@Composable
fun EntryItem(entry: Entries) {
val imageUrl = getFaviconUrl(entry.entryUrl)
val loadError = remember { mutableStateOf(false) }
if (!loadError.value && isValidUrl(entry.entryUrl)) {
Image(
painter = rememberAsyncImagePainter(
model = imageUrl,
onError = { loadError.value = true }
),
contentDescription = "Favicon",
modifier = Modifier.size(40.dp)
)
} else {
EntryInitial(entry.entryName)
}
} |
CCL3-stash/app/src/main/java/com/cc221012_cc221016/stash/MainActivity.kt | 3783323486 | package com.cc221012_cc221016.stash
import android.content.Context
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.room.Room
import com.cc221012_cc221016.stash.data.EntriesDatabase
import com.cc221012_cc221016.stash.data.UsersDatabase
import com.cc221012_cc221016.stash.ui.views.MainView
import com.cc221012_cc221016.stash.models.MainViewModel
import com.cc221012_cc221016.stash.ui.theme.stashTheme
import net.sqlcipher.database.SQLiteDatabase
import net.sqlcipher.database.SupportFactory
class MainActivity : ComponentActivity() {
//factory for sqlcipher
private val factory by lazy {
// Retrieve the encrypted passphrase from SharedPreferences
val sharedPreferences = getSharedPreferences("MyAppPreferences", Context.MODE_PRIVATE)
val encryptedPassphrase = sharedPreferences.getString("encryptedPassphraseKey", "")
// Decrypt the passphrase
val decryptedPassphrase = encryptedPassphrase?.let { KeystoreHelper.decryptData(it) }
// Convert passphrase to ByteArray and initialize SupportFactory
val passphrase = SQLiteDatabase.getBytes(decryptedPassphrase?.toCharArray())
SupportFactory(passphrase)
}
// Lazy initialization of EntriesDatabase
private val entriesDB by lazy {
Room.databaseBuilder(this, EntriesDatabase::class.java, "EntriesDatabase.db")
.openHelperFactory(factory)
.build()
}
// Lazy initialization of UsersDatabase
private val usersDB by lazy {
Room.databaseBuilder(this, UsersDatabase::class.java, "UsersDatabase.db")
.openHelperFactory(factory)
.build()
}
//initialize Passphrase if not set
private fun initializePassphraseIfNeeded() {
val sharedPreferences = getSharedPreferences("MyAppPreferences", Context.MODE_PRIVATE)
if (!sharedPreferences.contains("encryptedPassphraseKey")) {
val encryptedPassphrase = KeystoreHelper.encryptData("YourActualPassphrase")
sharedPreferences.edit().putString("encryptedPassphraseKey", encryptedPassphrase)
.apply()
}
}
private val mainViewModel by viewModels<MainViewModel>(
factoryProducer = {
object : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
// Providing both DAOs to the MainViewModel
return MainViewModel(entriesDB.entriesDao, usersDB.usersDao) as T
}
}
}
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
SQLiteDatabase.loadLibs(this) // Load SQLCipher libraries
KeystoreHelper.generateKey() // Ensure the key is generated
// Initialize passphrase at the start
initializePassphraseIfNeeded()
setContent {
stashTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
MainView(mainViewModel)
}
}
}
}
}
|
CCL3-stash/app/src/main/java/com/cc221012_cc221016/stash/models/MainViewModel.kt | 564884883 | package com.cc221012_cc221016.stash.models
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.cc221012_cc221016.stash.data.Entries
import com.cc221012_cc221016.stash.data.EntriesDao
import com.cc221012_cc221016.stash.data.Users
import com.cc221012_cc221016.stash.data.UsersDao
import com.cc221012_cc221016.stash.ui.state.MainViewState
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
class MainViewModel(private val entriesDao: EntriesDao, private val usersDao: UsersDao): ViewModel() {
init {
getEntries() // Fetch entries when ViewModel is created
}
//Entries
private val _entriesState = MutableStateFlow(Entries("","", "", ""))
val entriesState: StateFlow<Entries> = _entriesState.asStateFlow()
//Users
private val _usersState = MutableStateFlow(Users(""))
val usersState: StateFlow<Users> = _usersState.asStateFlow()
//MainViewState
private val _mainViewState = MutableStateFlow(MainViewState())
val mainViewState: StateFlow<MainViewState> = _mainViewState.asStateFlow()
private val _selectedEntry = MutableStateFlow<Entries?>(null)
val selectedEntry = _selectedEntry.asStateFlow()
private val _currentScreen = MutableStateFlow("Home")
val currentScreen = _currentScreen.asStateFlow()
fun logOut() {
viewModelScope.launch {
// Update the state to reflect that the user is not authenticated
_mainViewState.update { currentState ->
currentState.copy(isUserAuthenticated = false)
}
// Perform any additional cleanup or state updates necessary for logging out
}
}
fun setCurrentScreen(screen: String) {
_currentScreen.value = screen
}
fun setSelectedEntry(entry: Entries?) {
_selectedEntry.value = entry
}
//ENTRIES METHODS
//Save an entry
suspend fun saveEntry(entry: Entries): Long {
val id = entriesDao.insertEntry(entry)
getEntries() // Update entries list
return id // Return the generated ID
}
suspend fun getEntryById(id: Int): Entries {
return entriesDao.getEntry(id.toLong()).first()
}
//Get all entries
private fun getEntries() {
viewModelScope.launch {
entriesDao.getEntries().collect { allEntries ->
Log.d("MainViewModel", "Fetched entries: $allEntries")
_mainViewState.update { it.copy(entries = allEntries) }
}
}
}
//Update an entry
fun updateEntry(entry: Entries) {
viewModelScope.launch {
entriesDao.updateEntry(entry)
getEntries() // Refresh the list of entries
}
}
//delete an entry
fun deleteEntry(entry: Entries) {
viewModelScope.launch {
try {
entriesDao.deleteEntry(entry)
getEntries()
} catch (e: Exception) {
Log.e("MainViewModel", "Error deleting entry: ${e.message}")
// Handle the exception appropriately
}
}
}
//USER METHODS
//Save a user
fun saveUser(user: Users){
viewModelScope.launch {
usersDao.insertUser(user)
_mainViewState.update { it.copy(isUserAuthenticated = true) }
}
}
//Get a user
private fun getUsers(){
viewModelScope.launch {
usersDao.getUsers().collect(){ allUsers ->
_mainViewState.update { it.copy(users = allUsers) }
Log.d("MainViewModel", "Fetched users: $allUsers")
}
}
}
fun authenticateUser() {
_mainViewState.update { it.copy(isUserAuthenticated = true) }
}
fun initialGetUsers(): Flow<List<Users>> {
return usersDao.getUsers()
}
fun deleteUser(user: Users){
viewModelScope.launch {
usersDao.deleteUser(user)
}
getUsers()
}
} |
CCL3-stash/app/src/main/java/com/cc221012_cc221016/stash/models/KeyStoreHelper.kt | 264978103 | import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import java.security.KeyStore
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.Cipher
import android.util.Base64
import android.util.Log
import javax.crypto.spec.GCMParameterSpec
object KeystoreHelper {
private const val KEY_ALIAS = "MyKeyAlias"
private const val TRANSFORMATION = "AES/GCM/NoPadding"
fun generateKey() {
val keyStore = KeyStore.getInstance("AndroidKeyStore")
keyStore.load(null)
if (!keyStore.containsAlias(KEY_ALIAS)) {
val keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
val keyGenParameterSpec = KeyGenParameterSpec.Builder(KEY_ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.build()
keyGenerator.init(keyGenParameterSpec)
keyGenerator.generateKey()
}
Log.d("KeystoreHelper", "Key generated or already exists")
}
fun encryptData(data: String): String {
try {
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey())
val encryptionIv = cipher.iv
val encryptedData = cipher.doFinal(data.toByteArray(Charsets.UTF_8))
Log.d("KeystoreHelper", "Encrypted data")
// Combine IV and encrypted data
return Base64.encodeToString(encryptionIv + encryptedData, Base64.DEFAULT)
} catch (e: Exception) {
throw RuntimeException("Failed to encrypt data", e)
}
}
fun decryptData(encryptedData: String): String {
try {
val encryptedBytes = Base64.decode(encryptedData, Base64.DEFAULT)
val cipher = Cipher.getInstance(TRANSFORMATION)
val iv = encryptedBytes.copyOfRange(0, 12)
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(), GCMParameterSpec(128, iv))
val decryptedBytes = cipher.doFinal(encryptedBytes, 12, encryptedBytes.size - 12)
Log.d("KeystoreHelper", "Decrypted data")
return String(decryptedBytes, Charsets.UTF_8)
} catch (e: Exception) {
throw RuntimeException("Failed to decrypt data", e)
}
}
private fun getSecretKey(): SecretKey {
val keyStore = KeyStore.getInstance("AndroidKeyStore")
keyStore.load(null)
Log.d("KeystoreHelper", "Key generated or already exists")
return keyStore.getKey(KEY_ALIAS, null) as SecretKey
}
}
|
CCL3-stash/app/src/main/java/com/cc221012_cc221016/stash/data/EntriesDatabase.kt | 2588981355 | package com.cc221012_cc221016.stash.data
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(entities = [Entries::class], version = 1)
abstract class EntriesDatabase : RoomDatabase() {
abstract val entriesDao: EntriesDao
}
|
CCL3-stash/app/src/main/java/com/cc221012_cc221016/stash/data/UsersDao.kt | 3506181098 | package com.cc221012_cc221016.stash.data
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import kotlinx.coroutines.flow.Flow
@Dao
interface UsersDao {
@Insert
suspend fun insertUser(user: Users)
@Update
suspend fun updateUser(user: Users)
@Delete
suspend fun deleteUser(user: Users)
@Query("SELECT * FROM users")
fun getUsers(): Flow<List<Users>>
} |
CCL3-stash/app/src/main/java/com/cc221012_cc221016/stash/data/Entries.kt | 369124351 | package com.cc221012_cc221016.stash.data
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity (tableName = "entries")
data class Entries(
val entryName: String,
val entryUsername: String,
val entryPassword: String,
val entryUrl: String,
@PrimaryKey(autoGenerate = true) val entryID: Int = 0
) |
CCL3-stash/app/src/main/java/com/cc221012_cc221016/stash/data/Users.kt | 1627411444 | package com.cc221012_cc221016.stash.data
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity (tableName = "users")
data class Users(
val userPassword: String,
@PrimaryKey(autoGenerate = true) val userID: Int = 0
) |
CCL3-stash/app/src/main/java/com/cc221012_cc221016/stash/data/UsersDatabase.kt | 3865216582 | package com.cc221012_cc221016.stash.data
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(entities = [Users::class], version = 1)
abstract class UsersDatabase : RoomDatabase() {
abstract val usersDao: UsersDao
}
|
CCL3-stash/app/src/main/java/com/cc221012_cc221016/stash/data/EntriesDao.kt | 1098431528 | package com.cc221012_cc221016.stash.data
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import kotlinx.coroutines.flow.Flow
@Dao
interface EntriesDao {
@Insert
suspend fun insertEntry(entry: Entries) :Long
@Update
suspend fun updateEntry(entry: Entries)
@Delete
suspend fun deleteEntry(entry: Entries)
@Query("SELECT * FROM entries")
fun getEntries(): Flow<List<Entries>>
@Query("SELECT * FROM entries WHERE entryID = :id")
fun getEntry(id: Long): Flow<Entries>
} |
Coroutain/app/src/androidTest/java/com/example/coroutain/ExampleInstrumentedTest.kt | 3545957376 | package com.example.coroutain
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* 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("com.example.coroutain", appContext.packageName)
}
} |
Coroutain/app/src/test/java/com/example/coroutain/ExampleUnitTest.kt | 3882562846 | package com.example.coroutain
import org.junit.Test
import org.junit.Assert.*
/**
* 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)
}
} |
Coroutain/app/src/main/java/com/example/coroutain/MainActivity.kt | 3989020103 | package com.example.coroutain
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.coroutain.databinding.ActivityMainBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
var remainingTime = 0L
var job : Job? = null
var isPaused = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.btnStop.isEnabled = false
binding.btnStart.isEnabled = false
binding.btnStart.setOnClickListener {
startTimer()
}
binding.btnStop.setOnClickListener {
stopTimer()
}
binding.btnPause.setOnClickListener {
if(!isPaused) {
pauseTimer()
}else {
resumeTimer()
}
}
}
private fun startTimer(){
val inputTime = binding.edInput.text.toString().toLong()
isPaused = false
job= CoroutineScope(Dispatchers.Default).launch {
withContext(Dispatchers.Main){
binding.btnStart.isEnabled = false
binding.btnStop.isEnabled = true
binding.btnPause.isEnabled = true
}
remainingTime = inputTime
while (remainingTime > 0) {
if (isPaused) {
delay(1000)
} else {
updateUi(remainingTime)
delay(1000)
remainingTime--
}
}
updateUi(remainingTime)
}
binding.btnStart.isEnabled = true
binding.btnStop.isEnabled = false
binding.btnPause.isEnabled = false
}
private fun stopTimer(){
job?.cancel()
//binding.tvOutput.text = "Timer stopped"
binding.btnStart.isEnabled = true
binding.btnStop.isEnabled = false
binding.btnPause.isEnabled = false
}
private fun pauseTimer() {
isPaused = true
binding.btnPause.text = "Resume"
}
private fun resumeTimer() {
isPaused = true
binding.btnPause.text = "Pause"
}
private suspend fun updateUi(time: Long){
withContext(Dispatchers.Main) {
binding.tvOutput.text = "Time remaining: ${time}"
}
}
} |
json_editing/app/src/androidTest/java/com/example/json_editing/ExampleInstrumentedTest.kt | 1475109630 | package com.example.json_editing
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* 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("com.example.json_editing", appContext.packageName)
}
} |
json_editing/app/src/test/java/com/example/json_editing/ExampleUnitTest.kt | 495137644 | package com.example.json_editing
import org.junit.Test
import org.junit.Assert.*
/**
* 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)
}
} |
json_editing/app/src/main/java/com/example/json_editing/MainActivity.kt | 2552386153 | package com.example.json_editing
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val disclosures = listOf(
"WyJtN2ZmSGJrbWJMemtSdWw0bkgxekN3IiwibGFzdE5hbWUiLCJEb2UiXQ==",
"WyJjdUZSSXRwaEViVE9IOU4zTHh1VE1RIiwic2VyaWFsTnVtYmVyIiwiMTIzNDUiXQ==",
"WyJMZWVCeWJ6Uk1YWEtRVjVRNm5sc09RIiwiZ2VuZGVyIiwiTWFsZSJd",
"WyJveThaaW9kY0diNWR1RGZwc0dwVy1RIiwiZmlyc3ROYW1lIiwiSm9obiJd",
"WyJOSzIzX0F6dmdPclFjc3NNUGItVEV3IiwibmF0aW9uYWxpdHkiLCJFVSJd"
)
val originalJson = """{
"@context": [
"https://www.w3.org/2018/credentials/v1",
"https://purl.imsglobal.org/spec/ob/v3p0/context.json"
],
"id": "urn:uuid:ca2bd80d-d953-41fa-a033-53930bd5e5c0",
"type": [
"VerifiableCredential",
"Passport"
],
"name": "JFF x vc-edu PlugFest 3 Interoperability",
"issuer": {
"type": [
"Profile"
],
"id": "did:key:z6MkjoRhq1jSNJdLiruSXrFFxagqrztZaXHqHGUTKJbcNywp",
"name": "Jobs for the Future (JFF)",
"url": "https://www.jff.org/",
"image": "https://w3c-ccg.github.io/vc-ed/plugfest-1-2022/images/JFF_LogoLockup.png"
},
"issuanceDate": "2024-03-19T10:54:03.017124893Z",
"expirationDate": "2025-03-19T10:54:03.017160173Z",
"credentialSubject": {
"cred": {
"_sd": [
"9soGNMzf-tbcvnTgnt8oWCRPve6EphhNX8BHbieIJ-A",
"jw-ybk660khxWyQhu29rN_PF6LTSy5m6vOC2tGOIW74",
"cVl5HkJyjv_vTPGWbun11gbgd2mDWzyhew-1OPkmh6g",
"IBFmE-8fcoAVSPkmzA6VMbArMJHiPmNXgeXbnDlQWy8",
"50ZJpOPR3B0Z3tbjUeK-fexOTt8zoEdL80-1nXZ4c38"
]
},
"serialNumber": "12345",
"personalNumber": "123456789",
"issuerAuthority": "EU",
"expiryDate": "12-12-2026",
"id": "did:key:z2dmzD81cgPx8Vki7JbuuMmFYrWPgYoytykUZ3eyqht1j9KbndeoNhFTpdnkqkkC85C6ChoYBrhrRrjGu7dW5TrChVuKusBiy8Wrz6Gmz9WC2fBB5qtc1B6uDeLHmzNLVQxqQwkDT2WdSFsYVMswYYePR9T5xNF9xMiz2UbBQ9JeGsNMPi#z2dmzD81cgPx8Vki7JbuuMmFYrWPgYoytykUZ3eyqht1j9KbndeoNhFTpdnkqkkC85C6ChoYBrhrRrjGu7dW5TrChVuKusBiy8Wrz6Gmz9WC2fBB5qtc1B6uDeLHmzNLVQxqQwkDT2WdSFsYVMswYYePR9T5xNF9xMiz2UbBQ9JeGsNMPi",
"_sd": [
"9soGNMzf-tbcvnTgnt8oWCRPve6EphhNX8BHbieIJ-A",
"jw-ybk660khxWyQhu29rN_PF6LTSy5m6vOC2tGOIW74",
"cVl5HkJyjv_vTPGWbun11gbgd2mDWzyhew-1OPkmh6g",
"IBFmE-8fcoAVSPkmzA6VMbArMJHiPmNXgeXbnDlQWy8",
"50ZJpOPR3B0Z3tbjUeK-fexOTt8zoEdL80-1nXZ4c38"
]
},
"_sd": [
"9soGNMzf-tbcvnTgnt8oWCRPve6EphhNX8BHbieIJ-A",
"jw-ybk660khxWyQhu29rN_PF6LTSy5m6vOC2tGOIW74",
"cVl5HkJyjv_vTPGWbun11gbgd2mDWzyhew-1OPkmh6g",
"IBFmE-8fcoAVSPkmzA6VMbArMJHiPmNXgeXbnDlQWy8",
"50ZJpOPR3B0Z3tbjUeK-fexOTt8zoEdL80-1nXZ4c38"
]
}"""
val modifiedJson = JsonModifier.addTestKey(originalJson, disclosures)
println("Resulted json is :$modifiedJson")
}
} |
json_editing/app/src/main/java/com/example/json_editing/jsonModifier.kt | 3186979655 | import android.util.Base64
import android.util.Log
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import java.security.MessageDigest
object JsonModifier {
private const val TAG = "JsonModifier"
private fun calculateSHA256Hash(inputString: String?): String? {
if (inputString == null)
return null
val decodedBytes = inputString.toByteArray(Charsets.UTF_8)
val sha256Digest = MessageDigest.getInstance("SHA-256").digest(decodedBytes)
val base64urlEncodedHash = Base64.encodeToString(
sha256Digest,
Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING
)
return base64urlEncodedHash
}
private fun decodeBase64(encodedString: String): String {
val decodedBytes = Base64.decode(encodedString, Base64.DEFAULT)
return String(decodedBytes, Charsets.UTF_8)
}
private fun extractKeyValue(decodedString: String): Pair<String, String> {
val jsonArray = JsonParser.parseString(decodedString).asJsonArray
val key = jsonArray[1].asString
val value = jsonArray[2].asString
return Pair(key, value)
}
fun addTestKey(jsonString: String, disclosures: List<String>): String {
val gson = Gson()
val jsonObject = gson.fromJson(jsonString, JsonObject::class.java)
val hashList: MutableList<String> = mutableListOf()
disclosures.forEach { encodedString ->
try {
val hash = calculateSHA256Hash(encodedString)
if (hash != null) {
hashList.add(hash)
}
} catch (e: IllegalArgumentException) {
// Handle invalid base64-encoded strings
Log.e(TAG, "Invalid base64-encoded string: $encodedString")
}
}
addTestKeyRecursively(jsonObject, disclosures, hashList)
return gson.toJson(jsonObject)
}
private fun addTestKeyRecursively(
jsonElement: JsonElement,
disclosures: List<String>,
hashList: MutableList<String>
) {
if (jsonElement.isJsonObject) {
val jsonObject = jsonElement.asJsonObject
if (jsonObject.has("_sd")) {
val sdList = jsonObject.getAsJsonArray("_sd")
hashList.forEachIndexed { index, hash ->
val sdKey = sdList[index].asString
if (hash == sdKey) {
try {
val disclosure = decodeBase64(disclosures[index])
// Extract key-value pair from the encodedString
val (decodedKey, decodedValue) = extractKeyValue(disclosure)
Log.d(TAG, "decodedKey:decodedValue = $decodedKey:$decodedValue")
// Add key-value pair to jsonObject
jsonObject.addProperty(decodedKey, decodedValue)
} catch (e: IllegalArgumentException) {
// Handle invalid base64-encoded strings
Log.e(TAG, "Invalid base64-encoded string in _sd list: $sdKey")
}
}
}
}
jsonObject.entrySet().forEach { (_, value) ->
addTestKeyRecursively(value, disclosures, hashList)
}
} else if (jsonElement.isJsonArray) {
jsonElement.asJsonArray.forEach { arrayElement ->
addTestKeyRecursively(arrayElement, disclosures, hashList)
}
}
}
}
|
cbor/lib/src/jvmTest/kotlin/io/github/routis/cbor/CborSpecTests.kt | 2871158251 | package io.github.routis.cbor
import kotlinx.serialization.json.*
import okio.FileSystem
import okio.Path.Companion.toPath
import org.junit.jupiter.api.DynamicTest
import org.junit.jupiter.api.DynamicTest.dynamicTest
import org.junit.jupiter.api.TestFactory
import org.junit.jupiter.api.assertDoesNotThrow
import kotlin.test.assertEquals
class CborSpecTests {
@TestFactory
fun decodeTests() = readTestVectors().map { decodeTest(it) }
@TestFactory
fun encodeTests() =
readTestVectors()
.filter { it.roundTrip }
.map { encodeTest(it) }
private fun encodeTest(tv: TestVector): DynamicTest {
val dataItem = decode(tv.bytes).also { println(it) }
return dynamicTest("given a cbor \"${dataItem}\", when encoded, then it should produce ${tv.hex}") {
val bytes = encode(dataItem)
val expected = tv.hex
val actual = bytes.toHexString()
assertEquals(expected, actual)
}
}
private fun decodeTest(tv: TestVector): DynamicTest {
fun DataItem.assertJsonIs(
expected: JsonElement,
dataItemJson: JsonElement?,
) {
when (this) {
is SinglePrecisionFloatDataItem ->
assertEquals(
expected.jsonPrimitive.floatOrNull,
dataItemJson?.jsonPrimitive?.floatOrNull,
)
is DoublePrecisionFloatDataItem ->
assertEquals(
expected.jsonPrimitive.doubleOrNull,
dataItemJson?.jsonPrimitive?.doubleOrNull,
)
is HalfPrecisionFloatDataItem ->
assertEquals(
expected.jsonPrimitive.floatOrNull,
dataItemJson?.jsonPrimitive?.floatOrNull,
)
else -> assertEquals(expected, dataItemJson)
}
}
return dynamicTest("given a \"${tv.hex}\", decode() should produce ${tv.decoded ?: tv.diagnostic}}") {
val dataItem =
assertDoesNotThrow("Failed decode") {
decode(tv.bytes)
}.also { println(it) }
val dataItemJson = assertDoesNotThrow("Failed toJson for ${dataItem.javaClass}") { dataItem.toJson() }
tv.decoded?.let { elem -> dataItem.assertJsonIs(elem, dataItemJson) }
}
}
}
fun readTestVectors(): List<TestVector> =
FileSystem.RESOURCES.read("appendix_a.json".toPath()) {
jsonSupport.decodeFromStream<List<TestVector>>(this.inputStream())
}
|
cbor/lib/src/commonMain/kotlin/io/github/routis/cbor/BigNumSupport.kt | 2151139012 | package io.github.routis.cbor
import com.ionspin.kotlin.bignum.integer.BigInteger
import com.ionspin.kotlin.bignum.integer.Sign
fun IntegerDataItem.asBigInteger(): BigInteger =
when (this) {
is UnsignedIntegerDataItem -> BigInteger.fromULong(value)
is NegativeIntegerDataItem -> BigInteger.fromULong(value).toCborNegative()
}
fun BigNumUnsigned.asBigInteger(): BigInteger = BigInteger.fromByteString(content)
fun BigNumNegative.asBigInteger(): BigInteger = BigInteger.fromByteString(content).toCborNegative()
private fun BigInteger.Companion.fromByteString(byteString: ByteStringDataItem) = fromByteArray(byteString.bytes, Sign.POSITIVE)
private fun BigInteger.toCborNegative(): BigInteger {
check(this >= BigInteger.ZERO) { "Applicable to integers greater equal to zero" }
return -(BigInteger.ONE + this)
}
|
cbor/lib/src/commonMain/kotlin/io/github/routis/cbor/internal/MajorType.kt | 2300766049 | package io.github.routis.cbor.internal
/**
* The three higher bits of the initial byte.
* By definition, there are eight major types from zero to seven.
*
* To obtain the [MajorType] from an initial byte use [fromInitialByte]
*/
internal enum class MajorType {
Zero,
One,
Two,
Three,
Four,
Five,
Six,
Seven,
;
companion object {
/**
* Keeps the three high-order bytes of the [initialByte]
*/
fun fromInitialByte(initialByte: UByte): MajorType {
// Take the 3 bits and moved the 5 positions to the right
// filling left positions with zeros
val highOrder3Bits = initialByte.toInt() ushr 5
return when (highOrder3Bits) {
0 -> Zero
1 -> One
2 -> Two
3 -> Three
4 -> Four
5 -> Five
6 -> Six
7 -> Seven
else -> error("Cannot happen, since we use only 3bits")
}
}
}
}
/**
* The five lower bits of the initial byte.
* By definition [value] is in the range 0..31 inclusive.
*
* To obtain additional info from initial byte use [fromInitialByte]
*
*/
internal class AdditionalInfo(val value: UByte) : Comparable<AdditionalInfo> {
init {
require(value in ZERO..THIRTY_ONE) { "Value should be between $ZERO .. $THIRTY_ONE" }
}
override fun compareTo(other: AdditionalInfo): Int = this.value.compareTo(other.value)
override fun toString(): String = "AdditionalInfo(value=$value)"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as AdditionalInfo
return value == other.value
}
override fun hashCode(): Int {
return value.hashCode()
}
companion object {
private const val ZERO: UByte = 0u
private const val THIRTY_ONE: UByte = 31u
const val SINGLE_BYTE_UINT: UByte = 24u
const val DOUBLE_BYTE_UINT: UByte = 25u
const val FOUR_BYTE_UINT: UByte = 26u
const val EIGHT_BYTE_UINT: UByte = 27u
const val INDEFINITE_LENGTH_INDICATOR: UByte = 31u
const val BOOLEAN_FALSE: UByte = 20u
const val BOOLEAN_TRUE: UByte = 21u
const val NULL: UByte = 22u
const val UNDEFINED: UByte = 23u
const val RESERVED_OR_UNASSIGNED: UByte = 24u
const val HALF_PRECISION_FLOAT: UByte = 25u
const val SINGLE_PRECISION_FLOAT: UByte = 26u
const val DOUBLE_PRECISION_FLOAT: UByte = 27u
const val BREAK: UByte = 31u
val ZeroToTwentyThreeRange: ULongRange = 0uL..<SINGLE_BYTE_UINT.toULong()
private val SingleByteRange: ULongRange = SINGLE_BYTE_UINT.toULong()..UByte.MAX_VALUE.toULong()
private val DoubleByteRange: ULongRange = UByte.MAX_VALUE.toULong().inc()..UShort.MAX_VALUE.toULong()
private val FourByteRange: ULongRange = UShort.MAX_VALUE.toULong().inc()..UInt.MAX_VALUE.toULong()
private val EightByteRange: ULongRange = UInt.MAX_VALUE.toULong().inc()..ULong.MAX_VALUE
/**
* Keeps the five lower bits of the given [initialByte]
*/
fun fromInitialByte(initialByte: UByte): AdditionalInfo {
val lowOrder5Bits = initialByte and 0b00011111u
return AdditionalInfo(lowOrder5Bits)
}
/**
* Calculates the closest [AdditionalInfo] for the given [value]
*/
fun forUnsignedInt(value: ULong): AdditionalInfo =
when (value) {
in ZeroToTwentyThreeRange -> AdditionalInfo(value.toUByte())
in SingleByteRange -> AdditionalInfo(SINGLE_BYTE_UINT)
in DoubleByteRange -> AdditionalInfo(DOUBLE_BYTE_UINT)
in FourByteRange -> AdditionalInfo(FOUR_BYTE_UINT)
in EightByteRange -> AdditionalInfo(EIGHT_BYTE_UINT)
else -> error("Invalid value $value")
}
}
}
/**
* Creates the initial byte by combining the given [majorType] (three higher bits) with
* the [additionalInfo] (lower five bits)
*/
internal fun initialByte(
majorType: MajorType,
additionalInfo: AdditionalInfo,
): UByte {
val highOrder3Bits: UByte =
when (majorType) {
MajorType.Zero -> 0b000_00000u
MajorType.One -> 0b001_00000u
MajorType.Two -> 0b010_00000u
MajorType.Three -> 0b011_00000u
MajorType.Four -> 0b100_00000u
MajorType.Five -> 0b101_00000u
MajorType.Six -> 0b110_00000u
MajorType.Seven -> 0b111_00000u
}
val lowOrder5Bits = additionalInfo.value
return highOrder3Bits or lowOrder5Bits
}
|
cbor/lib/src/commonMain/kotlin/io/github/routis/cbor/internal/EncodeIO.kt | 2972510301 | package io.github.routis.cbor.internal
import io.github.routis.cbor.*
import kotlinx.io.*
/**
* @receiver The sink to write to
*/
@Throws(IOException::class)
internal fun Sink.writeDataItem(item: DataItem) {
when (item) {
is UnsignedIntegerDataItem -> writeInitialByteAndUnsignedInteger(MajorType.Zero, item.value)
is NegativeIntegerDataItem -> writeInitialByteAndUnsignedInteger(MajorType.One, item.value)
is ByteStringDataItem -> {
val bytes = item.bytes
val byteCount = item.bytes.size
writeInitialByteAndUnsignedInteger(MajorType.Two, byteCount.toULong())
write(bytes)
}
is TextStringDataItem -> {
val bytes = item.text.encodeToByteArray()
val byteCount = bytes.size
writeInitialByteAndUnsignedInteger(MajorType.Three, byteCount.toULong())
write(bytes)
}
is ArrayDataItem -> {
val elementsNo = item.size
writeInitialByteAndUnsignedInteger(MajorType.Four, elementsNo.toULong())
item.forEach { element -> writeDataItem(element) }
}
is MapDataItem -> {
val entriesNo = item.size
writeInitialByteAndUnsignedInteger(MajorType.Five, entriesNo.toULong())
item.forEach { (key, value) ->
writeDataItem(key.item)
writeDataItem(value)
}
}
is TaggedDataItem<*> -> {
val tagValue = item.tagValue()
writeInitialByteAndUnsignedInteger(MajorType.Six, tagValue)
writeDataItem(item.content)
}
is BooleanDataItem -> {
if (item.value) {
writeMajorSevenInitialByte(AdditionalInfo.BOOLEAN_TRUE)
} else {
writeMajorSevenInitialByte(AdditionalInfo.BOOLEAN_FALSE)
}
}
NullDataItem -> writeMajorSevenInitialByte(AdditionalInfo.NULL)
UndefinedDataItem -> writeMajorSevenInitialByte(AdditionalInfo.UNDEFINED)
is ReservedDataItem -> {
writeMajorSevenInitialByte(AdditionalInfo.RESERVED_OR_UNASSIGNED)
writeUByte(item.value)
}
is HalfPrecisionFloatDataItem -> {
writeMajorSevenInitialByte(AdditionalInfo.HALF_PRECISION_FLOAT)
writeShort(halfBitsFromFloat(item.value))
}
is SinglePrecisionFloatDataItem -> {
writeMajorSevenInitialByte(AdditionalInfo.SINGLE_PRECISION_FLOAT)
writeFloat(item.value)
}
is DoublePrecisionFloatDataItem -> {
writeMajorSevenInitialByte(AdditionalInfo.DOUBLE_PRECISION_FLOAT)
writeDouble(item.value)
}
is UnassignedDataItem -> {
val (additionalInfo, next) =
when (item.value) {
in 0u..19u -> item.value to null
in 28u..30u -> item.value to null
else -> AdditionalInfo.RESERVED_OR_UNASSIGNED to item.value.toByte()
}
writeMajorSevenInitialByte(additionalInfo)
next?.let { writeByte(it) }
}
}
}
/**
* Calculates the closest [AdditionalInfo] of the given [value], then writes to the [Sink] the
* initial byte followed, if needed, by an 1, 2, 4 or 8 byte long value
*
* @receiver The sink to write to
*/
private fun Sink.writeInitialByteAndUnsignedInteger(
majorType: MajorType,
value: ULong,
) {
require(majorType != MajorType.Seven) { "Not applicable for Major type 7" }
require(value >= 0u)
val additionalInfo = AdditionalInfo.forUnsignedInt(value)
val initialByte = initialByte(majorType, additionalInfo)
writeByte(initialByte.toByte())
when (additionalInfo.value) {
in AdditionalInfo.ZeroToTwentyThreeRange -> Unit // Do nothing. Value is included in initial byte
AdditionalInfo.SINGLE_BYTE_UINT -> writeUByte(value.toUByte())
AdditionalInfo.DOUBLE_BYTE_UINT -> writeUShort(value.toUShort())
AdditionalInfo.FOUR_BYTE_UINT -> writeUInt(value.toUInt())
AdditionalInfo.EIGHT_BYTE_UINT -> writeULong(value)
else -> error("Oops")
}
}
private fun Sink.writeMajorSevenInitialByte(additionalInfo: UByte) {
val initialByte = initialByte(MajorType.Seven, AdditionalInfo(additionalInfo))
writeByte(initialByte.toByte())
}
|
cbor/lib/src/commonMain/kotlin/io/github/routis/cbor/internal/HalfBits.kt | 2868912067 | package io.github.routis.cbor.internal
private const val HALF_PRECISION_EXPONENT_BIAS = 15
private const val HALF_PRECISION_MAX_EXPONENT = 0x1f
private const val HALF_PRECISION_MAX_MANTISSA = 0x3ff
private const val SINGLE_PRECISION_EXPONENT_BIAS = 127
private const val SINGLE_PRECISION_MAX_EXPONENT = 0xFF
private const val SINGLE_PRECISION_NORMALIZE_BASE = 0.5f
private val normalizeBaseBits = SINGLE_PRECISION_NORMALIZE_BASE.toBits()
/**
* Copied this from kotlinx serialization
*
* https://github.com/Kotlin/kotlinx.serialization/blob/master/formats/cbor/commonMain/src/kotlinx/serialization/cbor/internal/Encoding.kt#L665
* For details about half-precision floating-point numbers see https://tools.ietf.org/html/rfc7049#appendix-D
*/
internal fun floatFromHalfBits(bits: Short): Float {
val intBits = bits.toInt()
val negative = (intBits and 0x8000) != 0
val halfExp = intBits shr 10 and HALF_PRECISION_MAX_EXPONENT
val halfMant = intBits and HALF_PRECISION_MAX_MANTISSA
val exp: Int
val mant: Int
when (halfExp) {
HALF_PRECISION_MAX_EXPONENT -> {
// if exponent maximal - value is NaN or Infinity
exp = SINGLE_PRECISION_MAX_EXPONENT
mant = halfMant
}
0 -> {
if (halfMant == 0) {
// if exponent and mantissa are zero - value is zero
mant = 0
exp = 0
} else {
// if exponent is zero and mantissa non-zero - value denormalized. normalize it
var res = Float.fromBits(normalizeBaseBits + halfMant)
res -= SINGLE_PRECISION_NORMALIZE_BASE
return if (negative) -res else res
}
}
else -> {
// normalized value
exp = (halfExp + (SINGLE_PRECISION_EXPONENT_BIAS - HALF_PRECISION_EXPONENT_BIAS))
mant = halfMant
}
}
val res = Float.fromBits((exp shl 23) or (mant shl 13))
return if (negative) -res else res
}
// https://stackoverflow.com/questions/6162651/half-precision-floating-point-in-java
internal fun halfBitsFromFloat(number: Float): Short {
val bits = number.toRawBits()
val sign = bits ushr 16 and 0x8000
val value = (bits and 0x7fffffff) + 0x1000
val result =
when {
value >= 0x47800000 -> {
if (bits and 0x7fffffff >= 0x47800000) {
if (value < 0x7f800000) {
sign or 0x7c00
} else {
sign or 0x7c00 or (bits and 0x007fffff ushr 13)
}
} else {
sign or 0x7bff
}
}
value >= 0x38800000 -> sign or (value - 0x38000000 ushr 13)
value < 0x33000000 -> sign
else -> {
val otherValue = bits and 0x7fffffff ushr 23
sign or (
(
(bits and 0x7fffff or 0x800000) +
(0x800000 ushr otherValue - 102)
) ushr 126 - otherValue
)
}
}
return result.toShort()
}
|
cbor/lib/src/commonMain/kotlin/io/github/routis/cbor/internal/ToJson.kt | 3673564045 | package io.github.routis.cbor.internal
import com.ionspin.kotlin.bignum.integer.BigInteger
import io.github.routis.cbor.*
import kotlinx.serialization.json.*
internal fun JsonOptions.dataItemToJson(dataItem: DataItem): JsonElement {
fun convert(item: DataItem): JsonElement =
when (item) {
is UnsignedIntegerDataItem -> JsonPrimitive(item.value)
is NegativeIntegerDataItem -> item.asBigInteger().toJson()
is ByteStringDataItem -> byteStringOption(item)
is TextStringDataItem -> JsonPrimitive(item.text)
is ArrayDataItem -> item.map(::convert).let(::JsonArray)
is MapDataItem ->
buildMap {
item.forEach { (k, v) -> keyAsString(k)?.let { put(it, convert(v)) } }
}.let(::JsonObject)
is TaggedDataItem<*> ->
when (item) {
is StandardDateTimeDataItem -> convert(item.content)
is IntegerEpochDataItem -> convert(item.content)
is HalfFloatEpochDataItem -> convert(item.content)
is SingleFloatEpochDataItem -> convert(item.content)
is DoubleFloatEpochDataItem -> convert(item.content)
is BigNumUnsigned -> item.asBigInteger().toJson()
is BigNumNegative -> item.asBigInteger().toJson()
is DecimalFraction -> TODO("Implement toJson for DecimalFraction")
is BigFloat -> TODO("Implement toJson for BigFloat")
is EncodedText -> convert(item.content)
is CborDataItem -> convert(decode(item.content.bytes))
is SelfDescribedCbor -> convert(item.content)
is UnsupportedTagDataItem -> JsonNull
is CalendarDayDataItem -> convert(item.content)
is CalendarDateDataItem -> convert(item.content)
}
is BooleanDataItem -> JsonPrimitive(item.value)
is HalfPrecisionFloatDataItem -> JsonPrimitive(item.value)
is SinglePrecisionFloatDataItem -> JsonPrimitive(item.value)
is DoublePrecisionFloatDataItem -> JsonPrimitive(item.value)
is ReservedDataItem -> JsonNull
is UnassignedDataItem -> JsonNull
UndefinedDataItem -> JsonNull
NullDataItem -> JsonNull
}
return convert(dataItem)
}
private fun JsonOptions.keyAsString(k: Key<*>): String? =
when (k) {
is BoolKey -> keyOptions.boolKeyMapper?.invoke(k)
is ByteStringKey -> keyOptions.byteStringKeyMapper?.invoke(k)
is IntegerKey -> keyOptions.integerKeyMapper?.invoke(k)
is TextStringKey -> k.item.text
}
private fun BigInteger.toJson() = JsonUnquotedLiteral(toString(10))
|
cbor/lib/src/commonMain/kotlin/io/github/routis/cbor/internal/Tag.kt | 4115782995 | package io.github.routis.cbor.internal
import io.github.routis.cbor.*
internal sealed interface Tag {
data object StandardDateTimeString : Tag
data object EpochBasedDateTime : Tag
data object BigNumUnsigned : Tag
data object BigNumNegative : Tag
data object DecimalFraction : Tag
data object BigFloat : Tag
data object ToBase64Url : Tag
data object ToBase64 : Tag
data object ToBase16 : Tag
data object CborDataItem : Tag
data object Uri : Tag
data object Base64Url : Tag
data object Base64 : Tag
data object Regex : Tag
data object Mime : Tag
data object SelfDescribedCbor : Tag
data object CalendarDay : Tag
data object CalendarDate : Tag
companion object {
fun of(x: ULong): Tag? =
when (x) {
0uL -> StandardDateTimeString
1uL -> EpochBasedDateTime
2uL -> BigNumUnsigned
3uL -> BigNumNegative
4uL -> DecimalFraction
5uL -> BigFloat
21uL -> ToBase64Url
22uL -> ToBase64
23uL -> ToBase16
24uL -> CborDataItem
32uL -> Uri
33uL -> Base64Url
34uL -> Base64
35uL -> Regex
36uL -> Mime
55799uL -> SelfDescribedCbor
100uL -> CalendarDay
1004uL -> CalendarDate
else -> null
}
}
}
internal fun Tag.value(): ULong =
when (this) {
Tag.StandardDateTimeString -> 0uL
Tag.EpochBasedDateTime -> 1uL
Tag.BigNumUnsigned -> 2uL
Tag.BigNumNegative -> 3uL
Tag.DecimalFraction -> 4uL
Tag.BigFloat -> 5uL
Tag.ToBase64Url -> 21uL
Tag.ToBase64 -> 22uL
Tag.ToBase16 -> 23uL
Tag.CborDataItem -> 24uL
Tag.Uri -> 32uL
Tag.Base64Url -> 33uL
Tag.Base64 -> 34uL
Tag.Regex -> 35uL
Tag.Mime -> 36uL
Tag.SelfDescribedCbor -> 55799uL
Tag.CalendarDay -> 100uL
Tag.CalendarDate -> 1004uL
}
internal fun TaggedDataItem<*>.tagValue(): ULong =
when (this) {
is StandardDateTimeDataItem -> Tag.StandardDateTimeString.value()
is EpochBasedDateTime<*> -> Tag.EpochBasedDateTime.value()
is BigNumUnsigned -> Tag.BigNumUnsigned.value()
is BigNumNegative -> Tag.BigNumNegative.value()
is DecimalFraction -> Tag.DecimalFraction.value()
is BigFloat -> Tag.BigFloat.value()
is Base64DataItem -> Tag.Base64.value()
is Base64UrlDataItem -> Tag.Base64Url.value()
is MimeDataItem -> Tag.Mime.value()
is RegexDataItem -> Tag.Regex.value()
is UriDataItem -> Tag.Uri.value()
is CborDataItem -> Tag.CborDataItem.value()
is SelfDescribedCbor -> Tag.SelfDescribedCbor.value()
is UnsupportedTagDataItem -> tag
is CalendarDayDataItem -> Tag.CalendarDay.value()
is CalendarDateDataItem -> Tag.CalendarDate.value()
}
internal fun DataItem.tagged(tag: Tag): TaggedDataItem<DataItem> {
val dataItem = this
return with(tag) {
when (this) {
Tag.StandardDateTimeString -> StandardDateTimeDataItem(expected(dataItem))
Tag.EpochBasedDateTime ->
when (dataItem) {
is IntegerDataItem -> IntegerEpochDataItem(dataItem)
is HalfPrecisionFloatDataItem -> HalfFloatEpochDataItem(dataItem)
is SinglePrecisionFloatDataItem -> SingleFloatEpochDataItem(dataItem)
is DoublePrecisionFloatDataItem -> DoubleFloatEpochDataItem(dataItem)
else -> error("$dataItem is not valid for $this. Expecting integer or float")
}
Tag.BigNumUnsigned -> BigNumUnsigned(expected(dataItem))
Tag.BigNumNegative -> BigNumNegative(expected(dataItem))
Tag.DecimalFraction -> exponentAndMantissa(dataItem) { e, m -> DecimalFraction(e, m) }
Tag.BigFloat -> exponentAndMantissa(dataItem) { e, m -> BigFloat(e, m) }
Tag.ToBase16 -> UnsupportedTagDataItem(value(), dataItem) // TODO
Tag.ToBase64 -> UnsupportedTagDataItem(value(), dataItem) // TODO
Tag.ToBase64Url -> UnsupportedTagDataItem(value(), dataItem) // TODO
Tag.CborDataItem -> CborDataItem(expected(dataItem))
Tag.SelfDescribedCbor -> SelfDescribedCbor(dataItem)
Tag.Uri -> UriDataItem(expected(dataItem))
Tag.Base64Url -> Base64UrlDataItem(expected(dataItem))
Tag.Base64 -> Base64DataItem(expected(dataItem))
Tag.Regex -> RegexDataItem(expected(dataItem))
Tag.Mime -> MimeDataItem(expected(dataItem))
Tag.CalendarDay -> CalendarDayDataItem(expected(dataItem))
Tag.CalendarDate -> CalendarDateDataItem(expected(dataItem))
}
}
}
private inline fun <reified DI : DataItem> Tag.expected(dataItem: DataItem): DI {
require(dataItem is DI) { "$dataItem is not valid for $this. Expecting ${DI::class}" }
return dataItem
}
private fun <DI> Tag.exponentAndMantissa(
dataItem: DataItem,
cons: (IntegerDataItem, IntegerDataItem) -> DI,
): DI {
val array = expected<ArrayDataItem>(dataItem)
require(array.size == 2) { "Array must have 2 elements" }
return cons(expected(array[0]), expected(array[1]))
}
|
cbor/lib/src/commonMain/kotlin/io/github/routis/cbor/internal/DecodeIO.kt | 2904711799 | package io.github.routis.cbor.internal
import io.github.routis.cbor.*
import kotlinx.io.*
import kotlin.contracts.contract
/**
* When reading a byte array for [DataItem] you can
* get either a [DataItemOrBreak.Item] or a [DataItemOrBreak.Break]
*/
private sealed interface DataItemOrBreak {
data class Item(val item: DataItem) : DataItemOrBreak
data object Break : DataItemOrBreak
}
/**
* Lifts a [DataItem] to the [DataItemOrBreak] hierarchy
*/
private fun DataItem.orBreak() = DataItemOrBreak.Item(this)
/**
* Reads the next [DataItem] from the source.
*
* @throws IllegalStateException when instead of a [DataItem] we get break
*/
@Throws(IllegalStateException::class, IOException::class)
internal fun Source.readDataItem(): DataItem {
val dataItemOrBreak = readDataItemOrBreak()
check(dataItemOrBreak is DataItemOrBreak.Item) { "Unexpected break" }
return dataItemOrBreak.item
}
/**
* Reads the next [DataItem] or break from the source.
*/
private fun Source.readDataItemOrBreak(): DataItemOrBreak {
val initialByte = readUByte()
val majorType = MajorType.fromInitialByte(initialByte)
val additionalInfo = AdditionalInfo.fromInitialByte(initialByte)
fun readSizeThen(block: (Size) -> DataItem): DataItem = readSize(additionalInfo).let(block)
return when (majorType) {
MajorType.Zero -> readUnsignedInteger(additionalInfo).orBreak()
MajorType.One -> readNegativeInteger(additionalInfo).orBreak()
MajorType.Two -> readSizeThen(::readByteString).orBreak()
MajorType.Three -> readSizeThen(::readTextString).orBreak()
MajorType.Four -> readSizeThen(::readArray).orBreak()
MajorType.Five -> readSizeThen(::readMap).orBreak()
MajorType.Six -> readTagged(additionalInfo).orBreak()
MajorType.Seven -> readMajorSeven(additionalInfo)
}
}
private fun Source.readUnsignedInteger(additionalInfo: AdditionalInfo): UnsignedIntegerDataItem {
val value = readUnsignedInt(additionalInfo)
return UnsignedIntegerDataItem(value)
}
private fun Source.readNegativeInteger(additionalInfo: AdditionalInfo): NegativeIntegerDataItem {
val value = readUnsignedInt(additionalInfo)
return NegativeIntegerDataItem(value)
}
private const val BRAKE_BYTE: UByte = 0b111_11111u
private fun Source.readByteString(size: Size): ByteStringDataItem {
val byteCount =
when (size) {
Size.Indefinite -> indexOf(BRAKE_BYTE.toByte())
is Size.Definite -> size.value.toLong()
}
val bytes = readByteArray(byteCount.toInt())
return ByteStringDataItem(bytes)
}
private fun Source.readTextString(size: Size): TextStringDataItem {
val text =
when (size) {
Size.Indefinite -> {
var buffer = ""
untilBreak { item ->
require(item is TextStringDataItem)
buffer += item.text
}
buffer
}
is Size.Definite -> {
require(size.value <= Long.MAX_VALUE.toULong()) { "Too big byteCount to handle" }
val byteCount = size.value.toLong()
readString(byteCount)
}
}
return TextStringDataItem(text)
}
private fun Source.readArray(size: Size): ArrayDataItem {
val items =
buildList {
when (size) {
Size.Indefinite -> untilBreak(::add)
is Size.Definite -> repeat(size.value) { add(readDataItem()) }
}
}
return ArrayDataItem(items)
}
private fun Source.readMap(size: Size): MapDataItem {
val items =
buildMap {
fun put(item: DataItem) {
val key = keyOf(item) ?: error("$item cannot be used as key")
check(!contains(key)) { "Duplicate $key" }
val value = readDataItem()
put(key, value)
}
when (size) {
Size.Indefinite -> untilBreak(::put)
is Size.Definite -> repeat(size.value) { put(readDataItem()) }
}
}
return MapDataItem(items)
}
private fun Source.readTagged(additionalInfo: AdditionalInfo): TaggedDataItem<*> {
val tag = readUnsignedInt(additionalInfo)
val dataItem = readDataItem()
return when (val supportedTag = Tag.of(tag)) {
null -> UnsupportedTagDataItem(tag, dataItem)
else -> dataItem.tagged(supportedTag)
}
}
private fun Source.readMajorSeven(additionalInfo: AdditionalInfo): DataItemOrBreak {
return when (additionalInfo.value) {
in 0u..19u -> UnassignedDataItem(additionalInfo.value).orBreak()
AdditionalInfo.BOOLEAN_FALSE -> BooleanDataItem(false).orBreak()
AdditionalInfo.BOOLEAN_TRUE -> BooleanDataItem(true).orBreak()
AdditionalInfo.NULL -> NullDataItem.orBreak()
AdditionalInfo.UNDEFINED -> UndefinedDataItem.orBreak()
AdditionalInfo.RESERVED_OR_UNASSIGNED ->
when (val next = readUByte()) {
in 0.toUByte()..31.toUByte() -> ReservedDataItem(next)
else -> UnassignedDataItem(next)
}.orBreak()
AdditionalInfo.HALF_PRECISION_FLOAT -> HalfPrecisionFloatDataItem(floatFromHalfBits(readShort())).orBreak()
AdditionalInfo.SINGLE_PRECISION_FLOAT -> SinglePrecisionFloatDataItem(Float.fromBits(readInt())).orBreak()
AdditionalInfo.DOUBLE_PRECISION_FLOAT -> DoublePrecisionFloatDataItem(Double.fromBits(readLong())).orBreak()
in 28u..30u -> UnassignedDataItem(additionalInfo.value).orBreak()
AdditionalInfo.BREAK -> DataItemOrBreak.Break
else -> error("Not supported")
}
}
/**
* Reads the next [DataItem] until it finds a break.
* For each [DataItem] the callback [useDataItem] is being invoked
*/
private fun Source.untilBreak(useDataItem: (DataItem) -> Unit) {
do {
val dataItemOrBreak = readDataItemOrBreak()
if (dataItemOrBreak is DataItemOrBreak.Item) {
useDataItem(dataItemOrBreak.item)
}
} while (dataItemOrBreak !is DataItemOrBreak.Break)
}
private inline fun repeat(
times: ULong,
action: (ULong) -> Unit,
) {
contract { callsInPlace(action) }
for (index in 0uL until times) {
action(index)
}
}
private sealed interface Size {
data object Indefinite : Size
data class Definite(val value: ULong) : Size
}
private fun Source.readSize(additionalInfo: AdditionalInfo): Size =
when (additionalInfo.value) {
AdditionalInfo.INDEFINITE_LENGTH_INDICATOR -> Size.Indefinite
else -> Size.Definite(readUnsignedInt(additionalInfo))
}
/**
* Reads from the [Source] an unsigned integer, using the [additionalInfo] as follows:
* - if [additionalInfo] is less than 24, the result is the additional info itself
* - if [additionalInfo] is 24, 25, 26 or 27 The argument's value is held in the following 1, 2, 4, or 8 bytes,
* respectively, in network byte order
*
* @param additionalInfo the instruction on how to read the unsigned integer
* @receiver The [Source] to read from
* @return the unsigned integer. Regardless of the case this always a [ULong]
*/
private fun Source.readUnsignedInt(additionalInfo: AdditionalInfo): ULong {
return when (additionalInfo.value) {
in AdditionalInfo.ZeroToTwentyThreeRange -> additionalInfo.value.toULong()
AdditionalInfo.SINGLE_BYTE_UINT -> readUByte().toULong()
AdditionalInfo.DOUBLE_BYTE_UINT -> readUShort().toULong()
AdditionalInfo.FOUR_BYTE_UINT -> readUInt().toULong()
AdditionalInfo.EIGHT_BYTE_UINT -> readULong()
else -> error("Cannot use ${additionalInfo.value} for reading unsigned. Valid values are in 0..27 inclusive")
}
}
|
cbor/lib/src/commonMain/kotlin/io/github/routis/cbor/Decode.kt | 4113610258 | @file:JvmName("Decoder")
package io.github.routis.cbor
import io.github.routis.cbor.internal.readDataItem
import kotlinx.io.Buffer
import kotlinx.io.IOException
import kotlin.io.encoding.Base64
import kotlin.jvm.JvmName
/**
* Decodes the given [source] into [DataItem]
*
* @param source the CBOR bytes Base64, URL safe, encoded.
*
* @throws IOException if something goes wrong with IO
* @throws IllegalStateException if the given input is invalid
*/
@Throws(IllegalStateException::class, IOException::class)
fun decodeBase64UrlSafe(source: String): DataItem {
val bytes = Base64.UrlSafe.decode(source)
return decode(bytes)
}
/**
* Decodes the given [bytes] into [DataItem]
*
* @param bytes input to decode.
*
* @throws IOException if something goes wrong with IO
* @throws IllegalStateException if the given input is invalid
*/
@Throws(IllegalStateException::class, IOException::class)
fun decode(bytes: ByteArray): DataItem {
return Buffer().use { buffer ->
buffer.write(bytes)
buffer.readDataItem()
}
}
|
cbor/lib/src/commonMain/kotlin/io/github/routis/cbor/Encode.kt | 2282245665 | @file:JvmName("Encoder")
package io.github.routis.cbor
import io.github.routis.cbor.internal.writeDataItem
import kotlinx.io.Buffer
import kotlinx.io.IOException
import kotlinx.io.readByteArray
import kotlin.jvm.JvmName
/**
* Encodes the given [dataItem] into a [ByteArray] according to CBOR
*
* The implementation doesn't support indefinite size (aka streaming)
* for lists, maps or other types.
*
* @param dataItem the item to encode
* @return the byte representation of the item in CBOR
*
* @throws IOException if something goes wrong with IO
*/
@Throws(IOException::class)
fun encode(dataItem: DataItem): ByteArray {
return Buffer().use { buffer ->
buffer.writeDataItem(dataItem)
buffer.readByteArray()
}
}
|
cbor/lib/src/commonMain/kotlin/io/github/routis/cbor/DataItem.kt | 177934608 | package io.github.routis.cbor
sealed interface DataItem
/**
* Integer numbers in the range -2^64..2^64-1 inclusive
*/
sealed interface IntegerDataItem : DataItem
/**
* Unsigned integer in the range 0 to 2^64-1 inclusive
*
* @param value The numeric value
*/
data class UnsignedIntegerDataItem(val value: ULong) : IntegerDataItem {
init {
require(value >= 0uL) { "Value should be in range 0..2^64-1" }
}
}
/**
* Negative integer in the range -2^64 to -1 inclusive
*
* Please note that the [value] is the unsigned (zero or positive) representation
* of the number.
*
* To get the actual numeric value, please use [NegativeIntegerDataItem.asBigInteger]
*
* @param value the unsigned representation of the Negative Integer.
*/
data class NegativeIntegerDataItem(val value: ULong) : IntegerDataItem {
init {
require(value >= 0uL) { "Value should be in range 0..2^64-1" }
}
}
/**
* A "string" of [bytes]
*/
data class ByteStringDataItem(val bytes: ByteArray) : DataItem {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as ByteStringDataItem
return bytes.contentEquals(other.bytes)
}
override fun hashCode(): Int = bytes.contentHashCode()
}
/**
* A [text] string encoded as UTF-8.
*/
data class TextStringDataItem(val text: String) : DataItem
/**
* An array of data [items].
* Items in an array do not need to all be of the same type
*/
data class ArrayDataItem(private val items: List<DataItem>) : DataItem, List<DataItem> by items
/**
* A map (set of key value pairs)
* Not all [DataItem] can be used as keys.
* Check [Key]
*/
data class MapDataItem(private val items: Map<Key<*>, DataItem>) : DataItem, Map<Key<*>, DataItem> by items
/**
* A tagged [DataItem]
* @param DI the type of the content
*/
sealed interface TaggedDataItem<out DI : DataItem> : DataItem {
val content: DI
}
/**
* Tag number 0 contains a text string in the standard format described by the
* date-time production in RFC3339, as refined by Section 3.3 of RFC4287,
* representing the point in time described there.
*/
data class StandardDateTimeDataItem(override val content: TextStringDataItem) : TaggedDataItem<TextStringDataItem>
sealed interface EpochBasedDateTime<DI : DataItem> : TaggedDataItem<DI>
data class IntegerEpochDataItem(override val content: IntegerDataItem) : EpochBasedDateTime<IntegerDataItem>
data class HalfFloatEpochDataItem(override val content: HalfPrecisionFloatDataItem) :
EpochBasedDateTime<HalfPrecisionFloatDataItem>
data class SingleFloatEpochDataItem(override val content: SinglePrecisionFloatDataItem) :
EpochBasedDateTime<SinglePrecisionFloatDataItem>
data class DoubleFloatEpochDataItem(override val content: DoublePrecisionFloatDataItem) :
EpochBasedDateTime<DoublePrecisionFloatDataItem>
/**
* To get the actual numeric value, please use [BigNumUnsigned.asBigInteger]
*/
data class BigNumUnsigned(override val content: ByteStringDataItem) : TaggedDataItem<ByteStringDataItem>
/**
* To get the actual numeric value, please use [BigNumNegative.asBigInteger]
*/
data class BigNumNegative(override val content: ByteStringDataItem) : TaggedDataItem<ByteStringDataItem>
data class DecimalFraction(
val exponent: IntegerDataItem,
val mantissa: IntegerDataItem,
) : TaggedDataItem<ArrayDataItem> {
override val content: ArrayDataItem
get() = ArrayDataItem(listOf(exponent, mantissa))
}
data class BigFloat(
val exponent: IntegerDataItem,
val mantissa: IntegerDataItem,
) : TaggedDataItem<ArrayDataItem> {
override val content: ArrayDataItem
get() = ArrayDataItem(listOf(exponent, mantissa))
}
data class CborDataItem(override val content: ByteStringDataItem) : TaggedDataItem<ByteStringDataItem> {
constructor(content: ByteArray) : this(ByteStringDataItem(content))
}
data class SelfDescribedCbor(override val content: DataItem) : TaggedDataItem<DataItem>
sealed interface EncodedText : TaggedDataItem<TextStringDataItem>
data class Base64DataItem(override val content: TextStringDataItem) : EncodedText {
constructor(content: String) : this(TextStringDataItem(content))
}
data class Base64UrlDataItem(override val content: TextStringDataItem) : EncodedText {
constructor(content: String) : this(TextStringDataItem(content))
}
data class RegexDataItem(override val content: TextStringDataItem) : EncodedText {
constructor(content: String) : this(TextStringDataItem(content))
}
data class MimeDataItem(override val content: TextStringDataItem) : EncodedText {
constructor(content: String) : this(TextStringDataItem(content))
}
data class UriDataItem(override val content: TextStringDataItem) : EncodedText {
constructor(content: String) : this(TextStringDataItem(content))
}
data class CalendarDayDataItem(override val content: IntegerDataItem) : TaggedDataItem<IntegerDataItem>
data class CalendarDateDataItem(override val content: TextStringDataItem) : TaggedDataItem<TextStringDataItem> {
constructor(content: String) : this(TextStringDataItem(content))
}
data class UnsupportedTagDataItem(val tag: ULong, override val content: DataItem) : TaggedDataItem<DataItem>
data class BooleanDataItem(val value: Boolean) : DataItem
data class HalfPrecisionFloatDataItem(val value: Float) : DataItem
data class SinglePrecisionFloatDataItem(val value: Float) : DataItem
data class DoublePrecisionFloatDataItem(val value: Double) : DataItem
data object NullDataItem : DataItem
data object UndefinedDataItem : DataItem
data class UnassignedDataItem(val value: UByte) : DataItem
data class ReservedDataItem(val value: UByte) : DataItem
|
cbor/lib/src/commonMain/kotlin/io/github/routis/cbor/Key.kt | 639629331 | package io.github.routis.cbor
/**
* [Data items][DataItem] that can be used as keys in a [CBOR map][MapDataItem]
* @param DI The type of the data item
*/
sealed interface Key<out DI : DataItem> {
/**
* The data item of the key
*/
val item: DI
}
data class BoolKey(override val item: BooleanDataItem) : Key<BooleanDataItem>
data class ByteStringKey(override val item: ByteStringDataItem) : Key<ByteStringDataItem>
data class IntegerKey(override val item: IntegerDataItem) : Key<IntegerDataItem>
data class TextStringKey(override val item: TextStringDataItem) : Key<TextStringDataItem>
/**
* Creates a [Key] for the given [dataItem]
* In case the [dataItem] cannot be used as a kay a `null` is being returned.
*/
fun keyOf(dataItem: DataItem): Key<DataItem>? =
when (dataItem) {
is BooleanDataItem -> BoolKey(dataItem)
is ByteStringDataItem -> ByteStringKey(dataItem)
is UnsignedIntegerDataItem -> IntegerKey(dataItem)
is NegativeIntegerDataItem -> IntegerKey(dataItem)
is TextStringDataItem -> TextStringKey(dataItem)
else -> null
}
|
cbor/lib/src/commonMain/kotlin/io/github/routis/cbor/JsonConverter.kt | 2847818842 | @file:JvmName("JsonConverter")
package io.github.routis.cbor
import io.github.routis.cbor.internal.dataItemToJson
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonPrimitive
import kotlin.io.encoding.Base64
typealias KeyMapper<K> = (K) -> String?
/**
* Options on if and how to serialize a [Key] other than [TextStringKey],
* into a Json attribute name.
* One may choose to not map into Json other keys (besides [TextStringKey])
* to make sure that there is no key collision in JSON.
*
* @param boolKeyMapper how to include [BoolKey]
* @param byteStringKeyMapper how to include [ByteStringKey]
* @param integerKeyMapper how to include [IntegerKey]
*/
data class KeyOptions
@JvmOverloads
constructor(
val boolKeyMapper: KeyMapper<BoolKey>? = null,
val byteStringKeyMapper: KeyMapper<ByteStringKey>? = null,
val integerKeyMapper: KeyMapper<IntegerKey>? = null,
)
/**
* A function that serializes a [ByteStringDataItem] into a [JsonElement]
*/
typealias ByteStringOption = (ByteStringDataItem) -> JsonElement
/**
* Options for converting a [DataItem] into Json
*
* @param keyOptions options about [keys][Key] of [maps][MapDataItem]
* @param byteStringOption how to serialize into JSON a [ByteStringDataItem]
*/
data class JsonOptions(
val keyOptions: KeyOptions,
val byteStringOption: ByteStringOption,
) {
companion object {
/**
* Serializes a [ByteStringDataItem] into a base64 url encoded string
*/
@JvmStatic
val Base64UrlEncodedBytes: ByteStringOption =
{ byteString -> JsonPrimitive(Base64.UrlSafe.encode(byteString.bytes)) }
/**
* Choice to use only [text keys][TextStringKey]
*/
@JvmStatic
val UseOnlyTextKey: KeyOptions =
KeyOptions(boolKeyMapper = null, byteStringKeyMapper = null, integerKeyMapper = null)
/**
* Default convention options.
* Uses [UseOnlyTextKey] and [Base64UrlEncodedBytes]
*/
@JvmStatic
val Default = JsonOptions(keyOptions = UseOnlyTextKey, byteStringOption = Base64UrlEncodedBytes)
}
}
/**
* Converts the a [DataItem] into JSON using the provided [options]
* @receiver the item to convert
*/
@JvmOverloads
fun DataItem.toJson(options: JsonOptions = JsonOptions.Default): JsonElement = with(options) { dataItemToJson(this@toJson) }
|
cbor/lib/src/commonTest/kotlin/io/github/routis/cbor/AdditionalInfoTests.kt | 3529047832 | package io.github.routis.cbor
import io.github.routis.cbor.internal.AdditionalInfo
import kotlin.test.Test
import kotlin.test.assertEquals
class AdditionalInfoTests {
@Test
fun additionalInfoForUnsignedInt_for_number_0_to_23_UByte() {
val start: UByte = 0u
val end: UByte = 23u
(start..end).forEach {
assertEquals(AdditionalInfo(it.toUByte()), AdditionalInfo.forUnsignedInt(it.toULong()))
}
}
@Test
fun additionalInfoForUnsignedInt_for_number_24_to_2255_UByte() {
val start: UByte = 24u
val end: UByte = 255u
(start..end).forEach {
assertEquals(AdditionalInfo(AdditionalInfo.SINGLE_BYTE_UINT), AdditionalInfo.forUnsignedInt(it.toULong()))
}
}
@Test
fun additionalInfoForUnsignedInt_for_number_0_to_23_UShort() {
val start: UShort = 0u
val end: UShort = 23u
(start..end).forEach {
assertEquals(AdditionalInfo(it.toUByte()), AdditionalInfo.forUnsignedInt(it.toULong()))
}
}
@Test
fun additionalInfoForUnsignedInt_for_number_24_to_2255_UShort() {
val start: UShort = 24u
val end: UShort = 255u
(start..end).forEach {
assertEquals(AdditionalInfo(AdditionalInfo.SINGLE_BYTE_UINT), AdditionalInfo.forUnsignedInt(it.toULong()))
}
}
@Test
fun additionalInfoForUnsignedInt_for_number_2256_to_65535_UByte() {
val start: UShort = 256u
val end: UShort = 65535u
(start..end).forEach {
assertEquals(AdditionalInfo(AdditionalInfo.DOUBLE_BYTE_UINT), AdditionalInfo.forUnsignedInt(it.toULong()))
}
}
@Test
fun additionalInfoForUnsignedInt_for_number_0_to_23_UInt() {
val start = 0u
val end = 23u
(start..end).forEach {
assertEquals(AdditionalInfo(it.toUByte()), AdditionalInfo.forUnsignedInt(it.toULong()))
}
}
@Test
fun additionalInfoForUnsignedInt_for_number_24_to_2255_UInt() {
val start = 24u
val end = 255u
(start..end).forEach {
assertEquals(AdditionalInfo(AdditionalInfo.SINGLE_BYTE_UINT), AdditionalInfo.forUnsignedInt(it.toULong()))
}
}
@Test
fun additionalInfoForUnsignedInt_for_number_2256_to_65535_UInt() {
val start = 256u
val end = 65535u
(start..end).forEach {
assertEquals(AdditionalInfo(AdditionalInfo.DOUBLE_BYTE_UINT), AdditionalInfo.forUnsignedInt(it.toULong()))
}
}
@Test
fun additionalInfoForUnsignedInt_for_number_0_to_23_ULong() {
val start: ULong = 0u
val end: ULong = 23u
(start..end).forEach {
assertEquals(AdditionalInfo(it.toUByte()), AdditionalInfo.forUnsignedInt(it))
}
}
@Test
fun additionalInfoForUnsignedInt_for_number_24_to_2255_ULong() {
val start: ULong = 24u
val end: ULong = 255u
(start..end).forEach {
assertEquals(AdditionalInfo(AdditionalInfo.SINGLE_BYTE_UINT), AdditionalInfo.forUnsignedInt(it))
}
}
@Test
fun additionalInfoForUnsignedInt_for_number_2256_to_65535_ULong() {
val start: ULong = 256u
val end: ULong = 65535u
(start..end).forEach {
assertEquals(AdditionalInfo(AdditionalInfo.DOUBLE_BYTE_UINT), AdditionalInfo.forUnsignedInt(it))
}
}
}
|
cbor/lib/src/commonTest/kotlin/io/github/routis/cbor/DecodeTests.kt | 3260717541 | package io.github.routis.cbor
import com.ionspin.kotlin.bignum.integer.BigInteger
import kotlinx.serialization.encodeToString
import kotlin.test.Test
import kotlin.test.assertEquals
class DecodeTests {
@Test
fun major_0_single_byte() {
for (i in 0..23) {
val expected = UnsignedIntegerDataItem(i.toULong())
val decoded = decode(byteArrayOf(i.toByte()))
assertEquals(expected, decoded)
}
}
@Test
fun major_0_0b000_01010_is_uint_10() {
val bytes = byteArrayOf(0b000_01010.toByte())
val decoded = decode(bytes)
assertEquals(UnsignedIntegerDataItem(10uL), decoded)
}
@Test
fun value_0b000_11001_followed_by_0x01F4_is_uint_500() {
val bytes =
byteArrayOf(
0b000_11001.toByte(),
0x01.toByte(),
0xF4.toByte(),
)
val decoded = decode(bytes)
assertEquals(UnsignedIntegerDataItem(500uL), decoded)
}
@Test
fun value_minus_500_should_be_represented_as_Major_1_499() {
val value499 = 499uL
0b001_11001.toHexString().also { println(it) }
val bytes =
byteArrayOf(
0b001_11001.toByte(),
0x01.toByte(),
0xF3.toByte(),
)
val decoded = decode(bytes)
assertEquals(NegativeIntegerDataItem(value499), decoded)
}
@Test
fun value_1000000000000() {
val bytes: ByteArray =
byteArrayOf(
0x1B, 0x00, 0x00, 0x00,
0xE8.toByte(), 0xD4.toByte(), 0xA5.toByte(), 0x10,
0x00,
)
val decoded = decode(bytes)
val expected = UnsignedIntegerDataItem(1000000000000uL)
assertEquals(expected, decoded)
}
@Test
fun value_18446744073709551616() {
val bytes =
byteArrayOf(
0xC2.toByte(), 0x49.toByte(), 0x01.toByte(), 0x00.toByte(),
0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(),
0x00.toByte(), 0x00.toByte(), 0x00.toByte(),
)
val decoded = decode(bytes)
val expected = BigNumUnsigned(ByteStringDataItem(BigInteger.parseString("18446744073709551616").toByteArray()))
assertEquals(expected, decoded)
}
@Test
fun value_uri() {
val bytes =
byteArrayOf(
0xd8.toByte(), 0x20.toByte(), 0x76.toByte(), 0x68.toByte(),
0x74.toByte(), 0x74.toByte(), 0x70.toByte(), 0x3a.toByte(),
0x2f.toByte(), 0x2f.toByte(), 0x77.toByte(), 0x77.toByte(),
0x77.toByte(), 0x2e.toByte(), 0x65.toByte(), 0x78.toByte(),
0x61.toByte(), 0x6d.toByte(), 0x70.toByte(), 0x6c.toByte(),
0x65.toByte(), 0x2e.toByte(), 0x63.toByte(), 0x6f.toByte(),
0x6d.toByte(),
)
val decoded = decode(bytes)
val expected = UriDataItem("http://www.example.com")
assertEquals(expected, decoded)
}
@Test
fun vp_token_should_be_decoded() {
decodeBase64UrlSafe(vpToken).also { cbor ->
cbor.toJson().also { println(jsonSupport.encodeToString(it)) }
}
}
@Test
fun sample_msoMdoc_should_be_decoded() {
decodeBase64UrlSafe(sampleMsoMdoc).also { cbor ->
cbor.toJson().also { println(jsonSupport.encodeToString(it)) }
}
}
@Test
fun other_should_be_decoded() {
decode(otherHex.hexToByteArray(format = HexFormat { upperCase = true })).also { cbor ->
cbor.toJson().also { println(jsonSupport.encodeToString(it)) }
}
}
private val vpToken =
"""
o2d2ZXJzaW9uYzEuMGlkb2N1bWVudHOBo2dkb2NUeXBleBhldS5ldXJvcGEuZWMuZXVkaXcucGlkLjFsaXNzdWVyU2lnbmVkompuYW1lU3BhY2VzoXgYZXUuZXVyb3BhLmVjLmV1ZGl3LnBpZC4xkNgYWFikaGRpZ2VzdElEE2ZyYW5kb21QSmzzPZyCDv1T17NLxFK-onFlbGVtZW50SWRlbnRpZmllcmtmYW1pbHlfbmFtZWxlbGVtZW50VmFsdWVpQU5ERVJTU09O2BhYUaRoZGlnZXN0SUQEZnJhbmRvbVDqmfP2aA8nfl5TSHowY8m9cWVsZW1lbnRJZGVudGlmaWVyamdpdmVuX25hbWVsZWxlbWVudFZhbHVlY0pBTtgYWFykaGRpZ2VzdElEGBhmcmFuZG9tUJ1dU9F63fDU9XpbZ5IjMq5xZWxlbWVudElkZW50aWZpZXJqYmlydGhfZGF0ZWxlbGVtZW50VmFsdWXZA-xqMTk4NS0wMy0zMNgYWF6kaGRpZ2VzdElEDmZyYW5kb21QCU2SXHh-buWPbU6RMHcY73FlbGVtZW50SWRlbnRpZmllcnFmYW1pbHlfbmFtZV9iaXJ0aGxlbGVtZW50VmFsdWVpQU5ERVJTU09O2BhYV6RoZGlnZXN0SUQLZnJhbmRvbVDE-UnG_R9fklw8tMfXIQXOcWVsZW1lbnRJZGVudGlmaWVycGdpdmVuX25hbWVfYmlydGhsZWxlbWVudFZhbHVlY0pBTtgYWFWkaGRpZ2VzdElECmZyYW5kb21Q7aHFdl7agjf38513RbhjzHFlbGVtZW50SWRlbnRpZmllcmtiaXJ0aF9wbGFjZWxlbGVtZW50VmFsdWVmU1dFREVO2BhYZKRoZGlnZXN0SUQYGWZyYW5kb21QGVDZsN0X6o47yYU938bdR3FlbGVtZW50SWRlbnRpZmllcnByZXNpZGVudF9hZGRyZXNzbGVsZW1lbnRWYWx1ZW9GT1JUVU5BR0FUQU4gMTXYGFhcpGhkaWdlc3RJRAVmcmFuZG9tUDkVyImEeK9h7opQdhbeSDxxZWxlbWVudElkZW50aWZpZXJtcmVzaWRlbnRfY2l0eWxlbGVtZW50VmFsdWVrS0FUUklORUhPTE3YGFhdpGhkaWdlc3RJRBJmcmFuZG9tUF8F2eAL4JrvyQ0A5tBdfXpxZWxlbWVudElkZW50aWZpZXJ0cmVzaWRlbnRfcG9zdGFsX2NvZGVsZWxlbWVudFZhbHVlZTY0MTMz2BhYVKRoZGlnZXN0SUQMZnJhbmRvbVDm5aPBwr7FsyZX5k1nj2gRcWVsZW1lbnRJZGVudGlmaWVybnJlc2lkZW50X3N0YXRlbGVsZW1lbnRWYWx1ZWJTRdgYWFakaGRpZ2VzdElEAGZyYW5kb21Qi0eHxS49YJdz_yxPWTx3lnFlbGVtZW50SWRlbnRpZmllcnByZXNpZGVudF9jb3VudHJ5bGVsZW1lbnRWYWx1ZWJTRdgYWEqkaGRpZ2VzdElEA2ZyYW5kb21QDwYENdGWt-XUq7gi1iPEbHFlbGVtZW50SWRlbnRpZmllcmZnZW5kZXJsZWxlbWVudFZhbHVlAdgYWFGkaGRpZ2VzdElED2ZyYW5kb21Q4NMx_u8EloVTQkzjZ7GShXFlbGVtZW50SWRlbnRpZmllcmtuYXRpb25hbGl0eWxlbGVtZW50VmFsdWViU0XYGFhPpGhkaWdlc3RJRAJmcmFuZG9tUFE9zNuMOez7t6LQ5jnQVRBxZWxlbWVudElkZW50aWZpZXJrYWdlX292ZXJfMThsZWxlbWVudFZhbHVl9dgYWFGkaGRpZ2VzdElEFmZyYW5kb21Qa0Mdsk6zlTuKvl_ifh-rGXFlbGVtZW50SWRlbnRpZmllcmxhZ2VfaW5feWVhcnNsZWxlbWVudFZhbHVlGCbYGFhUpGhkaWdlc3RJRA1mcmFuZG9tUHVeV2RpUa1pvkam8EBOMHdxZWxlbWVudElkZW50aWZpZXJuYWdlX2JpcnRoX3llYXJsZWxlbWVudFZhbHVlGQfBamlzc3VlckF1dGiEQ6EBJqEYIVkChTCCAoEwggImoAMCAQICCRZK5ZkC3AUQZDAKBggqhkjOPQQDAjBYMQswCQYDVQQGEwJCRTEcMBoGA1UEChMTRXVyb3BlYW4gQ29tbWlzc2lvbjErMCkGA1UEAxMiRVUgRGlnaXRhbCBJZGVudGl0eSBXYWxsZXQgVGVzdCBDQTAeFw0yMzA1MzAxMjMwMDBaFw0yNDA1MjkxMjMwMDBaMGUxCzAJBgNVBAYTAkJFMRwwGgYDVQQKExNFdXJvcGVhbiBDb21taXNzaW9uMTgwNgYDVQQDEy9FVSBEaWdpdGFsIElkZW50aXR5IFdhbGxldCBUZXN0IERvY3VtZW50IFNpZ25lcjBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHyTE_TBpKpOsLPraBGkmU5Z3meZZDHC864IjrehBhy2WL2MORJsGVl6yQ35nQeNPvORO6NL2yy8aYfQJ-mvnfyjgcswgcgwHQYDVR0OBBYEFNGksSQ5MvtFcnKZSPJSfZVYp00tMB8GA1UdIwQYMBaAFDKR6w4cAR0UDnZPbE_qTJY42vsEMA4GA1UdDwEB_wQEAwIHgDASBgNVHSUECzAJBgcogYxdBQECMB8GA1UdEgQYMBaGFGh0dHA6Ly93d3cuZXVkaXcuZGV2MEEGA1UdHwQ6MDgwNqA0oDKGMGh0dHBzOi8vc3RhdGljLmV1ZGl3LmRldi9wa2kvY3JsL2lzbzE4MDEzLWRzLmNybDAKBggqhkjOPQQDAgNJADBGAiEA3l-Y5x72V1ISa_LEuE_e34HSQ8pXsVvTGKq58evrP30CIQD-Ivcya0tXWP8W_obTOo2NKYghadoEm1peLIBqsUcISFkE1tgYWQTRpmd2ZXJzaW9uYzEuMG9kaWdlc3RBbGdvcml0aG1nU0hBLTI1Nmdkb2NUeXBleBhldS5ldXJvcGEuZWMuZXVkaXcucGlkLjFsdmFsdWVEaWdlc3RzoXgYZXUuZXVyb3BhLmVjLmV1ZGl3LnBpZC4xuBoAWCAxMjgJkpvspLKPMN-Pnty4oh4maG2wtTFoemKpj_m5lgFYIH1Zh6Dbdoa5uXkKnqkxeq9h6djxynaGjSNEiqjsfbqnAlggTPupXMvLYNCuUxRiJH6g5qXfcWJIZ3ksZdcBA3pRwVUDWCB09uPPCqgMuIAJjQn2YRgmBl_tT9_3E9e0Jt3wburrMQRYIKyhscjEnmppDBFnWXIexzJ6VA3qO_0O_28WUVZ7Do73BVggTnDM3Imck9Hyok1Bmq4AZppNorJD00rpxc5BcXL5DJIGWCAo2rB9bGnbf9Xk5SYW22eaR2gxf1fj8a5rvDrpg66_jgdYIGo9ozvjL4bMgj7DuocMDAW5625WzDTj_BYNkHWFtgWOCFgg33OYzqyvNX-DNFMfs2ylTqBLJLnd8Yrm-ifEwMKPOhcJWCC31ffovu9YfCMFuUG7bdA3aqLaAEslQSq3whIl2pftugpYIC871wTY0U5kzcdUgKT0-HU2vOQGK_R7xTYzMeHdNW-nC1ggOWtn_Y2bEeQPO-5c0ULn9SbuLqx3et9VPV_97W_4ak0MWCCfycCaJs0xNbn_hWILpaZFvND6lWlm0oWRXTr_fA3BeA1YIKh7sCAEOwZJgTTy8o1xKD3B3x377CyYJX60oNthxPOtDlggwlmw_3oWKQZuk5zZ6J3WqWs8CPUKBgqQ_-4iiQNi-Z8PWCDrLdImBO7FEZy6AOWUKiDZqCgLy3OIAbhL3r2saF_VQhBYIKfGo-N144iz-NMxZKBHRITm8nE0ehQLPYDjvyRZ9l4eEVggU--gmFBCsGFt4k9ok9OYq1x5yRudR2EI5aoypDqdo5gSWCDWNI6q2jc9agynYGJAcI2iNFmoBYtErVC0_M-gKmrGSBNYIJ7xfKUNEwKhWfOX7XepB-wbgTRbZvBaGWXLYNb3Gf9AFFgg5C3mvEIKHsvvRRew19IErl0H7LcjBuozBqiUAqgpkWUVWCDCgU5RvDr9vu213R4u8rPTZ7h8CiVBDGTnvwH4GOe7RhZYIPOVFTWGsQyS2tAEWHFmpBX0qA33YuedXUdCM_w4El-XF1ggpWkSSNUczHH0KlnfVMYGF91Nh1k4QWNpGBAJKWISthUYGFgg6QCJ07heChHShYpVlRM2H-FmFVTEH_TQPQn4ie44ZGMYGVggDxlSeoNAWC2gPtQRoGXudIsumxrSkV6vi9ePrJYLN_NtZGV2aWNlS2V5SW5mb6FpZGV2aWNlS2V5pAECIAEhWCBUnC7AtGRRpb0PMV3aoCWymw28qjrFbRp6khJkvPK5TSJYIIzHjsTwaoV-LlDUVbScnLjsn1Nqfs6iSqo5-J2FKtPxbHZhbGlkaXR5SW5mb6Nmc2lnbmVkwHQyMDIzLTA3LTEzVDE2OjA4OjQ1Wml2YWxpZEZyb23AdDIwMjMtMDctMTNUMTY6MDg6NDVaanZhbGlkVW50aWzAdDIwMjQtMDctMTNUMTY6MDg6NDVaWEAtug-r916DygJtBmo-uBWynnJDQXy0N7zre1jnDf4qnaRq8OZENCiEfG4Jiw9saECd84Y7BKXZpTK4j1J14dvObGRldmljZVNpZ25lZKJqbmFtZVNwYWNlc9gYQaBqZGV2aWNlQXV0aKFvZGV2aWNlU2lnbmF0dXJlhEOhASag9lhA_5-pTyCo_U85BsOkGlYkKtYJjWfWz0myI6Q6lRWI-qunvUb1Bd3aWYxod5Fx6_NLDJjqs4k0SCKHwLZDhBkIHmZzdGF0dXMA
""".trimIndent().replace("\n", "")
private val sampleMsoMdoc =
"""
o2ZzdGF0dXMAZ3ZlcnNpb25jMS4waWRvY3VtZW50c4GiZ2RvY1R5cGV4GGV1LmV1cm9wYS5lYy
5ldWRpdy5waWQuMWxpc3N1ZXJTaWduZWSiamlzc3VlckF1dGiEQ6EBJqEYIVkC6DCCAuQwggJq
oAMCAQICFHIybfZjCJp7UA-MPyamhcvCwtLKMAoGCCqGSM49BAMCMFwxHjAcBgNVBAMMFVBJRC
BJc3N1ZXIgQ0EgLSBVVCAwMTEtMCsGA1UECgwkRVVESSBXYWxsZXQgUmVmZXJlbmNlIEltcGxl
bWVudGF0aW9uMQswCQYDVQQGEwJVVDAeFw0yMzA5MDIxNzQyNTFaFw0yNDExMjUxNzQyNTBaMF
QxFjAUBgNVBAMMDVBJRCBEUyAtIDAwMDExLTArBgNVBAoMJEVVREkgV2FsbGV0IFJlZmVyZW5j
ZSBJbXBsZW1lbnRhdGlvbjELMAkGA1UEBhMCVVQwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAA
RJBHzUHC0bpmqOtZBhZbDmk94bHOWvem1civd-0j3esn8q8L1MCColNqQkCPadXjJAYsmXS3D4
-HB9scOshixYo4IBEDCCAQwwHwYDVR0jBBgwFoAUs2y4kRcc16QaZjGHQuGLwEDMlRswFgYDVR
0lAQH_BAwwCgYIK4ECAgAAAQIwQwYDVR0fBDwwOjA4oDagNIYyaHR0cHM6Ly9wcmVwcm9kLnBr
aS5ldWRpdy5kZXYvY3JsL3BpZF9DQV9VVF8wMS5jcmwwHQYDVR0OBBYEFIHv9JxcgwpQpka-91
B4WlM-P9ibMA4GA1UdDwEB_wQEAwIHgDBdBgNVHRIEVjBUhlJodHRwczovL2dpdGh1Yi5jb20v
ZXUtZGlnaXRhbC1pZGVudGl0eS13YWxsZXQvYXJjaGl0ZWN0dXJlLWFuZC1yZWZlcmVuY2UtZn
JhbWV3b3JrMAoGCCqGSM49BAMCA2gAMGUCMEX62qLvLZVT67SIRNhkGtAqnjqOSit32uL0Hnlf
Ly2QmwPygQmUa04tkoOtf8GhhQIxAJueTu1QEJ9fDrcALM-Ys_7kEUB-Ze4w-wEEvtZzguqD3h
9cxIjmEBdkATInQ0BNClkCgNgYWQJ7pmdkb2NUeXBleBhldS5ldXJvcGEuZWMuZXVkaXcucGlk
LjFndmVyc2lvbmMxLjBsdmFsaWRpdHlJbmZvo2ZzaWduZWTAdDIwMjMtMTEtMDlUMTQ6NTI6Mz
laaXZhbGlkRnJvbcB0MjAyMy0xMS0wOVQxNDo1MjozOVpqdmFsaWRVbnRpbMB0MjAyNC0wMi0x
N1QwMDowMDowMFpsdmFsdWVEaWdlc3RzoXgYZXUuZXVyb3BhLmVjLmV1ZGl3LnBpZC4xqQBYID
5sw3SZR5gy-dq2Hti1SpQwPIqmPLBYzhyERS_szsLjAVgglDXLX4pQBIV3H-RIT2FYLBECnQUP
UuS6krTINwXgnAECWCCUJ-qaB1TSmJWD7nxa3i9ZU4iOyaBbZkUGXlHj0Vw3bQNYINLsiLYiwL
I_7LvGVRIEKkaD17tl7no0hq92FX4SQ6tEBFggKPg879SPzr9iWo6vi_2wdFbep33D-izjCrqc
jFDesSQFWCA2SH-DH52oGL1D4NcVRgaJqWN6You9h8ZH85cr_-AhNQZYIHBtgMUXuj0ifnFect
PWHgA1XBWTcPpysjfDyaKoy9t_B1ggZeACDTM7d6fCW5Mc8er4_I0EqhLzzaTvFDf7nSVJ3R4I
WCDXbFUlmVhTr88PcHI67KL3YOzWQd20-T8TkJqoZ3Cx221kZXZpY2VLZXlJbmZvoWlkZXZpY2
VLZXmkAQIgASFYIGnFtLlPlN2AJ80EKW3PKKa8kROJpSM4x1xABck19Q-lIlgg32KKtkQwHBmc
rvVxoJZdmFHY4hXRakJrCkl4nSuPTjFvZGlnZXN0QWxnb3JpdGhtZ1NIQS0yNTZYQG4p4t9PWK
REh0_nGgxWiYV9Oq3rOqTXhE6CYtRAR0ies_BpSVSkUTbZniLcAp-nT0IvI-_le8hWC3iWSChd
WWpqbmFtZVNwYWNlc6F4GGV1LmV1cm9wYS5lYy5ldWRpdy5waWQuMYnYGFiIpGZyYW5kb21YIM
O_HzYnttnHb0yHd20C61HPPbnVvhjZ-JAiwzQg_chSaGRpZ2VzdElEAGxlbGVtZW50VmFsdWV4
ISBGb28gYmF0IGFkbWluaXN0cmF0aXZlIGF1dGhvcml0eXFlbGVtZW50SWRlbnRpZmllcnFpc3
N1aW5nX2F1dGhvcml0edgYWIOkZnJhbmRvbVgg2RsmtUKTY2LLmr62OuR9XZAmqMtMP1PhpgbB
yveNO_JoZGlnZXN0SUQBbGVsZW1lbnRWYWx1ZXgkNTc3MTFjMjYtZjBkNC00NmFkLTliYjQtYW
RkNTE5MDI1YjNkcWVsZW1lbnRJZGVudGlmaWVyaXVuaXF1ZV9pZNgYWGSkZnJhbmRvbVggNh1c
mH2nCaczqnmqcnamE-2Z9lx3ntu0OmUsXxF0ZVloZGlnZXN0SUQCbGVsZW1lbnRWYWx1ZWVCYW
Jpc3FlbGVtZW50SWRlbnRpZmllcmpnaXZlbl9uYW1l2BhYbaRmcmFuZG9tWCBC9Pl6hc0JLisV
2J9IQUfs9ZTXVhCoe85FSFXBK8-qdmhkaWdlc3RJRANsZWxlbWVudFZhbHVl2QPsajIwMjQtMD
ItMTdxZWxlbWVudElkZW50aWZpZXJrZXhwaXJ5X2RhdGXYGFhspGZyYW5kb21YID_I8pi1wFu6
o0UN0R7VGHP_ho-AACUBDVnth_UNJ-QRaGRpZ2VzdElEBGxlbGVtZW50VmFsdWXZA-xqMjAyMy
0xMS0wOXFlbGVtZW50SWRlbnRpZmllcmpiaXJ0aF9kYXRl2BhYX6RmcmFuZG9tWCC_AmIAH-mv
urJOAnIUGsOy3G7sl8PdFMt3lLSB_fjRO2hkaWdlc3RJRAVsZWxlbWVudFZhbHVl9XFlbGVtZW
50SWRlbnRpZmllcmppc19vdmVyXzE42BhYZqRmcmFuZG9tWCBqznUqqbCSDDPMzbilMxNZ0JKp
OCk32u2FBNEDv0vpFWhkaWdlc3RJRAZsZWxlbWVudFZhbHVlZlJvdXRpc3FlbGVtZW50SWRlbn
RpZmllcmtmYW1pbHlfbmFtZdgYWGakZnJhbmRvbVggLHJ8WFXncKMwTD3LRagOfLkRPbOzHYNZ
T4wCBPcJAFFoZGlnZXN0SUQHbGVsZW1lbnRWYWx1ZWJGQ3FlbGVtZW50SWRlbnRpZmllcm9pc3
N1aW5nX2NvdW50cnnYGFhvpGZyYW5kb21YIEp-BnPVwHaFuxEwOOvm5rWfgj1RZRi1yPr86MxX
to20aGRpZ2VzdElECGxlbGVtZW50VmFsdWXZA-xqMjAyMy0xMS0wOXFlbGVtZW50SWRlbnRpZm
llcm1pc3N1YW5jZV9kYXRl
""".trimIndent().replace("\n", "")
private val otherHex =
"""
A2626964781E6469643A6578616D706C653A313233343536373839616263
6465666768696E61757468656E7469636174696F6E81A462696478256469
643A6578616D706C653A313233343536373839616263646566676869236B
6579732D316474797065781A45643235353139566572696669636174696F
6E4B6579323031386A636F6E74726F6C6C6572781E6469643A6578616D70
6C653A3132333435363738396162636465666768696F7075626C69634B65
79426173653538782C483343324156764C4D7636676D4D4E616D33755641
6A5A70666B634A437744776E5A6E367A3377586D715056
""".trimIndent().replace("\n", "")
}
|
cbor/lib/src/commonTest/kotlin/io/github/routis/cbor/TestSupport.kt | 972144710 | package io.github.routis.cbor
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
val jsonSupport =
Json {
prettyPrint = true
ignoreUnknownKeys = true
}
// https://github.com/cbor/test-vectors/blob/master/appendix_a.json
@Serializable
data class TestVector(
val cbor: String,
val hex: String,
@SerialName("roundtrip") val roundTrip: Boolean,
val decoded: JsonElement? = null,
val diagnostic: String? = null,
) {
val bytes: ByteArray by lazy {
hex.hexToByteArray(HexFormat.Default)
}
}
|
Android-Compose-App/app/src/androidTest/java/com/example/composeapp/ExampleInstrumentedTest.kt | 664356573 | package com.example.composeapp
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* 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("com.example.composeapp", appContext.packageName)
}
} |
Android-Compose-App/app/src/test/java/com/example/composeapp/ExampleUnitTest.kt | 2911153763 | package com.example.composeapp
import org.junit.Test
import org.junit.Assert.*
/**
* 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)
}
} |
Android-Compose-App/app/src/main/java/com/example/composeapp/viewmodel/CharacterVIewModel.kt | 3779628482 | package com.example.composeapp.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.composeapp.data.DataState
import com.example.composeapp.data.model.Characters
import com.example.composeapp.data.repo.remote.NetworkRepository
import com.example.composeapp.data.repo.remote.RemoteRepositoryImpl
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class CharacterViewModel @Inject constructor(private val repository: RemoteRepositoryImpl): ViewModel() {
private val _dataState = MutableStateFlow<DataState<Characters>>(DataState.Loading)
val dataState: StateFlow<DataState<Characters>> = _dataState
init {
fetchData()
}
private fun fetchData(){
_dataState.value = DataState.Loading
viewModelScope.launch {
val data = repository.getCharacterData()
NetworkRepository<Characters>().asFlow(data).collectLatest { mappedData ->
_dataState.value = mappedData
}
}
}
} |
Android-Compose-App/app/src/main/java/com/example/composeapp/ui/ListScreen.kt | 285565585 | package com.example.composeapp.ui
import androidx.compose.foundation.background
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
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.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import coil.compose.AsyncImage
import com.example.composeapp.Utils.CommonMethods.getColorByStatus
import com.example.composeapp.data.DataState
import com.example.composeapp.data.model.Characters
import com.example.composeapp.viewmodel.CharacterViewModel
@Composable
fun CharacterList(modifier: Modifier= Modifier){
val viewModel = hiltViewModel<CharacterViewModel>()
val response by viewModel.dataState.collectAsStateWithLifecycle()
when(response){
is DataState.Loading -> {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center){
CircularProgressIndicator()
}
}
is DataState.Error -> {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center){
Text(text = (response as DataState.Error).exception.localizedMessage ?: "Something went wrong")
}
}
is DataState.Success -> {
LazyColumn {
items((response as DataState.Success<Characters>).data.results){ item ->
CharacterItem(modifier = modifier,item)
}
}
}
}
}
@Composable
fun CharacterItem(modifier: Modifier = Modifier, item: Characters.Result? = null){
Card(
modifier = modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
shape = RoundedCornerShape(4.dp),
colors = CardDefaults.cardColors(
containerColor = Color(0xFF3C3E44),
contentColor = Color.Transparent
)
) {
Row {
AsyncImage(
item?.image,
contentDescription = "Character Image",
contentScale = ContentScale.Crop,
modifier = Modifier.size(width = 125.dp, height = 125.dp))
Column(
modifier = Modifier
.fillMaxWidth()
.padding(start = 8.dp)) {
Text(
text = item?.name?:"",
color = Color.White,
fontSize = 18.sp,
fontWeight = FontWeight.Bold
)
Row(
verticalAlignment = Alignment.CenterVertically) {
Box(modifier = Modifier
.size(6.dp)
.clip(CircleShape)
.background(color = getColorByStatus(item?.status)))
Text(
text = item?.status.plus(" - ").plus(item?.species?:""),
fontSize = 12.sp, color = Color.White,
modifier = Modifier.padding(start = 4.dp))
}
ItemCommonInfo("Last known Location:",item?.location?.name?:"")
// ItemCommonInfo("First seen in:",item?.episode?.getOrNull(0)?:"Unknown")
}
}
}
}
@Composable
fun ItemCommonInfo(title:String = "Last known Location:",data:String="Earth"){
Column(modifier = Modifier
.fillMaxWidth()
.padding(top = 8.dp)) {
Text(text = title, color = Color.LightGray, fontSize = 12.sp)
Text(text = data, color = Color.White, fontSize = 14.sp)
}
}
@Preview(showBackground = true, name = "CharacterList")
@Composable
fun CharacterListPreview(){
CharacterList()
}
@Preview(showBackground = true, name = "CharacterItem")
@Composable
fun CharacterItemPreview(){
CharacterItem()
}
@Preview(showBackground = true, name = "ItemCommonInfo")
@Composable
fun ItemCommonInfoPreview(){
ItemCommonInfo()
} |
Android-Compose-App/app/src/main/java/com/example/composeapp/ui/MainActivity.kt | 2210123164 | package com.example.composeapp.ui
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.composeapp.ui.theme.ComposeAppTheme
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
ComposeAppTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { paddingValues ->
Log.d("paddingValues","$paddingValues")
MainScreen(
modifier = Modifier.padding(vertical = 8.dp)
)
}
}
}
}
}
@Composable
fun MainScreen(modifier: Modifier = Modifier) {
CharacterList(modifier = modifier)
}
@Preview(showBackground = true, name = "Main screen preview")
@Composable
fun GreetingPreview() {
ComposeAppTheme {
MainScreen()
}
} |
Android-Compose-App/app/src/main/java/com/example/composeapp/ui/theme/Color.kt | 2642260128 | package com.example.composeapp.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) |
Android-Compose-App/app/src/main/java/com/example/composeapp/ui/theme/Theme.kt | 2547182440 | package com.example.composeapp.ui.theme
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.ui.platform.LocalContext
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* 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 ComposeAppTheme(
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 -> DarkColorScheme
else -> LightColorScheme
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} |
Android-Compose-App/app/src/main/java/com/example/composeapp/ui/theme/Type.kt | 1013678622 | package com.example.composeapp.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
)
*/
) |
Android-Compose-App/app/src/main/java/com/example/composeapp/App.kt | 1920916060 | package com.example.composeapp
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class App:Application() |
Android-Compose-App/app/src/main/java/com/example/composeapp/di/AppModule.kt | 2116718711 | package com.example.composeapp.di
import com.example.composeapp.Utils
import com.example.composeapp.data.repo.remote.RemoteRepository
import com.example.composeapp.data.repo.remote.RemoteRepositoryImpl
import com.example.composeapp.data.source.remote.ApiService
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
@InstallIn(SingletonComponent::class)
@Module
class AppModule {
@Singleton
@Provides
fun provideBaseUrl() = Utils.Constant.BASE_URL
@Singleton
@Provides
fun provideApiService(retrofit: Retrofit): ApiService = retrofit.create(ApiService::class.java)
@Singleton
@Provides
fun provideRetrofit(okHttpClient:OkHttpClient,baseUrl:String): Retrofit =
Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build()
@Singleton
@Provides
fun provideOkHttp(httpLoggingInterceptor: HttpLoggingInterceptor?): OkHttpClient {
val builder = OkHttpClient.Builder()
httpLoggingInterceptor?.let { interceptor ->
builder.addNetworkInterceptor(interceptor)
}
builder.connectTimeout(15, TimeUnit.SECONDS)
builder.writeTimeout(15, TimeUnit.SECONDS)
builder.readTimeout(15, TimeUnit.SECONDS)
builder.pingInterval(15, TimeUnit.SECONDS)
builder.retryOnConnectionFailure(false)
builder.followRedirects(false)
return builder.build()
}
@Singleton
@Provides
fun provideHttpLoggingInterceptor() = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}
@Singleton
@Provides
fun provideRemoteRepository(apiService: ApiService):RemoteRepository = RemoteRepositoryImpl(apiService)
} |
Android-Compose-App/app/src/main/java/com/example/composeapp/Utils.kt | 1510986040 | package com.example.composeapp
import androidx.compose.ui.graphics.Color
object Utils {
object Constant{
const val BASE_URL = "https://rickandmortyapi.com/api/"
}
object CommonMethods{
fun getColorByStatus(status: String?) =
when(status?.lowercase()){
"Alive".lowercase() -> Color.Green
"Unknown".lowercase() -> Color.LightGray
else -> Color.Red
}
}
} |
Android-Compose-App/app/src/main/java/com/example/composeapp/data/source/remote/ApiService.kt | 1902851573 | package com.example.composeapp.data.source.remote
import com.example.composeapp.data.model.Characters
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
interface ApiService {
@GET("character/")
suspend fun getCharacters(@Query("page") page:Int):Response<Characters>
} |
Android-Compose-App/app/src/main/java/com/example/composeapp/data/model/Characters.kt | 1948656863 | package com.example.composeapp.data.model
import com.google.gson.annotations.SerializedName
data class Characters(
@SerializedName("info")
val info: Info,
@SerializedName("results")
val results: List<Result>
) {
data class Info(
@SerializedName("count")
val count: Int, // 826
@SerializedName("next")
val next: String, // https://rickandmortyapi.com/api/character?page=2
@SerializedName("pages")
val pages: Int, // 42
@SerializedName("prev")
val prev: Any? // null
)
data class Result(
@SerializedName("created")
val created: String, // 2017-11-04T18:48:46.250Z
@SerializedName("episode")
val episode: List<String>,
@SerializedName("gender")
val gender: String, // Male
@SerializedName("id")
val id: Int, // 1
@SerializedName("image")
val image: String, // https://rickandmortyapi.com/api/character/avatar/1.jpeg
@SerializedName("location")
val location: Location,
@SerializedName("name")
val name: String, // Rick Sanchez
@SerializedName("origin")
val origin: Origin,
@SerializedName("species")
val species: String, // Human
@SerializedName("status")
val status: String, // Alive
@SerializedName("type")
val type: String,
@SerializedName("url")
val url: String // https://rickandmortyapi.com/api/character/1
) {
data class Location(
@SerializedName("name")
val name: String, // Citadel of Ricks
@SerializedName("url")
val url: String // https://rickandmortyapi.com/api/location/3
)
data class Origin(
@SerializedName("name")
val name: String, // Earth (C-137)
@SerializedName("url")
val url: String // https://rickandmortyapi.com/api/location/1
)
}
} |
Android-Compose-App/app/src/main/java/com/example/composeapp/data/DataState.kt | 2739538894 | package com.example.composeapp.data
sealed class DataState<out T> {
data object Loading : DataState<Nothing>()
data class Success<T>(val data: T) : DataState<T>()
data class Error(val exception: Exception) : DataState<Nothing>()
} |
Android-Compose-App/app/src/main/java/com/example/composeapp/data/repo/Repository.kt | 2102868780 | package com.example.composeapp.data.repo
interface Repository |
Android-Compose-App/app/src/main/java/com/example/composeapp/data/repo/remote/RemoteRepositoryImpl.kt | 1754981268 | package com.example.composeapp.data.repo.remote
import com.example.composeapp.data.source.remote.ApiService
import javax.inject.Inject
class RemoteRepositoryImpl @Inject constructor(
private val apiService: ApiService
):RemoteRepository {
override suspend fun getCharacterData() = apiService.getCharacters(1)
} |
Android-Compose-App/app/src/main/java/com/example/composeapp/data/repo/remote/NetworkRepository.kt | 1384528744 | package com.example.composeapp.data.repo.remote
import com.example.composeapp.data.DataState
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import retrofit2.Response
class NetworkRepository<T> {
fun asFlow(response: Response<T>) = flow<DataState<T>> {
// val response = fetchFromNetwork()
val data = response.body()
if(response.isSuccessful && data != null){
emit(DataState.Success(data))
}else{
emit(DataState.Error(Exception(response.errorBody()?.string())))
}
}.catch {
emit(DataState.Error(Exception(it)))
}
// protected abstract suspend fun fetchFromNetwork():Response<T>
} |
Android-Compose-App/app/src/main/java/com/example/composeapp/data/repo/remote/RemoteRepository.kt | 3887669971 | package com.example.composeapp.data.repo.remote
import com.example.composeapp.data.model.Characters
import com.example.composeapp.data.repo.Repository
import kotlinx.coroutines.flow.Flow
import retrofit2.Response
interface RemoteRepository:Repository {
suspend fun getCharacterData(): Response<Characters>
} |
GlideListenerBugSample/app/src/androidTest/java/com/pluu/glidelistenerbugsample/ExampleInstrumentedTest.kt | 2361412476 | package com.pluu.glidelistenerbugsample
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("com.pluu.glidelistenerbugsample", appContext.packageName)
}
} |
GlideListenerBugSample/app/src/test/java/com/pluu/glidelistenerbugsample/ExampleUnitTest.kt | 83043424 | package com.pluu.glidelistenerbugsample
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)
}
} |
GlideListenerBugSample/app/src/main/java/com/pluu/glidelistenerbugsample/MainActivity.kt | 1139665019 | package com.pluu.glidelistenerbugsample
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.pluu.glidelistenerbugsample.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val image1 =
"https://plus.unsplash.com/premium_photo-1669885054268-cbd716cb8b52?q=80&w=2713&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"
private val image2 =
"https://images.unsplash.com/photo-1547721064-da6cfb341d50?q=80&w=2574&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"
private val image3 =
"https://images.unsplash.com/photo-1485470733090-0aae1788d5af?q=80&w=2717&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.btn1.setOnClickListener {
loadImage(image1)
}
binding.btn2.setOnClickListener {
loadImage(image2)
}
binding.btn3.setOnClickListener {
loadImage(image3)
}
}
private fun loadImage(url: String) {
val listener = object : RequestListener<Drawable> {
override fun onLoadFailed(
e: GlideException?,
model: Any?,
target: Target<Drawable>?,
isFirstResource: Boolean
): Boolean {
Log.d("TAG", "[onLoadFailed] = ${hashCode()}")
return false
}
override fun onResourceReady(
resource: Drawable?,
model: Any?,
target: Target<Drawable>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
Log.d("TAG", "[onResourceReady] = ${hashCode()}")
return false
}
}
Log.d("TAG", "[Listener] = ${listener.hashCode()} ==> $url")
Glide.with(binding.imgView)
.load(url)
.centerCrop()
.addListener(listener)
.into(binding.imgView)
}
} |
SimpleSDKconsumer/app/src/demo/java/com/loptor/mysamplesdkconsumer/WrapperModule.kt | 4098588847 | package com.loptor.mysamplesdkconsumer
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
abstract class WrapperModule {
@Binds
abstract fun bindAnalyticsService(
wrapper: DemoLibraryWrapper
): Wrapper
} |
SimpleSDKconsumer/app/src/demo/java/com/loptor/mysamplesdkconsumer/DemoLibraryWrapper.kt | 509402088 | package com.loptor.mysamplesdkconsumer
import javax.inject.Inject
class DemoLibraryWrapper @Inject constructor() : Wrapper {
override fun getGreeting(): String = "Dummy"
} |
SimpleSDKconsumer/app/src/androidTest/java/com/loptor/mysamplesdkconsumer/ExampleInstrumentedTest.kt | 930285524 | package com.loptor.mysamplesdkconsumer
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* 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("com.loptor.mysamplesdkconsumer", appContext.packageName)
}
} |
SimpleSDKconsumer/app/src/full/java/com/loptor/mysamplesdkconsumer/FullLibraryWrapper.kt | 3544369758 | package com.loptor.mysamplesdkconsumer
import com.loptor.dummylib.MyDummyLib
import javax.inject.Inject
class FullLibraryWrapper @Inject constructor() : Wrapper {
override fun getGreeting(): String = MyDummyLib.getGreeting()
} |
SimpleSDKconsumer/app/src/full/java/com/loptor/mysamplesdkconsumer/WrapperModule.kt | 3467706985 | package com.loptor.mysamplesdkconsumer
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
abstract class WrapperModule {
@Binds
abstract fun bindAnalyticsService(
wrapper: FullLibraryWrapper
): Wrapper
} |
SimpleSDKconsumer/app/src/test/java/com/loptor/mysamplesdkconsumer/ExampleUnitTest.kt | 1287523541 | package com.loptor.mysamplesdkconsumer
import org.junit.Test
import org.junit.Assert.*
/**
* 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)
}
} |
SimpleSDKconsumer/app/src/main/java/com/loptor/mysamplesdkconsumer/ui/theme/Color.kt | 3307287195 | package com.loptor.mysamplesdkconsumer.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) |
SimpleSDKconsumer/app/src/main/java/com/loptor/mysamplesdkconsumer/ui/theme/Theme.kt | 3464409917 | package com.loptor.mysamplesdkconsumer.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 DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* 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 MySampleSDKconsumerTheme(
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 -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} |
SimpleSDKconsumer/app/src/main/java/com/loptor/mysamplesdkconsumer/ui/theme/Type.kt | 96039688 | package com.loptor.mysamplesdkconsumer.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
)
*/
) |
SimpleSDKconsumer/app/src/main/java/com/loptor/mysamplesdkconsumer/MainActivity.kt | 2711844185 | package com.loptor.mysamplesdkconsumer
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.loptor.mysamplesdkconsumer.ui.theme.MySampleSDKconsumerTheme
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
@Inject
lateinit var libWrapper: Wrapper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MySampleSDKconsumerTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Greeting(libWrapper.getGreeting())
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
MySampleSDKconsumerTheme {
Greeting("Android")
}
} |
SimpleSDKconsumer/app/src/main/java/com/loptor/mysamplesdkconsumer/SampleApp.kt | 730901113 | package com.loptor.mysamplesdkconsumer
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class SampleApp : Application() |
SimpleSDKconsumer/app/src/main/java/com/loptor/mysamplesdkconsumer/Wrapper.kt | 1051828500 | package com.loptor.mysamplesdkconsumer
interface Wrapper {
fun getGreeting(): String
} |
SimpleSDKconsumer/dummylib/src/main/java/com/loptor/dummylib/MyDummyLib.kt | 3366310012 | package com.loptor.dummylib
object MyDummyLib {
fun getGreeting() = "Library"
} |
equipoSiete/app/src/androidTest/java/com/example/equipoSiete/ExampleInstrumentedTest.kt | 2515224051 | package com.example.equipoSiete
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* 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("com.example.clase8", appContext.packageName)
}
} |
equipoSiete/app/src/test/java/com/example/equipoSiete/viewmodel/LoginViewModelTest.kt | 1357985971 | package com.example.equipoSiete.viewmodel
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.example.equipoSiete.repository.InventoryRepository
import com.example.equipoSiete.repository.LoginRepository
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.MockitoAnnotations
class LoginViewModelTest {
@get:Rule
val rule = InstantTaskExecutorRule() //código que involucra LiveData y ViewModel
private lateinit var loginViewModel: LoginViewModel
private lateinit var loginRepository: LoginRepository
@Before
fun setUp() {
loginRepository = mock(LoginRepository::class.java)
loginViewModel = LoginViewModel(loginRepository)
}
@Test
fun `test método registerUser`(){
val email="[email protected]"
val password="123456"
val expectedResult=true
//when
`when`(loginRepository.registerUser(email,password){}).thenAnswer{
val callback=it.arguments[2] as (Boolean)-> Unit
callback.invoke(expectedResult)
}
//then
loginViewModel.registerUser(email,password){
result ->assert(result)
}
}
} |
equipoSiete/app/src/test/java/com/example/equipoSiete/viewmodel/InventoryViewModelTest.kt | 2350807425 | package com.example.equipoSiete.viewmodel
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.example.equipoSiete.model.Inventory
import com.example.equipoSiete.model.Product
import com.example.equipoSiete.repository.InventoryRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify
import org.mockito.Mockito.`when`
class InventoryViewModelTest {
@get:Rule
val rule = InstantTaskExecutorRule() //código que involucra LiveData y ViewModel
private lateinit var inventoryViewModel: InventoryViewModel
private lateinit var inventoryRepository: InventoryRepository
@Before
fun setUp() {
inventoryRepository = mock(InventoryRepository::class.java)
inventoryViewModel = InventoryViewModel(inventoryRepository)
}
@Test
fun `test método totalProducto`(){
//given (qué necesitamos:condiciones previas necesarias para que la prueba se ejecute correctamente)
val price = 10000
val quantity = 5
val expectedResult = (price * quantity).toDouble()
//when (Aquí, ejecutas el código o la función que estás evaluando.)
val resul = inventoryViewModel.totalProducto(price, quantity)
//Then (lo que tiene que pasar:resultados esperados )
assertEquals(expectedResult, resul,0.0)
}
@Test
fun `test método getListInventory`() = runBlocking {
//given
// es responsable de ejecutar tareas en el hilo principal, necesitamos simular ese proceso
Dispatchers.setMain(UnconfinedTestDispatcher())
// Configurar el comportamiento del repositorio simulado
val mockInventory = mutableListOf(
Inventory(7, "zapatos", 60000,4)
)
`when`(inventoryRepository.getListInventory()).thenReturn(mockInventory)
// Llamar a la función que queremos probar
//when
inventoryViewModel.getListInventory()
// Asegurarse de que la LiveData de productos se haya actualizado correctamente
//then
assertEquals(inventoryViewModel.listInventory.value, mockInventory)
// son utilizados para controlar y simular la ejecución de coroutines en el hilo principal durante las pruebas unitarias
Dispatchers.resetMain()
}
@Test
fun testSaveInventory_success() = runBlocking {
//given
Dispatchers.setMain(UnconfinedTestDispatcher())
val inventory= Inventory(codigo = 1, nombre = "Item1", precio = 10, cantidad = 5)
`when`(inventoryRepository.saveInventory(inventory))
.thenAnswer { invocation ->
val inventoryArgument = invocation.getArgument<Inventory>(0)//inventoryArgument contendrá el valor del primer argumento que se pasó al método
inventoryArgument
}
// Llamamos al método que queremos probar
inventoryViewModel.saveInventory(inventory)
// Verificamos que el estado de progreso sea falso después de la operación
verify(inventoryRepository).saveInventory(inventory)
Dispatchers.resetMain()
}
} |
equipoSiete/app/src/main/java/com/example/equipoSiete/viewmodel/InventoryViewModel.kt | 432393705 | package com.example.equipoSiete.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.equipoSiete.model.Inventory
import com.example.equipoSiete.model.Product
import com.example.equipoSiete.repository.InventoryRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class InventoryViewModel @Inject constructor(
private val inventoryRepository: InventoryRepository
) : ViewModel() {
private val _listInventory = MutableLiveData<MutableList<Inventory>>()
val listInventory: LiveData<MutableList<Inventory>> get() = _listInventory
private val _progresState = MutableLiveData(false)
val progresState: LiveData<Boolean> = _progresState
//para almacenar una lista de productos
private val _listProducts = MutableLiveData<MutableList<Product>>()
val listProducts: LiveData<MutableList<Product>> = _listProducts
fun saveInventory(inventory: Inventory) {
viewModelScope.launch {
_progresState.value = true
try {
inventoryRepository.saveInventory(inventory)
_progresState.value = false
} catch (e: Exception) {
_progresState.value = false
}
}
}
fun getListInventory() {
viewModelScope.launch {
_progresState.value = true
try {
_listInventory.value = inventoryRepository.getListInventory()
_progresState.value = false
} catch (e: Exception) {
_progresState.value = false
}
}
}
fun deleteInventory(inventory: Inventory) {
viewModelScope.launch {
_progresState.value = true
try {
inventoryRepository.deleteInventory(inventory)
_progresState.value = false
} catch (e: Exception) {
_progresState.value = false
}
}
}
fun updateInventory(inventory: Inventory) {
viewModelScope.launch {
_progresState.value = true
try {
inventoryRepository.updateRepositoy(inventory)
_progresState.value = false
} catch (e: Exception) {
_progresState.value = false
}
}
}
fun totalProducto(price: Int, quantity: Int): Double {
val total = price * quantity
return total.toDouble()
}
}
|
equipoSiete/app/src/main/java/com/example/equipoSiete/viewmodel/LoginViewModel.kt | 1582342159 | package com.example.equipoSiete.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.equipoSiete.repository.InventoryRepository
import com.example.equipoSiete.repository.LoginRepository
import com.google.firebase.auth.FirebaseAuth
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class LoginViewModel @Inject constructor(
private val loginRepository: LoginRepository
) : ViewModel() {
//private val repository = LoginRepository()
//registerUser se comunica con el repository
fun registerUser(email: String, pass: String, isRegister: (Boolean) -> Unit) {
loginRepository.registerUser(email, pass) { response ->
isRegister(response)
}
}
fun loginUser(email: String, pass: String, isLogin: (Boolean) -> Unit) {
if (email.isNotEmpty() && pass.isNotEmpty()) {
FirebaseAuth.getInstance()
.signInWithEmailAndPassword(email, pass)
.addOnCompleteListener {
if (it.isSuccessful) {
isLogin(true)
} else {
isLogin(false)
}
}
} else {
isLogin(false)
}
}
fun sesion(email: String?, isEnableView: (Boolean) -> Unit) {
if (email != null) {
isEnableView(true)
} else {
isEnableView(false)
}
}
} |
equipoSiete/app/src/main/java/com/example/equipoSiete/repository/InventoryRepository.kt | 1886130425 | package com.example.equipoSiete.repository
import android.widget.Toast
import com.example.equipoSiete.data.InventoryDao
import com.example.equipoSiete.model.Inventory
import com.example.equipoSiete.model.Product
import com.example.equipoSiete.webservice.ApiService
import com.google.firebase.firestore.FirebaseFirestore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.tasks.await
import kotlinx.coroutines.withContext
import javax.inject.Inject
class InventoryRepository @Inject constructor(
private val inventoryDao: InventoryDao,
private val apiService: ApiService,
private val db: FirebaseFirestore,
){
suspend fun saveInventory(inventory:Inventory) {
withContext(Dispatchers.IO) {
try {
db.collection("articulo").document(inventory.codigo.toString()).set(
hashMapOf(
"codigo" to inventory.codigo,
"nombre" to inventory.nombre,
"precio" to inventory.precio,
"cantidad" to inventory.cantidad
)
).await()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
suspend fun getListInventory():MutableList<Inventory>{
return withContext(Dispatchers.IO){
try {
val snapshot = db.collection("articulo").get().await()
val inventoryList = mutableListOf<Inventory>()
for (document in snapshot.documents) {
val codigo = document.getLong("codigo")?.toInt() ?: 0
val nombre = document.getString("nombre") ?: ""
val precio = document.getLong("precio")?.toInt() ?: 0
val cantidad = document.getLong("cantidad")?.toInt() ?: 0
val item = Inventory(codigo, nombre, precio, cantidad)
inventoryList.add(item)
}
inventoryList
} catch (e: Exception) {
e.printStackTrace()
mutableListOf()
}
}
}
suspend fun deleteInventory(inventory: Inventory) {
withContext(Dispatchers.IO) {
try {
// Aquí asumo que 'codigo' es un identificador único para Inventory
val codigo = inventory.codigo
// Obtener una referencia al documento que queremos eliminar
val documentReference = db.collection("articulo").document(codigo.toString())
// Eliminar el documento
documentReference.delete().await()
} catch (e: Exception) {
e.printStackTrace()
// Manejar la excepción según tus necesidades
}
}
}
suspend fun updateRepositoy(inventory: Inventory){
withContext(Dispatchers.IO) {
try {
db.collection("articulo").document(inventory.codigo.toString()).update(
mapOf(
"nombre" to inventory.nombre,
"precio" to inventory.precio,
"cantidad" to inventory.cantidad
)
).await()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
suspend fun getProducts(): MutableList<Product> {
return withContext(Dispatchers.IO) {
try {
val response = apiService.getProducts()
response
} catch (e: Exception) {
e.printStackTrace()
mutableListOf()
}
}
}
} |
equipoSiete/app/src/main/java/com/example/equipoSiete/repository/LoginRepository.kt | 2600205870 | package com.example.equipoSiete.repository
import com.example.equipoSiete.data.InventoryDao
import com.example.equipoSiete.webservice.ApiService
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import javax.inject.Inject
class LoginRepository @Inject constructor(
){
private val firebaseAuth = FirebaseAuth.getInstance()
fun registerUser(email: String, pass:String, isRegisterComplete: (Boolean)->Unit){
if(email.isNotEmpty() && pass.isNotEmpty()){
firebaseAuth.createUserWithEmailAndPassword(email,pass)
.addOnCompleteListener {
if (it.isSuccessful) {
isRegisterComplete(true)
} else {
isRegisterComplete(false)
}
}
}else{
isRegisterComplete(false)
}
}
} |
equipoSiete/app/src/main/java/com/example/equipoSiete/AppExample.kt | 1345241535 | package com.example.equipoSiete
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class AppExample:Application() |
equipoSiete/app/src/main/java/com/example/equipoSiete/di/Module.kt | 779881955 | package com.example.equipoSiete.di
import android.content.Context
import com.example.equipoSiete.data.InventoryDB
import com.example.equipoSiete.data.InventoryDao
import com.example.equipoSiete.utils.Constants.BASE_URL
import com.example.equipoSiete.webservice.ApiService
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object Module {
@Singleton
@Provides
fun provideInventoryDB(@ApplicationContext context: Context):InventoryDB{
return InventoryDB.getDatabase(context)
}
@Singleton
@Provides
fun provideRetrofit(): Retrofit {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
@Singleton
@Provides
fun provideApiService(retrofit: Retrofit): ApiService {
return retrofit.create(ApiService::class.java)
}
@Singleton
@Provides
fun provideDaoReto(inventoryDB:InventoryDB): InventoryDao {
return inventoryDB.inventoryDao()
}
@Singleton
@Provides
fun provideFirestoreDB(): FirebaseFirestore {
return FirebaseFirestore.getInstance()
}
@Singleton
@Provides
fun provideAuthDB(): FirebaseAuth {
return FirebaseAuth.getInstance()
}
} |
equipoSiete/app/src/main/java/com/example/equipoSiete/widget/widget.kt | 2407598115 | package com.example.equipoSiete.widget
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.icu.text.NumberFormat
import android.util.Log
import android.widget.RemoteViews
import com.example.equipoSiete.R
import com.example.equipoSiete.view.LoginActivity
import com.example.equipoSiete.viewmodel.InventoryViewModel
import com.google.firebase.auth.FirebaseAuth
import androidx.activity.viewModels
import androidx.lifecycle.ViewModelProvider
import com.example.equipoSiete.view.MainActivity
import com.example.equipoSiete.view.fragment.HomeInventoryFragment
import com.google.firebase.firestore.FirebaseFirestore
import java.util.Locale
/**
* Implementation of App Widget functionality.
*/
class widget() : AppWidgetProvider() {
companion object {
var saldoVisible: Boolean = false
var total = 0L
}
override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray
) {
// There may be multiple widgets active, so update all of them
for (appWidgetId in appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId)
}
}
override fun onEnabled(context: Context) {
// Enter relevant functionality for when the first widget is created
}
override fun onDisabled(context: Context) {
// Enter relevant functionality for when the last widget is disabled
}
override fun onReceive(context: Context?, intent: Intent?) {
super.onReceive(context, intent)
when (intent!!.action?: "") {
"ICON_CLICKED_ACTION" -> {
println(isUserLoggedIn())
if (isUserLoggedIn()) {
updateSaldoWidget(context!!)
} else {
val loginIntent = Intent(context, LoginActivity::class.java)
context?.sendBroadcast(loginIntent)
loginIntent.putExtra("fromWidget", true)
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context?.startActivity(loginIntent)
}
}
"LOGIN_SUCCESSFUL" -> {
updateTextWidget(context!!)
}
"LOGOFF_SUCCESSFUL" -> {
userLogoff(context!!)
}
"CONFIG_CLICKED_ACTION" -> {
println(isUserLoggedIn())
if (isUserLoggedIn()) {
val homeIntent = Intent(context, MainActivity::class.java)
homeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context?.startActivity(homeIntent)
} else {
val loginIntent = Intent(context, LoginActivity::class.java)
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context?.startActivity(loginIntent)
}
}
"TEXT_GESTIONAR_CLICKED_ACTION" ->{
if (isUserLoggedIn()) {
val homeIntent = Intent(context, MainActivity::class.java)
homeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context?.startActivity(homeIntent)
} else {
val loginIntent = Intent(context, LoginActivity::class.java)
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context?.startActivity(loginIntent)
}
}
"UPDATE_TOTAL" ->{
updateTextWidget(context!!)
}
}
}
private fun updateTextWidget(context: Context) {
totalInventario { newTotal ->
val valor = formatearPrecio(newTotal.toDouble())
val appWidgetManager = AppWidgetManager.getInstance(context)
val thisAppWidget = ComponentName(context.packageName, javaClass.name)
val appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidget)
val views = RemoteViews(context.packageName, R.layout.widget)
views.setImageViewResource(R.id.iconImageView, R.drawable.visibilidad_off)
views.setTextViewText(R.id.text_saldo, "$ $valor")
saldoVisible = true
appWidgetManager.updateAppWidget(appWidgetIds, views)
}
}
private fun isUserLoggedIn(): Boolean {
// Verificar si el usuario está autenticado en Firebase
val firebaseAuth = FirebaseAuth.getInstance()
return firebaseAuth.currentUser != null
}
private fun updateSaldoWidget(context: Context) {
totalInventario { newTotal ->
val valor = formatearPrecio(newTotal.toDouble())
val appWidgetManager = AppWidgetManager.getInstance(context)
val thisAppWidget = ComponentName(context.packageName, javaClass.name)
val appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidget)
val views = RemoteViews(context.packageName, R.layout.widget)
if (saldoVisible) {
views.setImageViewResource(R.id.iconImageView, R.drawable.visibility_image)
views.setTextViewText(R.id.text_saldo, "$ * * * *")
saldoVisible = false
} else {
views.setImageViewResource(R.id.iconImageView, R.drawable.visibilidad_off)
views.setTextViewText(R.id.text_saldo, "$ $valor")
saldoVisible = true
}
// Actualizar todos los widgets
appWidgetManager.updateAppWidget(appWidgetIds, views)
}
}
private fun formatearPrecio(precio: Double): String {
val numberFormat = NumberFormat.getNumberInstance(Locale("es", "ES"))
numberFormat.minimumFractionDigits = 2
numberFormat.maximumFractionDigits = 2
return numberFormat.format(precio)
}
private fun userLogoff(context: Context) {
val appWidgetManager = AppWidgetManager.getInstance(context)
val thisAppWidget = ComponentName(context.packageName, javaClass.name)
val appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidget)
val views = RemoteViews(context.packageName, R.layout.widget)
views.setImageViewResource(R.id.iconImageView, R.drawable.visibility_image)
views.setTextViewText(R.id.text_saldo, "$ * * * *")
appWidgetManager.updateAppWidget(appWidgetIds, views)
}
private fun totalInventario(callback: (Long) -> Unit) {
var total: Long = 0
val db = FirebaseFirestore.getInstance()
db.collection("articulo")
.get()
.addOnSuccessListener { querySnapshot ->
for (document in querySnapshot) {
val price = document.get("precio") as Long
val quantity = document.get("cantidad") as Long
println("Cantidad: ${quantity.toInt()}")
println("Precio: ${price.toInt()}")
total += price * quantity
}
callback(total)
}
.addOnFailureListener { exception ->
println("Error al obtener datos: $exception")
// Manejar el error según sea necesario
}
}
private fun pendingIntent(
context: Context?,
action:String
): PendingIntent? {
val intent = Intent(context, javaClass)
intent.action = action
return PendingIntent.getBroadcast(
context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
}
internal fun updateAppWidget(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetId: Int
) {
val widgetText = context.getString(R.string.appwidget_text)
// Construct the RemoteViews object
val views = RemoteViews(context.packageName, R.layout.widget)
views.setOnClickPendingIntent(R.id.iconImageView, pendingIntent(context, "ICON_CLICKED_ACTION"))
views.setOnClickPendingIntent(R.id.config_image, pendingIntent(context, "CONFIG_CLICKED_ACTION"))
views.setOnClickPendingIntent(R.id.text_gestionarinventario, pendingIntent(context, "TEXT_GESTIONAR_CLICKED_ACTION"))
//views.setTextViewText(R.id.appwidget_text, widgetText)
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.