general: fix TrueDao & DatabaseViewModel
- Commit
923218f27244cf5bb84ee228a62c85bd79df335f- Author
- Vayun Mathur <[email protected]>
- When
- 2026-02-17 08:10 UTC (9 months ago)
- Parents
52d66f5
Diff
calendar/src/main/java/com/vayunmathur/calendar/ImportActivity.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/ImportActivity.kt b/calendar/src/main/java/com/vayunmathur/calendar/ImportActivity.ktindex 688caa74cc..662e4e39f1 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/ImportActivity.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/ImportActivity.kt@@ -50,6 +50,8 @@ import kotlinx.datetime.atTime import kotlinx.datetime.format.DateTimeComponents import kotlinx.datetime.format.char import kotlinx.datetime.toInstant+import java.io.BufferedInputStream+import java.io.InputStream import kotlin.time.Duration import kotlin.time.Duration.Companion.days import kotlin.time.Duration.Companion.milliseconds@@ -205,7 +207,7 @@ fun EventCard(event: Event) { } // Simple ICS parser that returns a list of Event (uses the app's Event class)-fun parseICSFile(iS: InputS): List<Event> {+fun parseICSFile(iS: InputStream): List<Event> { val events = mutableListOf<Event>() // Read and unfold lines (lines that start with space or tab are continuations)@@ -393,7 +395,7 @@ private fun tryParseDurationMillis(duration: String, startMillis: Long): Long? { // This handles the full yyyyMMdd'T'HHmmssZ pattern val BasicIsoInstantFormat = DateTimeComponents.Format {- year(); monthNumber(); dayOfMonth()+ year(); monthNumber(); day() char('T') hour(); minute(); second() // ISO_BASIC handles 'Z' or '+HHmm' (no colons)@@ -402,18 +404,18 @@ val BasicIsoInstantFormat = DateTimeComponents.Format { // Format for all-day events: yyyyMMdd val AllDayFormat = LocalDate.Format {- year(); monthNumber(); dayOfMonth()+ year(); monthNumber(); day() } // Formats for local times without offset val DateTimeFormat = LocalDateTime.Format {- year(); monthNumber(); dayOfMonth()+ year(); monthNumber(); day() char('T') hour(); minute(); second() } val DateTimeShortFormat = LocalDateTime.Format {- year(); monthNumber(); dayOfMonth()+ year(); monthNumber(); day() char('T') hour(); minute() }\ No newline at end of file
contacts/src/main/java/com/vayunmathur/contacts/Contact.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/Contact.kt b/contacts/src/main/java/com/vayunmathur/contacts/Contact.ktindex 3220566477..a6bb252c21 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/Contact.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/Contact.kt@@ -340,7 +340,7 @@ data class Contact( if(details.names.isEmpty()) details = details.copy(names = listOf(Name(0, "", "", "", "", ""))) - if((details.names.first().firstName.isEmpty() && details.names.first().lastName.isEmpty()) && displayName != null) {+ if((details.names.first().firstName.isEmpty() && details.names.first().lastName.isEmpty())) { val firstName = displayName.split(" ").first() val lastName = displayName.split(" ").last() if(firstName.isEmpty() && lastName.isEmpty()) return null
findfamily/src/main/java/com/vayunmathur/findfamily/LocationTrackingService.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/LocationTrackingService.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/LocationTrackingService.ktindex 9bbeae722e..b92539b90f 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/LocationTrackingService.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/LocationTrackingService.kt@@ -140,7 +140,7 @@ class LocationTrackingService : Service() { private fun startTracking() { val db = buildDatabase<FFDatabase>()- viewModel = DatabaseViewModel(+ viewModel = DatabaseViewModel(db, User::class to db.userDao(), Waypoint::class to db.waypointDao(), LocationValue::class to db.locationValueDao(),
findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.ktindex f59b49bbc7..f6615231d4 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.kt@@ -54,7 +54,7 @@ class MainActivity : ComponentActivity() { super.onCreate(savedInstanceState) enableEdgeToEdge() val db = buildDatabase<FFDatabase>()- val viewModel = DatabaseViewModel(User::class to db.userDao(), Waypoint::class to db.waypointDao(), LocationValue::class to db.locationValueDao(), TemporaryLink::class to db.temporaryLinkDao())+ val viewModel = DatabaseViewModel(db, User::class to db.userDao(), Waypoint::class to db.waypointDao(), LocationValue::class to db.locationValueDao(), TemporaryLink::class to db.temporaryLinkDao()) val platform = Platform(this) setContent { DynamicTheme {
findfamily/src/main/java/com/vayunmathur/findfamily/Networking.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/Networking.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/Networking.ktindex b1d596493c..ec424ee774 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/Networking.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/Networking.kt@@ -24,6 +24,7 @@ import io.ktor.util.decodeBase64Bytes import io.ktor.util.encodeBase64 import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json+import kotlin.io.encoding.Base64 import kotlin.properties.Delegates import kotlin.random.Random @@ -110,7 +111,8 @@ object Networking { data class Register(val userid: ULong, val key: String) return makeRequest("/api/register", Register( userid.toULong(),- publickey!!.encodeToByteArray(RSA.PublicKey.Format.PEM).encodeBase64())+ Base64.encode(publickey!!.encodeToByteArray(RSA.PublicKey.Format.PEM))+ ) ) ?: false } @@ -129,16 +131,20 @@ object Networking { if(response.status != HttpStatusCode.OK) { return@checkNetworkDown null }- return@checkNetworkDown crypto.publicKeyDecoder(SHA512).decodeFromByteArray(RSA.PublicKey.Format.PEM, response.bodyAsText().decodeBase64Bytes())+ return@checkNetworkDown crypto.publicKeyDecoder(SHA512).decodeFromByteArray(RSA.PublicKey.Format.PEM,+ Base64.decode(response.bodyAsText())+ ) } } suspend fun publishLocation(location: LocationValue, user: User): Boolean { val key = if(user.encryptionKey != null) {- crypto.publicKeyDecoder(SHA512).decodeFromByteArray(RSA.PublicKey.Format.PEM, user.encryptionKey.decodeBase64Bytes())+ crypto.publicKeyDecoder(SHA512).decodeFromByteArray(RSA.PublicKey.Format.PEM,+ Base64.decode(user.encryptionKey)+ ) } else { getKey(user.id.toULong())?.also {- val keyString = it.encodeToByteArray(RSA.PublicKey.Format.PEM).encodeBase64()+ val keyString = Base64.encode(it.encodeToByteArray(RSA.PublicKey.Format.PEM)) viewModel.upsert(user.copy(encryptionKey = keyString)) } } ?: return false@@ -146,7 +152,9 @@ object Networking { } suspend fun publishLocation(location: LocationValue, user: TemporaryLink): Boolean {- val key = crypto.publicKeyDecoder(SHA512).decodeFromByteArray(RSA.PublicKey.Format.PEM, user.publicKey.decodeBase64Bytes())+ val key = crypto.publicKeyDecoder(SHA512).decodeFromByteArray(RSA.PublicKey.Format.PEM,+ Base64.decode(user.publicKey)+ ) return makeRequest("/api/location/publish", encryptLocation(location, user.id.toULong(), key)) ?: false } @@ -158,13 +166,13 @@ object Networking { private suspend fun encryptLocation(location: LocationValue, recipientUserID: ULong, key: RSA.OAEP.PublicKey): LocationSharingData { val cipher = key.encryptor() val str = Json.encodeToString(location)- val encryptedData = cipher.encrypt(str.encodeToByteArray()).encodeBase64()+ val encryptedData = Base64.encode(cipher.encrypt(str.encodeToByteArray())) return LocationSharingData(recipientUserID, encryptedData) } private suspend fun decryptLocation(encryptedLocation: String): LocationValue { val cipher = privatekey!!.decryptor()- val decryptedData = cipher.decrypt(encryptedLocation.decodeBase64Bytes()).decodeToString()+ val decryptedData = cipher.decrypt(Base64.decode(encryptedLocation)).decodeToString() return Json.decodeFromString(decryptedData) }
findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.ktindex cd225d584e..0a1d5af163 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt@@ -1,9 +1,24 @@ package com.vayunmathur.findfamily.data +import androidx.room.Dao import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters import com.vayunmathur.library.util.DefaultConverters+import com.vayunmathur.library.util.TrueDao+++@Dao+interface LocationValueDao: TrueDao<LocationValue>++@Dao+interface WaypointDao: TrueDao<Waypoint>++@Dao+interface UserDao: TrueDao<User>++@Dao+interface TemporaryLinkDao: TrueDao<TemporaryLink> @Database(entities = [User::class, Waypoint::class, LocationValue::class, TemporaryLink::class], version = 1) @TypeConverters(DefaultConverters::class)
findfamily/src/main/java/com/vayunmathur/findfamily/data/LocationValue.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/LocationValue.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/LocationValue.ktindex 2cc13e6811..9b58d13a3d 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/LocationValue.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/LocationValue.kt@@ -21,13 +21,4 @@ data class LocationValue( val timestamp: Instant, val battery: Float, @PrimaryKey(autoGenerate = true) override val id: Long = 0-): DatabaseItem--@Dao-interface LocationValueDao: TrueDao<LocationValue> {- @Query("SELECT * FROM locationvalue")- override fun getAll(): Flow<List<LocationValue>>-- @Query("DELETE FROM locationvalue")- override suspend fun deleteAll()-}\ No newline at end of file+): DatabaseItem\ No newline at end of file
findfamily/src/main/java/com/vayunmathur/findfamily/data/TemporaryLink.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/TemporaryLink.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/TemporaryLink.ktindex 32b3311533..710fa67d11 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/TemporaryLink.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/TemporaryLink.kt@@ -21,13 +21,4 @@ data class TemporaryLink( val deleteAt: Instant, @PrimaryKey(autoGenerate = true) override val id: Long = 0,-): DatabaseItem--@Dao-interface TemporaryLinkDao: TrueDao<TemporaryLink> {- @Query("SELECT * FROM TemporaryLink")- override fun getAll(): Flow<List<TemporaryLink>>-- @Query("DELETE FROM TemporaryLink")- override suspend fun deleteAll()-}\ No newline at end of file+): DatabaseItem\ No newline at end of file
findfamily/src/main/java/com/vayunmathur/findfamily/data/User.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/User.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/User.ktindex 2ce4358e77..9831e72841 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/User.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/User.kt@@ -34,13 +34,4 @@ data class User( companion object { val EMPTY = User(" ", null, "Unnamed Location", true, RequestStatus.MUTUAL_CONNECTION, Clock.System.now(), null) }-}--@Dao-interface UserDao: TrueDao<User> {- @Query("SELECT * FROM user")- override fun getAll(): Flow<List<User>>-- @Query("DELETE FROM user")- override suspend fun deleteAll() }\ No newline at end of file
findfamily/src/main/java/com/vayunmathur/findfamily/data/Waypoint.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/Waypoint.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/Waypoint.ktindex f8d938566f..97c46458ce 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/Waypoint.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/Waypoint.kt@@ -21,13 +21,4 @@ data class Waypoint( companion object { val NEW_WAYPOINT = Waypoint("", 100.0, Coord(0.0, 0.0)) }-}--@Dao-interface WaypointDao: TrueDao<Waypoint> {- @Query("SELECT * FROM waypoint")- override fun getAll(): Flow<List<Waypoint>>-- @Query("DELETE FROM waypoint")- override suspend fun deleteAll() }\ No newline at end of file
findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.ktindex ffd2af4ab4..6f5e5a735c 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt@@ -158,7 +158,7 @@ fun MapView( if(initialized) { key(camera.position, sizeInDp) { Canvas(Modifier.fillMaxSize()) {- val allWaypoints = if(selectedWaypoint?.waypoint?.position == Double.POSITIVE_INFINITY) (waypoints + selectedWaypoint.waypoint) else waypoints+ val allWaypoints = if(selectedWaypoint?.waypoint?.id == 0L) (waypoints + selectedWaypoint.waypoint) else waypoints for (waypoint in allWaypoints) { val radiusMeters = if(selectedWaypoint?.waypoint == waypoint) selectedWaypoint.range else waypoint.range val coord = if(selectedWaypoint?.waypoint == waypoint) {
findfamily/src/main/java/com/vayunmathur/findfamily/ui/WaypointEditPage.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/WaypointEditPage.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/WaypointEditPage.ktindex e0b1f06a7b..c542cf6e27 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/WaypointEditPage.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/WaypointEditPage.kt@@ -43,7 +43,7 @@ fun WaypointEditPage(backStack: NavBackStack<Route>, viewModel: DatabaseViewMode Scaffold(floatingActionButton = { FloatingActionButton({ if(range.toDoubleOrNull() == null || name.isBlank()) return@FloatingActionButton- viewModel.upsert(waypoint.copy(name = name, range = range.toDouble(), coord = coord, position = 0.0))+ viewModel.upsert(waypoint.copy(name = name, range = range.toDouble(), coord = coord)) backStack.pop() }) { IconSave()
findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialog/AddLinkDialog.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialog/AddLinkDialog.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialog/AddLinkDialog.ktindex 10bcb9d45f..27d9926b71 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialog/AddLinkDialog.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialog/AddLinkDialog.kt@@ -41,6 +41,7 @@ import io.ktor.util.encodeBase64 import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch+import kotlin.io.encoding.Base64 import kotlin.math.pow import kotlin.random.Random import kotlin.random.nextULong@@ -75,8 +76,8 @@ fun AddLinkDialog(backStack: NavBackStack<Route>, viewModel: DatabaseViewModel, val newLink = TemporaryLink( name,- keypair.privateKey.encodeToByteArray(RSA.PrivateKey.Format.PEM).encodeBase64(),- keypair.publicKey.encodeToByteArray(RSA.PublicKey.Format.PEM).encodeBase64(),+ Base64.encode(keypair.privateKey.encodeToByteArray(RSA.PrivateKey.Format.PEM)),+ Base64.encode(keypair.publicKey.encodeToByteArray(RSA.PublicKey.Format.PEM)), Clock.System.now() + options[expiryTime]!! ) viewModel.upsert(newLink)
games/unblockjam/src/main/AndroidManifest.xml
diff --git a/games/unblockjam/src/main/AndroidManifest.xml b/games/unblockjam/src/main/AndroidManifest.xmlindex 5b4d011fdd..dc8970b481 100644--- a/games/unblockjam/src/main/AndroidManifest.xml+++ b/games/unblockjam/src/main/AndroidManifest.xml@@ -1,6 +1,5 @@ <?xml version="1.0" encoding="utf-8"?>-<manifest xmlns:android="http://schemas.android.com/apk/res/android"- xmlns:tools="http://schemas.android.com/tools">+<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <application android:allowBackup="true"
health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.kt b/health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.ktindex 451a334ba0..63775d0bbe 100644--- a/health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.kt@@ -199,7 +199,7 @@ fun BarChartDetails( ) { item { val headerLabel = when (selectedTab) {- 0 -> "${anchorDate.month.name} ${anchorDate.dayOfMonth}, ${anchorDate.year}"+ 0 -> "${anchorDate.month.name} ${anchorDate.day}, ${anchorDate.year}" 1 -> "Week of ${anchorDate.minus(anchorDate.dayOfWeek.ordinal, DateTimeUnit.DAY)}" 2 -> "${anchorDate.month.name} ${anchorDate.year}" else -> anchorDate.year.toString()@@ -322,7 +322,7 @@ fun GenericLineChart( val y = height - (value.toFloat() / maxChartValue.toFloat() * height).coerceIn(0f, height) val currentPoint = Offset(x, y) if (lastValidPoint != null) {- drawLine(color = color, start = lastValidPoint!!, end = currentPoint, strokeWidth = 3.dp.toPx())+ drawLine(color = color, start = lastValidPoint, end = currentPoint, strokeWidth = 3.dp.toPx()) } drawCircle(color = color, radius = 3.dp.toPx(), center = currentPoint) lastValidPoint = currentPoint
library/src/main/java/com/vayunmathur/library/ui/ListPage.kt
diff --git a/library/src/main/java/com/vayunmathur/library/ui/ListPage.kt b/library/src/main/java/com/vayunmathur/library/ui/ListPage.ktindex 049f66c0ea..3153051126 100644--- a/library/src/main/java/com/vayunmathur/library/ui/ListPage.kt+++ b/library/src/main/java/com/vayunmathur/library/ui/ListPage.kt@@ -61,7 +61,7 @@ inline fun <reified T : DatabaseItem, Route : NavKey, reified EditPage : Route> searchEnabled: Boolean = false, crossinline searchString: (T) -> String = {it.toString()}, ) {- val dbDataUnfiltered by viewModel.data<T>().collectAsState()+ val dbDataUnfiltered by viewModel.data<T>().collectAsState(listOf()) var searchQuery by remember { mutableStateOf("") } val dbData by remember { derivedStateOf { dbDataUnfiltered.filter { searchQuery.isBlank() || searchString(it).contains(searchQuery, true) } } } @@ -138,7 +138,7 @@ inline fun <reified T : ReorderableDatabaseItem<T>, Route : NavKey, reified Edit searchEnabled: Boolean = false, crossinline searchString: (T) -> String = {it.toString()}, ) {- val dbDataUnfiltered by viewModel.data<T>().collectAsState()+ val dbDataUnfiltered by viewModel.data<T>().collectAsState(listOf()) var searchQuery by remember { mutableStateOf("") } val dbData by remember { derivedStateOf { dbDataUnfiltered.filter { searchQuery.isBlank() || searchString(it).contains(searchQuery, true) } } }
library/src/main/java/com/vayunmathur/library/util/RoomViewModel.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/RoomViewModel.kt b/library/src/main/java/com/vayunmathur/library/util/RoomViewModel.ktindex 350c8cf8c1..066a9f3449 100644--- a/library/src/main/java/com/vayunmathur/library/util/RoomViewModel.kt+++ b/library/src/main/java/com/vayunmathur/library/util/RoomViewModel.kt@@ -16,25 +16,32 @@ import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.room.Delete+import androidx.room.InvalidationTracker import androidx.room.Query+import androidx.room.RawQuery import androidx.room.Room import androidx.room.RoomDatabase+import androidx.room.RoomRawQuery import androidx.room.Transaction import androidx.room.TypeConverter import androidx.room.Upsert import androidx.room.migration.Migration+import androidx.sqlite.db.SimpleSQLiteQuery+import androidx.sqlite.db.SupportSQLiteQuery import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext import kotlin.reflect.KClass import kotlin.time.Instant class DaoInterface<T: DatabaseItem>(val dao: TrueDao<T>, val viewModelScope: CoroutineScope) {- val data: StateFlow<List<T>> = dao.getAll().stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())- fun delete(t: T, andThen: (Int) -> Unit = {}) { viewModelScope.launch { val id = dao.delete(t)@@ -54,15 +61,9 @@ class DaoInterface<T: DatabaseItem>(val dao: TrueDao<T>, val viewModelScope: Cor dao.upsertAll(t) } }-- fun replaceAll(t: List<T>) {- viewModelScope.launch {- dao.replaceAll(t)- }- } } -class DatabaseViewModel(vararg daos: Pair<KClass<*>, TrueDao<*>>) : ViewModel() {+class DatabaseViewModel(val database: RoomDatabase, vararg daos: Pair<KClass<*>, TrueDao<*>>) : ViewModel() { val daoMap = daos.associate { it.first to DaoInterface(it.second, viewModelScope) }@@ -73,20 +74,16 @@ class DatabaseViewModel(vararg daos: Pair<KClass<*>, TrueDao<*>>) : ViewModel() return daoInterface as DaoInterface<E> } - inline fun <reified E: DatabaseItem> data(): StateFlow<List<E>> {- return getDaoInterface<E>().data- }- @Composable inline fun <reified E: DatabaseItem> get(id: Long, crossinline default: () -> E? = {null}): State<E> {- val data by getDaoInterface<E>().data.collectAsState()+ val data by data<E>().collectAsState(listOf()) val derived = remember { derivedStateOf { (data.firstOrNull { it.id == id } ?: default())!! } } return derived } @Composable inline fun <reified E: DatabaseItem> getNullable(id: Long): State<E?> {- val data by getDaoInterface<E>().data.collectAsState()+ val data by data<E>().collectAsState(listOf()) val derived = remember { derivedStateOf { (data.firstOrNull { it.id == id }) } } return derived }@@ -96,7 +93,8 @@ class DatabaseViewModel(vararg daos: Pair<KClass<*>, TrueDao<*>>) : ViewModel() } inline fun <reified E: DatabaseItem> replaceAll(items: List<E>) {- getDaoInterface<E>().replaceAll(items)+ database.openHelper.writableDatabase.delete(E::class.simpleName!!, null, null)+ upsertAll(items) } @Composable@@ -110,7 +108,7 @@ class DatabaseViewModel(vararg daos: Pair<KClass<*>, TrueDao<*>>) : ViewModel() var currentId by remember { mutableLongStateOf(initialId) } // 2. Observe the database state- val data by daoInterface.data.collectAsState()+ val data by data<E>().collectAsState(listOf()) // 3. Local state for immediate UI feedback val localState = remember { mutableStateOf<E?>(null) }@@ -147,6 +145,38 @@ class DatabaseViewModel(vararg daos: Pair<KClass<*>, TrueDao<*>>) : ViewModel() } } + val dataStateCache = mutableMapOf<KClass<*>, StateFlow<List<*>>>()++ @Suppress("UNCHECKED_CAST")+ inline fun <reified E : DatabaseItem> data(): StateFlow<List<E>> {+ return dataStateCache.getOrPut(E::class) {+ val tableName = E::class.simpleName!!++ callbackFlow<List<E>> {+ // 1. Create an observer for the specific table name+ val observer = object : InvalidationTracker.Observer(tableName) {+ override fun onInvalidated(tables: Set<String>) {+ // When the table changes, re-fetch the data+ launch { send(getAll<E>()) }+ }+ }++ database.invalidationTracker.addObserver(observer)++ // 2. Perform the initial fetch+ send(getAll<E>())++ // 3. Clean up the observer when the UI stops listening+ awaitClose { database.invalidationTracker.removeObserver(observer) }+ }.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())+ } as StateFlow<List<E>>+ }++ suspend inline fun <reified E : DatabaseItem> getAll(): List<E> {+ val tableName = E::class.simpleName!!+ return getDaoInterface<E>().dao.observeRaw(SimpleSQLiteQuery("SELECT * FROM $tableName"))+ }+ inline fun <reified E: DatabaseItem> upsert(t: E, noinline andThen: (Long) -> Unit = {}) { getDaoInterface<E>().upsert(t, andThen) }@@ -160,9 +190,11 @@ interface DatabaseItem { val id: Long } -abstract class ReorderableDatabaseItem<T: ReorderableDatabaseItem<T>>: DatabaseItem() {- abstract val position: Double- abstract fun withPosition(position: Double): T+fun DatabaseItem.isNew() = id == 0L++interface ReorderableDatabaseItem<T: ReorderableDatabaseItem<T>>: DatabaseItem {+ val position: Double+ fun withPosition(position: Double): T } interface TrueDao<T: DatabaseItem> {@@ -172,14 +204,8 @@ interface TrueDao<T: DatabaseItem> { suspend fun delete(value: T): Int @Upsert suspend fun upsertAll(t: List<T>)- @Transaction- suspend fun replaceAll(t: List<T>) {- deleteAll()- upsertAll(t)- }-- fun getAll(): Flow<List<T>>- suspend fun deleteAll()+ @RawQuery+ suspend fun observeRaw(query: SupportSQLiteQuery): List<T> } val databases: MutableMap<KClass<*>, RoomDatabase> = mutableMapOf()
maps/src/main/java/com/vayunmathur/maps/CountryMap.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/CountryMap.kt b/maps/src/main/java/com/vayunmathur/maps/CountryMap.ktindex cd1976ebe1..53a33e7b2b 100644--- a/maps/src/main/java/com/vayunmathur/maps/CountryMap.kt+++ b/maps/src/main/java/com/vayunmathur/maps/CountryMap.kt@@ -52,7 +52,7 @@ private fun extractRings(fgbGeom: FgbGeometry): List<List<Position>> { for (i in 0 until ends.length()) { // ends.get(i) is the number of vertices, but xy is [x, y] // so we multiply the vertex index by 2 to get the buffer index- val end = (ends.get(i) * 2).toInt()+ val end = (ends.get(i) * 2) val posList = mutableListOf<Position>() for (j in start until end step 2) { posList.add(Position(xy.get(j), xy.get(j + 1)))@@ -83,7 +83,7 @@ object CountryMap { // FlatGeobuf index size depends on the number of features and the branching factor if (header.indexNodeSize() > 0) { val featureCount = header.featuresCount()- val nodeSize = header.indexNodeSize().toInt()+ val nodeSize = header.indexNodeSize() // Calculate tree size manually var nodes = featureCount@@ -143,7 +143,7 @@ object CountryMap { // FlatGeobuf index size depends on the number of features and the branching factor if (header.indexNodeSize() > 0) { val featureCount = header.featuresCount()- val nodeSize = header.indexNodeSize().toInt()+ val nodeSize = header.indexNodeSize() // Calculate tree size manually var nodes = featureCount@@ -171,7 +171,7 @@ object CountryMap { if (properties["iso_3166_2"]?.jsonPrimitive?.content.equals(iso3166_2, ignoreCase = true)) { // Found it! Convert only this ONE feature to wololo GeoJSON- val skGeometry = fgbToSpatialK(fgbFeature.geometry(), fgbFeature.geometry().type().toInt())+ val skGeometry = fgbToSpatialK(fgbFeature.geometry(), fgbFeature.geometry().type()) return Feature1(skGeometry, properties) }
music/src/main/java/com/vayunmathur/music/MainActivity.kt
diff --git a/music/src/main/java/com/vayunmathur/music/MainActivity.kt b/music/src/main/java/com/vayunmathur/music/MainActivity.ktindex 8541e856d7..78c147a723 100644--- a/music/src/main/java/com/vayunmathur/music/MainActivity.kt+++ b/music/src/main/java/com/vayunmathur/music/MainActivity.kt@@ -29,7 +29,7 @@ class MainActivity : ComponentActivity() { super.onCreate(savedInstanceState) enableEdgeToEdge() val db = buildDatabase<MusicDatabase>()- val viewModel = DatabaseViewModel(Music::class to db.musicDao())+ val viewModel = DatabaseViewModel(db,Music::class to db.musicDao()) setContent { DynamicTheme { LaunchedEffect(Unit) {
music/src/main/java/com/vayunmathur/music/database/MusicDatabase.kt
diff --git a/music/src/main/java/com/vayunmathur/music/database/MusicDatabase.kt b/music/src/main/java/com/vayunmathur/music/database/MusicDatabase.ktindex c4cd84ce02..8f0b84ab05 100644--- a/music/src/main/java/com/vayunmathur/music/database/MusicDatabase.kt+++ b/music/src/main/java/com/vayunmathur/music/database/MusicDatabase.kt@@ -2,19 +2,11 @@ package com.vayunmathur.music.database import androidx.room.Dao import androidx.room.Database-import androidx.room.Query import androidx.room.RoomDatabase import com.vayunmathur.library.util.TrueDao-import kotlinx.coroutines.flow.Flow @Dao-interface MusicDao: TrueDao<Music> {- @Query("SELECT * FROM Music ORDER BY title ASC")- override fun getAll(): Flow<List<Music>>-- @Query("DELETE FROM Music")- override suspend fun deleteAll()-}+interface MusicDao: TrueDao<Music> @Database(entities = [Music::class], version = 1) abstract class MusicDatabase: RoomDatabase() {
notes/src/main/java/com/vayunmathur/notes/MainActivity.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/MainActivity.kt b/notes/src/main/java/com/vayunmathur/notes/MainActivity.ktindex d203865be1..586cf352c4 100644--- a/notes/src/main/java/com/vayunmathur/notes/MainActivity.kt+++ b/notes/src/main/java/com/vayunmathur/notes/MainActivity.kt@@ -15,7 +15,7 @@ import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.buildDatabase import com.vayunmathur.library.util.rememberNavBackStack import com.vayunmathur.notes.data.Note-import com.vayunmathur.notes.data.database.NoteDatabase+import com.vayunmathur.notes.data.NoteDatabase import com.vayunmathur.notes.ui.NotePage import com.vayunmathur.notes.ui.NotesListPage import kotlinx.serialization.Serializable@@ -27,7 +27,7 @@ class MainActivity : ComponentActivity() { val db = buildDatabase<NoteDatabase>(listOf(Migration(1, 2) { it.execSQL("ALTER TABLE Note ADD COLUMN position REAL NOT NULL DEFAULT 0.0") }))- val viewModel = DatabaseViewModel(Note::class to db.noteDao())+ val viewModel = DatabaseViewModel(db, Note::class to db.noteDao()) setContent { DynamicTheme { Navigation(viewModel)
notes/src/main/java/com/vayunmathur/notes/data/Note.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/data/Note.kt b/notes/src/main/java/com/vayunmathur/notes/data/Note.ktindex 6206623d4b..3cafcc5a87 100644--- a/notes/src/main/java/com/vayunmathur/notes/data/Note.kt+++ b/notes/src/main/java/com/vayunmathur/notes/data/Note.kt@@ -12,6 +12,6 @@ data class Note( val title: String, val content: String, override val position: Double = 0.0-): ReorderableDatabaseItem<Note>() {+): ReorderableDatabaseItem<Note> { override fun withPosition(position: Double) = copy(position = position) }\ No newline at end of file
notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/data/database/NoteDatabase.kt b/notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.ktsimilarity index 62%rename from notes/src/main/java/com/vayunmathur/notes/data/database/NoteDatabase.ktrename to notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.ktindex 3dad8ffdce..4958fc8f1f 100644--- a/notes/src/main/java/com/vayunmathur/notes/data/database/NoteDatabase.kt+++ b/notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.kt@@ -1,9 +1,14 @@-package com.vayunmathur.notes.data.database+package com.vayunmathur.notes.data +import androidx.room.Dao import androidx.room.Database import androidx.room.RoomDatabase+import com.vayunmathur.library.util.TrueDao import com.vayunmathur.notes.data.Note +@Dao+interface NoteDao: TrueDao<Note>+ @Database(entities = [Note::class], version = 2) abstract class NoteDatabase : RoomDatabase() { abstract fun noteDao(): NoteDao
notes/src/main/java/com/vayunmathur/notes/data/database/NoteDao.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/data/database/NoteDao.kt b/notes/src/main/java/com/vayunmathur/notes/data/database/NoteDao.ktdeleted file mode 100644index 29321510fc..0000000000--- a/notes/src/main/java/com/vayunmathur/notes/data/database/NoteDao.kt+++ /dev/null@@ -1,15 +0,0 @@-package com.vayunmathur.notes.data.database--import androidx.room.Dao-import androidx.room.Query-import com.vayunmathur.library.util.TrueDao-import com.vayunmathur.notes.data.Note-import kotlinx.coroutines.flow.Flow--@Dao-interface NoteDao: TrueDao<Note> {- @Query("SELECT * FROM Note ORDER BY position ASC")- override fun getAll(): Flow<List<Note>>- @Query("DELETE FROM Note")- override suspend fun deleteAll()-}
notes/src/main/java/com/vayunmathur/notes/intents/GetIntent.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/intents/GetIntent.kt b/notes/src/main/java/com/vayunmathur/notes/intents/GetIntent.ktindex 61e404872b..1c6536cb9e 100644--- a/notes/src/main/java/com/vayunmathur/notes/intents/GetIntent.kt+++ b/notes/src/main/java/com/vayunmathur/notes/intents/GetIntent.kt@@ -4,9 +4,10 @@ import android.app.Activity import android.content.Intent import android.os.Bundle import com.vayunmathur.library.util.AssistantIntent+import com.vayunmathur.library.util.DatabaseViewModel import com.vayunmathur.library.util.buildDatabase import com.vayunmathur.notes.data.Note-import com.vayunmathur.notes.data.database.NoteDatabase+import com.vayunmathur.notes.data.NoteDatabase import kotlinx.coroutines.flow.first import kotlinx.serialization.InternalSerializationApi import kotlinx.serialization.json.JsonObject@@ -17,6 +18,7 @@ class GetIntent: AssistantIntent<Unit, List<Note>>(serializer<Unit>(), serialize override suspend fun performCalculation(input: Unit): List<Note> { val db = buildDatabase<NoteDatabase>()- return db.noteDao().getAll().first()+ val viewModel = DatabaseViewModel(db, Note::class to db.noteDao())+ return viewModel.getAll() } }\ No newline at end of file
notes/src/main/java/com/vayunmathur/notes/intents/InsertIntent.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/intents/InsertIntent.kt b/notes/src/main/java/com/vayunmathur/notes/intents/InsertIntent.ktindex 473d89e0ff..5d32bc0815 100644--- a/notes/src/main/java/com/vayunmathur/notes/intents/InsertIntent.kt+++ b/notes/src/main/java/com/vayunmathur/notes/intents/InsertIntent.kt@@ -7,7 +7,7 @@ import com.vayunmathur.library.intents.notes.InsertNoteData import com.vayunmathur.library.util.AssistantIntent import com.vayunmathur.library.util.buildDatabase import com.vayunmathur.notes.data.Note-import com.vayunmathur.notes.data.database.NoteDatabase+import com.vayunmathur.notes.data.NoteDatabase import kotlinx.coroutines.flow.first import kotlinx.serialization.InternalSerializationApi import kotlinx.serialization.json.JsonObject
openassistant/schemas/com.vayunmathur.openassistant.data.database.MessageDatabase/5.json
diff --git a/openassistant/schemas/com.vayunmathur.openassistant.data.database.MessageDatabase/5.json b/openassistant/schemas/com.vayunmathur.openassistant.data.database.MessageDatabase/5.jsonindex 63dbc28390..392b11c25d 100644--- a/openassistant/schemas/com.vayunmathur.openassistant.data.database.MessageDatabase/5.json+++ b/openassistant/schemas/com.vayunmathur.openassistant.data.database.MessageDatabase/5.json@@ -2,11 +2,11 @@ "formatVersion": 1, "database": { "version": 5,- "identityHash": "3df67898f01262150a7b710dadf801ff",+ "identityHash": "f18779167ff0e30f8ecf68b4d2a320b3", "entities": [ { "tableName": "Message",- "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `conversationId` INTEGER NOT NULL, `role` TEXT NOT NULL, `textContent` TEXT NOT NULL, `displayContent` TEXT, `images` TEXT NOT NULL, `toolCallId` TEXT, `toolCalls` TEXT NOT NULL, `timestamp` INTEGER NOT NULL, `position` REAL NOT NULL, FOREIGN KEY(`conversationId`) REFERENCES `Conversation`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `conversationId` INTEGER NOT NULL, `role` TEXT NOT NULL, `textContent` TEXT NOT NULL, `displayContent` TEXT, `images` TEXT NOT NULL, `toolCallId` TEXT, `toolCalls` TEXT NOT NULL, `timestamp` INTEGER NOT NULL, FOREIGN KEY(`conversationId`) REFERENCES `Conversation`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", "fields": [ { "fieldPath": "id",@@ -59,12 +59,6 @@ "columnName": "timestamp", "affinity": "INTEGER", "notNull": true- },- {- "fieldPath": "position",- "columnName": "position",- "affinity": "REAL",- "notNull": true } ], "primaryKey": {@@ -100,7 +94,7 @@ }, { "tableName": "Conversation",- "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `title` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `position` REAL NOT NULL)",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `title` TEXT NOT NULL, `createdAt` INTEGER NOT NULL)", "fields": [ { "fieldPath": "id",@@ -119,12 +113,6 @@ "columnName": "createdAt", "affinity": "INTEGER", "notNull": true- },- {- "fieldPath": "position",- "columnName": "position",- "affinity": "REAL",- "notNull": true } ], "primaryKey": {@@ -137,7 +125,7 @@ ], "setupQueries": [ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",- "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '3df67898f01262150a7b710dadf801ff')"+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'f18779167ff0e30f8ecf68b4d2a320b3')" ] } }\ No newline at end of file
openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.ktindex ed4f06ee5d..f9dd979b17 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt@@ -28,9 +28,8 @@ class MainActivity : ComponentActivity() { super.onCreate(savedInstanceState) enableEdgeToEdge() - val database = buildDatabase<MessageDatabase>()- val viewModel =- DatabaseViewModel(Message::class to database.messageDao(), Conversation::class to database.conversationDao())+ val db = buildDatabase<MessageDatabase>()+ val viewModel = DatabaseViewModel(db, Message::class to db.messageDao(), Conversation::class to db.conversationDao()) val ds = DataStoreUtils.getInstance(this) intentLauncher = IntentLauncher(this)
openassistant/src/main/java/com/vayunmathur/openassistant/api/GrokApi.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/api/GrokApi.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/api/GrokApi.ktindex cba4c6ed7d..14e004d447 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/api/GrokApi.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/api/GrokApi.kt@@ -13,6 +13,7 @@ import io.ktor.http.HttpHeaders import io.ktor.http.contentType import io.ktor.http.isSuccess import io.ktor.serialization.kotlinx.json.json+import io.ktor.utils.io.readLine import io.ktor.utils.io.readUTF8Line import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow@@ -50,7 +51,7 @@ class GrokApi(private val apiKey: String) { val channel = response.bodyAsChannel() while (!channel.isClosedForRead) {- val line = channel.readUTF8Line()+ val line = channel.readLine() if (line?.startsWith("data: ") == true) { val jsonString = line.substring(6) if (jsonString != "[DONE]") {
openassistant/src/main/java/com/vayunmathur/openassistant/data/database/ConversationDao.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/data/database/ConversationDao.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/data/database/ConversationDao.ktdeleted file mode 100644index ac47453249..0000000000--- a/openassistant/src/main/java/com/vayunmathur/openassistant/data/database/ConversationDao.kt+++ /dev/null@@ -1,15 +0,0 @@-package com.vayunmathur.openassistant.data.database--import androidx.room.Dao-import androidx.room.Query-import com.vayunmathur.library.util.TrueDao-import com.vayunmathur.openassistant.data.Conversation-import kotlinx.coroutines.flow.Flow--@Dao-interface ConversationDao: TrueDao<Conversation> {- @Query("SELECT * FROM Conversation ORDER BY createdAt DESC")- override fun getAll(): Flow<List<Conversation>>- @Query("DELETE FROM Conversation")- override suspend fun deleteAll()-}
openassistant/src/main/java/com/vayunmathur/openassistant/data/database/MessageDao.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/data/database/MessageDao.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/data/database/MessageDao.ktdeleted file mode 100644index be86600fa5..0000000000--- a/openassistant/src/main/java/com/vayunmathur/openassistant/data/database/MessageDao.kt+++ /dev/null@@ -1,15 +0,0 @@-package com.vayunmathur.openassistant.data.database--import androidx.room.Dao-import androidx.room.Query-import com.vayunmathur.library.util.TrueDao-import com.vayunmathur.openassistant.data.Message-import kotlinx.coroutines.flow.Flow--@Dao-interface MessageDao: TrueDao<Message> {- @Query("SELECT * FROM Message ORDER BY timestamp ASC")- override fun getAll(): Flow<List<Message>>- @Query("DELETE FROM Message")- override suspend fun deleteAll()-}
openassistant/src/main/java/com/vayunmathur/openassistant/data/database/MessageDatabase.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/data/database/MessageDatabase.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/data/database/MessageDatabase.ktindex 6874d55790..df266fa836 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/data/database/MessageDatabase.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/data/database/MessageDatabase.kt@@ -1,11 +1,19 @@ package com.vayunmathur.openassistant.data.database +import androidx.room.Dao import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters+import com.vayunmathur.library.util.TrueDao import com.vayunmathur.openassistant.data.Conversation import com.vayunmathur.openassistant.data.Message +@Dao+interface ConversationDao: TrueDao<Conversation>++@Dao+interface MessageDao: TrueDao<Message>+ @TypeConverters(Converters::class) @Database(entities = [Message::class, Conversation::class], version = 5) abstract class MessageDatabase : RoomDatabase() {
openassistant/src/main/java/com/vayunmathur/openassistant/ui/ConversationScreen.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/ConversationScreen.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/ConversationScreen.ktindex 6fd8f649c3..d562a2329b 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/ConversationScreen.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/ConversationScreen.kt@@ -115,7 +115,7 @@ class ConversationWorker(appContext: Context, workerParams: WorkerParameters): C ds.setBoolean("isThinking", true) delay(500) val db = applicationContext.buildDatabase<MessageDatabase>()- val viewModel = DatabaseViewModel(Message::class to db.messageDao(), Conversation::class to db.conversationDao())+ val viewModel = DatabaseViewModel(db,Message::class to db.messageDao(), Conversation::class to db.conversationDao()) send(viewModel, ds, conversationID, userMessage, uris) ds.setBoolean("isThinking", false) return Result.success()
passwords/src/main/java/com/vayunmathur/passwords/MainActivity.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/MainActivity.kt b/passwords/src/main/java/com/vayunmathur/passwords/MainActivity.ktindex 20fa35288e..b03b27a31c 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/MainActivity.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/MainActivity.kt@@ -25,10 +25,10 @@ class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge()- val database = buildDatabase<PasswordDatabase>(listOf(Migration(1, 2) {+ val db = buildDatabase<PasswordDatabase>(listOf(Migration(1, 2) { it.execSQL("ALTER TABLE passwords ADD COLUMN position REAL NOT NULL DEFAULT 0.0") }))- val viewModel = DatabaseViewModel(Password::class to database.passwordDao())+ val viewModel = DatabaseViewModel(db,Password::class to db.passwordDao()) setContent { DynamicTheme { Navigation(viewModel)
passwords/src/main/java/com/vayunmathur/passwords/PasswordAutofillService.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/PasswordAutofillService.kt b/passwords/src/main/java/com/vayunmathur/passwords/PasswordAutofillService.ktindex a61860914a..71ad673d19 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/PasswordAutofillService.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/PasswordAutofillService.kt@@ -16,6 +16,7 @@ import android.view.autofill.AutofillId import android.view.autofill.AutofillValue import android.widget.RemoteViews import androidx.core.net.toUri+import com.vayunmathur.library.util.DatabaseViewModel import com.vayunmathur.library.util.buildDatabase import com.vayunmathur.passwords.data.PasswordDatabase import kotlinx.coroutines.flow.first@@ -23,7 +24,10 @@ import kotlinx.coroutines.runBlocking class PasswordAutofillService : AutofillService() { - private val db by lazy { applicationContext.buildDatabase<PasswordDatabase>() }+ private val viewModel by lazy {+ val db = applicationContext.buildDatabase<PasswordDatabase>()+ DatabaseViewModel(db, Password::class to db.passwordDao())+ } override fun onFillRequest(request: FillRequest, cancellationSignal: CancellationSignal, callback: FillCallback) { val parser = StructureParser(request.fillContexts)@@ -43,7 +47,7 @@ class PasswordAutofillService : AutofillService() { runBlocking { try { // 3. Fetch and Filter Passwords- val allPasswords = db.passwordDao().getAll().first()+ val allPasswords = viewModel.getAll<Password>() val matches = allPasswords.filter { pass -> pass.websites.any { site -> matchesContext(site, targetPackage, targetWebDomain) }@@ -98,13 +102,12 @@ class PasswordAutofillService : AutofillService() { if (!username.isNullOrBlank() && !password.isNullOrBlank()) { runBlocking {- val dao = db.passwordDao()- val existing = dao.getAll().first().firstOrNull { it.userId == username }+ val existing = viewModel.getAll<Password>().firstOrNull { it.userId == username } if (existing != null) {- dao.upsert(existing.copy(password = password))+ viewModel.upsert(existing.copy(password = password)) } else {- dao.upsert(+ viewModel.upsert( Password( name = "New Login", userId = username,
passwords/src/main/java/com/vayunmathur/passwords/data/PasswordDao.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/data/PasswordDao.kt b/passwords/src/main/java/com/vayunmathur/passwords/data/PasswordDao.ktdeleted file mode 100644index 85522ceebb..0000000000--- a/passwords/src/main/java/com/vayunmathur/passwords/data/PasswordDao.kt+++ /dev/null@@ -1,15 +0,0 @@-package com.vayunmathur.passwords.data--import androidx.room.Dao-import androidx.room.Query-import com.vayunmathur.library.util.TrueDao-import com.vayunmathur.passwords.Password-import kotlinx.coroutines.flow.Flow--@Dao-interface PasswordDao: TrueDao<Password> {- @Query("SELECT * FROM passwords ORDER BY name")- override fun getAll(): Flow<List<Password>>- @Query("DELETE FROM passwords")- override suspend fun deleteAll()-}
passwords/src/main/java/com/vayunmathur/passwords/data/PasswordDatabase.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/data/PasswordDatabase.kt b/passwords/src/main/java/com/vayunmathur/passwords/data/PasswordDatabase.ktindex 2dacb6ed38..3144b6ba07 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/data/PasswordDatabase.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/data/PasswordDatabase.kt@@ -1,10 +1,15 @@ package com.vayunmathur.passwords.data +import androidx.room.Dao import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters+import com.vayunmathur.library.util.TrueDao import com.vayunmathur.passwords.Password +@Dao+interface PasswordDao: TrueDao<Password>+ @Database(entities = [Password::class], version = 2) @TypeConverters(Converters::class) abstract class PasswordDatabase : RoomDatabase() {
passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordEditPage.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordEditPage.kt b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordEditPage.ktindex 9be94f907c..3d5f122fca 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordEditPage.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordEditPage.kt@@ -39,6 +39,7 @@ import com.vayunmathur.library.ui.IconClose import com.vayunmathur.library.ui.IconNavigation import com.vayunmathur.library.ui.IconSave import com.vayunmathur.library.util.DatabaseViewModel+import com.vayunmathur.library.util.isNew import com.vayunmathur.library.util.setLast import com.vayunmathur.passwords.Password import com.vayunmathur.passwords.Route
photos/schemas/com.vayunmathur.photos.data.PhotoDatabase/1.json
diff --git a/photos/schemas/com.vayunmathur.photos.data.PhotoDatabase/1.json b/photos/schemas/com.vayunmathur.photos.data.PhotoDatabase/1.jsonindex dfd026ae01..e8674cbb1c 100644--- a/photos/schemas/com.vayunmathur.photos.data.PhotoDatabase/1.json+++ b/photos/schemas/com.vayunmathur.photos.data.PhotoDatabase/1.json@@ -2,11 +2,11 @@ "formatVersion": 1, "database": { "version": 1,- "identityHash": "d8797eb490c4ac6ab35c015b82d611c9",+ "identityHash": "59f63f3c4bb06096d148596664d488c0", "entities": [ { "tableName": "Photo",- "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `uri` TEXT NOT NULL, `date` INTEGER NOT NULL, `width` INTEGER NOT NULL, `height` INTEGER NOT NULL, `exifSet` INTEGER NOT NULL, `lat` REAL, `long` REAL, `position` REAL NOT NULL, `duration` INTEGER)",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `uri` TEXT NOT NULL, `date` INTEGER NOT NULL, `width` INTEGER NOT NULL, `height` INTEGER NOT NULL, `exifSet` INTEGER NOT NULL, `lat` REAL, `long` REAL, `duration` INTEGER)", "fields": [ { "fieldPath": "id",@@ -60,12 +60,6 @@ "columnName": "long", "affinity": "REAL" },- {- "fieldPath": "position",- "columnName": "position",- "affinity": "REAL",- "notNull": true- }, { "fieldPath": "videoData.duration", "columnName": "duration",@@ -82,7 +76,7 @@ ], "setupQueries": [ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",- "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'd8797eb490c4ac6ab35c015b82d611c9')"+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '59f63f3c4bb06096d148596664d488c0')" ] } }\ No newline at end of file
photos/src/main/java/com/vayunmathur/photos/MainActivity.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/MainActivity.kt b/photos/src/main/java/com/vayunmathur/photos/MainActivity.ktindex 5749daca80..b47fcade19 100644--- a/photos/src/main/java/com/vayunmathur/photos/MainActivity.kt+++ b/photos/src/main/java/com/vayunmathur/photos/MainActivity.kt@@ -29,7 +29,7 @@ class MainActivity : ComponentActivity() { super.onCreate(savedInstanceState) enableEdgeToEdge() val db = buildDatabase<PhotoDatabase>()- val viewModel = DatabaseViewModel(Photo::class to db.noteDao())+ val viewModel = DatabaseViewModel(db, Photo::class to db.photoDao()) ImageLoader.init(this) setContent { DynamicTheme {
photos/src/main/java/com/vayunmathur/photos/data/PhotoDao.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDao.kt b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDao.ktdeleted file mode 100644index 0927fdf695..0000000000--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDao.kt+++ /dev/null@@ -1,14 +0,0 @@-package com.vayunmathur.photos.data--import androidx.room.Dao-import androidx.room.Query-import com.vayunmathur.library.util.TrueDao-import kotlinx.coroutines.flow.Flow--@Dao-interface PhotoDao: TrueDao<Photo> {- @Query("SELECT * FROM Photo ORDER BY position")- override fun getAll(): Flow<List<Photo>>- @Query("DELETE FROM Photo")- override suspend fun deleteAll()-}\ No newline at end of file
photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.ktindex 080e537a13..b0e0829a90 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt@@ -1,9 +1,14 @@ package com.vayunmathur.photos.data +import androidx.room.Dao import androidx.room.Database import androidx.room.RoomDatabase+import com.vayunmathur.library.util.TrueDao++@Dao+interface PhotoDao: TrueDao<Photo> @Database(entities = [Photo::class], version = 1) abstract class PhotoDatabase : RoomDatabase() {- abstract fun noteDao(): PhotoDao+ abstract fun photoDao(): PhotoDao }\ No newline at end of file
photos/src/main/java/com/vayunmathur/photos/glance/PhotoGlanceWidget.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/glance/PhotoGlanceWidget.kt b/photos/src/main/java/com/vayunmathur/photos/glance/PhotoGlanceWidget.ktindex b92dc24f82..b8b900299e 100644--- a/photos/src/main/java/com/vayunmathur/photos/glance/PhotoGlanceWidget.kt+++ b/photos/src/main/java/com/vayunmathur/photos/glance/PhotoGlanceWidget.kt@@ -36,7 +36,8 @@ class PhotoGlanceWidget : GlanceAppWidget() { override suspend fun provideGlance(context: Context, id: GlanceId) { val db = context.buildDatabase<PhotoDatabase>()- val photos = db.noteDao().getAll().first()+ val viewModel = DatabaseViewModel(db, Photo::class to db.photoDao())+ val photos = viewModel.getAll<Photo>() provideContent { var photo by remember(photos) { mutableStateOf(photos.filter{it.videoData == null}.randomOrNull()) }
youpipe/schemas/com.vayunmathur.youpipe.data.SubscriptionDatabase/1.json
diff --git a/youpipe/schemas/com.vayunmathur.youpipe.data.SubscriptionDatabase/1.json b/youpipe/schemas/com.vayunmathur.youpipe.data.SubscriptionDatabase/1.jsonindex 4a3b647a15..5e7f535951 100644--- a/youpipe/schemas/com.vayunmathur.youpipe.data.SubscriptionDatabase/1.json+++ b/youpipe/schemas/com.vayunmathur.youpipe.data.SubscriptionDatabase/1.json@@ -2,11 +2,11 @@ "formatVersion": 1, "database": { "version": 1,- "identityHash": "3df2a06f39a597270fb8c2f9e01fe93f",+ "identityHash": "151a91f97311262c9641653e38012bda", "entities": [ { "tableName": "Subscription",- "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `channelID` TEXT NOT NULL, `avatarURL` TEXT NOT NULL, `uploadsPlaylistID` TEXT NOT NULL, `position` REAL NOT NULL)",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `channelID` TEXT NOT NULL, `avatarURL` TEXT NOT NULL, `uploadsPlaylistID` TEXT NOT NULL)", "fields": [ { "fieldPath": "id",@@ -37,12 +37,6 @@ "columnName": "uploadsPlaylistID", "affinity": "TEXT", "notNull": true- },- {- "fieldPath": "position",- "columnName": "position",- "affinity": "REAL",- "notNull": true } ], "primaryKey": {@@ -54,7 +48,7 @@ }, { "tableName": "SubscriptionVideo",- "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `duration` INTEGER NOT NULL, `views` INTEGER NOT NULL, `uploadDate` INTEGER NOT NULL, `thumbnailURL` TEXT NOT NULL, `author` TEXT NOT NULL, `channelID` INTEGER NOT NULL, `position` REAL NOT NULL, FOREIGN KEY(`channelID`) REFERENCES `Subscription`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `duration` INTEGER NOT NULL, `views` INTEGER NOT NULL, `uploadDate` INTEGER NOT NULL, `thumbnailURL` TEXT NOT NULL, `author` TEXT NOT NULL, `channelID` INTEGER NOT NULL, FOREIGN KEY(`channelID`) REFERENCES `Subscription`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", "fields": [ { "fieldPath": "id",@@ -103,12 +97,6 @@ "columnName": "channelID", "affinity": "INTEGER", "notNull": true- },- {- "fieldPath": "position",- "columnName": "position",- "affinity": "REAL",- "notNull": true } ], "primaryKey": {@@ -144,7 +132,7 @@ }, { "tableName": "HistoryVideo",- "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `progress` INTEGER NOT NULL, `timestamp` INTEGER NOT NULL, `position` REAL NOT NULL, `name` TEXT NOT NULL, `videoID` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `views` INTEGER NOT NULL, `uploadDate` INTEGER NOT NULL, `thumbnailURL` TEXT NOT NULL, `author` TEXT NOT NULL)",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `progress` INTEGER NOT NULL, `timestamp` INTEGER NOT NULL, `name` TEXT NOT NULL, `videoID` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `views` INTEGER NOT NULL, `uploadDate` INTEGER NOT NULL, `thumbnailURL` TEXT NOT NULL, `author` TEXT NOT NULL)", "fields": [ { "fieldPath": "id",@@ -164,12 +152,6 @@ "affinity": "INTEGER", "notNull": true },- {- "fieldPath": "position",- "columnName": "position",- "affinity": "REAL",- "notNull": true- }, { "fieldPath": "videoItem.name", "columnName": "name",@@ -222,7 +204,7 @@ }, { "tableName": "SubscriptionCategory",- "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`subscriptionID` INTEGER NOT NULL, `category` TEXT NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `position` REAL NOT NULL, FOREIGN KEY(`subscriptionID`) REFERENCES `Subscription`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`subscriptionID` INTEGER NOT NULL, `category` TEXT NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, FOREIGN KEY(`subscriptionID`) REFERENCES `Subscription`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", "fields": [ { "fieldPath": "subscriptionID",@@ -241,12 +223,6 @@ "columnName": "id", "affinity": "INTEGER", "notNull": true- },- {- "fieldPath": "position",- "columnName": "position",- "affinity": "REAL",- "notNull": true } ], "primaryKey": {@@ -283,7 +259,7 @@ ], "setupQueries": [ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",- "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '3df2a06f39a597270fb8c2f9e01fe93f')"+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '151a91f97311262c9641653e38012bda')" ] } }\ No newline at end of file
youpipe/src/main/java/com/vayunmathur/youpipe/MainActivity.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/MainActivity.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/MainActivity.ktindex f559f54570..75269db322 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/MainActivity.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/MainActivity.kt@@ -79,7 +79,7 @@ class MainActivity : ComponentActivity() { super.onCreate(savedInstanceState) enableEdgeToEdge() val db = buildDatabase<SubscriptionDatabase>()- val viewModel = DatabaseViewModel(+ val viewModel = DatabaseViewModel(db, Subscription::class to db.subscriptionDao(), SubscriptionVideo::class to db.subscriptionVideoDao(), HistoryVideo::class to db.historyVideoDao(),
youpipe/src/main/java/com/vayunmathur/youpipe/data/HistoryVideo.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/History.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/HistoryVideo.ktsimilarity index 60%rename from youpipe/src/main/java/com/vayunmathur/youpipe/data/History.ktrename to youpipe/src/main/java/com/vayunmathur/youpipe/data/HistoryVideo.ktindex abf6432172..4959636ecc 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/data/History.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/HistoryVideo.kt@@ -1,16 +1,10 @@ package com.vayunmathur.youpipe.data -import androidx.room.Dao import androidx.room.Embedded import androidx.room.Entity import androidx.room.PrimaryKey-import androidx.room.Query import com.vayunmathur.library.util.DatabaseItem-import com.vayunmathur.library.util.TrueDao-import com.vayunmathur.youpipe.ui.VideoData import com.vayunmathur.youpipe.ui.VideoInfo-import com.vayunmathur.youpipe.videoURLtoID-import kotlinx.coroutines.flow.Flow import kotlin.time.Clock import kotlin.time.Instant @@ -24,12 +18,4 @@ data class HistoryVideo( companion object { fun fromVideoData(videoInfo: VideoInfo, progress: Long) = HistoryVideo(videoInfo.videoID, progress, videoInfo, Clock.System.now()) }-}--@Dao-interface HistoryVideoDao: TrueDao<HistoryVideo> {- @Query("SELECT * FROM HistoryVideo")- override fun getAll(): Flow<List<HistoryVideo>>- @Query("DELETE FROM HistoryVideo")- override suspend fun deleteAll() }\ No newline at end of file
youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionCategory.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionCategory.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionCategory.ktindex 1686aa1cc8..31b9ab4199 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionCategory.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionCategory.kt@@ -25,12 +25,6 @@ data class SubscriptionCategory( @Dao interface SubscriptionCategoryDao: TrueDao<SubscriptionCategory> {- @Query("SELECT * FROM SubscriptionCategory")- override fun getAll(): Flow<List<SubscriptionCategory>>-- @Query("DELETE FROM SubscriptionCategory")- override suspend fun deleteAll()- @Query("DELETE FROM SubscriptionCategory WHERE category = :categoryName") suspend fun deleteCategory(categoryName: String)
youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionDao.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionDao.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionDao.ktdeleted file mode 100644index f34ccf0be4..0000000000--- a/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionDao.kt+++ /dev/null@@ -1,14 +0,0 @@-package com.vayunmathur.youpipe.data--import androidx.room.Dao-import androidx.room.Query-import com.vayunmathur.library.util.TrueDao-import kotlinx.coroutines.flow.Flow--@Dao-interface SubscriptionDao: TrueDao<Subscription> {- @Query("SELECT * FROM Subscription")- override fun getAll(): Flow<List<Subscription>>- @Query("DELETE FROM Subscription")- override suspend fun deleteAll()-}\ No newline at end of file
youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionDatabase.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionDatabase.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionDatabase.ktindex b695ca3716..bb31cba604 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionDatabase.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionDatabase.kt@@ -1,9 +1,21 @@ package com.vayunmathur.youpipe.data +import androidx.room.Dao import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters import com.vayunmathur.library.util.DefaultConverters+import com.vayunmathur.library.util.TrueDao+++@Dao+interface HistoryVideoDao: TrueDao<HistoryVideo>++@Dao+interface SubscriptionDao: TrueDao<Subscription>++@Dao+interface SubscriptionVideoDao: TrueDao<SubscriptionVideo> @TypeConverters(DefaultConverters::class) @Database(entities = [Subscription::class, SubscriptionVideo::class, HistoryVideo::class, SubscriptionCategory::class], version = 1)
youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionVideo.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionVideoDao.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionVideo.ktsimilarity index 63%rename from youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionVideoDao.ktrename to youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionVideo.ktindex c76addc98c..7d52a1bcde 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionVideoDao.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionVideo.kt@@ -1,15 +1,10 @@ package com.vayunmathur.youpipe.data import androidx.room.ColumnInfo-import androidx.room.Dao import androidx.room.Entity import androidx.room.ForeignKey-import androidx.room.Index import androidx.room.PrimaryKey-import androidx.room.Query import com.vayunmathur.library.util.DatabaseItem-import com.vayunmathur.library.util.TrueDao-import kotlinx.coroutines.flow.Flow import kotlinx.serialization.Serializable import kotlin.time.Instant @@ -27,12 +22,4 @@ data class SubscriptionVideo( val author: String, @ColumnInfo(index = true) val channelID: Long-): DatabaseItem--@Dao-interface SubscriptionVideoDao: TrueDao<SubscriptionVideo> {- @Query("SELECT * FROM SubscriptionVideo ORDER BY position")- override fun getAll(): Flow<List<SubscriptionVideo>>- @Query("DELETE FROM SubscriptionVideo")- override suspend fun deleteAll()-}\ No newline at end of file+): DatabaseItem\ No newline at end of file
youpipe/src/main/java/com/vayunmathur/youpipe/ui/SubscriptionFetchTask.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/ui/SubscriptionFetchTask.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/ui/SubscriptionFetchTask.ktindex 7f67d65792..ed802c0c56 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/ui/SubscriptionFetchTask.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/ui/SubscriptionFetchTask.kt@@ -25,12 +25,13 @@ class SubscriptionFetchTask(context: Context, params: WorkerParameters) : Corout Log.d("SubscriptionFetchTask", "Starting...") return try { val db = applicationContext.buildDatabase<SubscriptionDatabase>()- val viewModel = DatabaseViewModel(+ val viewModel = DatabaseViewModel(db, Subscription::class to db.subscriptionDao(), SubscriptionVideo::class to db.subscriptionVideoDao() ) - val subscriptions = viewModel.getDaoInterface<Subscription>().dao.getAll().first()++ val subscriptions = viewModel.getAll<Subscription>() Log.d("SubscriptionFetchTask", "Fetched ${subscriptions.size} subscriptions") val videoIDs = getChannelVideos(subscriptions.map { it.toChannelInfo() })
youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPage.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPage.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPage.ktindex 2e5b0f0c31..c0c573a588 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPage.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPage.kt@@ -79,42 +79,11 @@ data class VideoStream(val url: String, val width: Int, val height: Int, val bit data class VideoData(val title: String, val views: Long, val duration: Long, val uploadDate: Instant, val thumbnailURL: String, val author: String, val authorURL: String, val authorThumbnail: String) data class Comment(val text: String, val author: String, val likes: Int, val dislikes: Int) -@Composable-fun RotatedComponent(- rotation: Float = 90f,- content: @Composable () -> Unit-) {- Layout(- content = content,- modifier = Modifier.rotate(rotation)- ) { measurables, constraints ->- // 1. Swap the constraints: MaxWidth becomes MaxHeight and vice versa- val swappedConstraints = constraints.copy(- minWidth = constraints.minHeight,- maxWidth = constraints.maxHeight,- minHeight = constraints.minWidth,- maxHeight = constraints.maxWidth- )-- // 2. Measure the child with the flipped constraints- val placeable = measurables.first().measure(swappedConstraints)-- // 3. Set the parent size to the FLIPPED dimensions of the child- layout(placeable.height, placeable.width) {- // 4. Place the child centered- placeable.placeRelative(- x = (placeable.height - placeable.width) / 2,- y = (placeable.width - placeable.height) / 2- )- }- }-}- @Composable fun LockScreenOrientation(orientation: Int) { val context = LocalContext.current DisposableEffect(orientation) {- val activity = context.findActivity() ?: return@DisposableEffect onDispose {}+ val activity = context.findActivity() val originalOrientation = activity.requestedOrientation activity.requestedOrientation = orientation