101 lines
2.3 KiB
Kotlin
Executable File
101 lines
2.3 KiB
Kotlin
Executable File
/*
|
|
* Created by sweetbread
|
|
* Copyright (c) 2025. All rights reserved.
|
|
*/
|
|
|
|
package ru.risdeveau.pixeldragon.db
|
|
|
|
import androidx.room.Dao
|
|
import androidx.room.Delete
|
|
import androidx.room.Embedded
|
|
import androidx.room.Entity
|
|
import androidx.room.Insert
|
|
import androidx.room.Junction
|
|
import androidx.room.OnConflictStrategy
|
|
import androidx.room.PrimaryKey
|
|
import androidx.room.Query
|
|
import androidx.room.Relation
|
|
import androidx.room.TypeConverters
|
|
import ru.risdeveau.pixeldragon.repo.Room
|
|
import ru.risdeveau.pixeldragon.repo.User
|
|
import java.time.Instant
|
|
|
|
@Entity(tableName = "room")
|
|
@TypeConverters(Converters::class)
|
|
data class RoomDB (
|
|
@PrimaryKey val id: String,
|
|
val updatedAt: Instant,
|
|
val name: String?,
|
|
val type: String,
|
|
val creatorId: String?,
|
|
val createTime: Long?,
|
|
val avatarUrl: String?,
|
|
val members: Int?,
|
|
val joined: Boolean,
|
|
val direct: String?
|
|
)
|
|
|
|
fun RoomDB.isExpired(cacheDuration: Long = 60 * 60): Boolean {
|
|
return Instant.now().minusSeconds(cacheDuration) > updatedAt
|
|
}
|
|
|
|
suspend fun RoomDB.toDomain(): Room = Room(
|
|
id = id,
|
|
name = name,
|
|
type = type,
|
|
creatorId = creatorId,
|
|
createTime = createTime,
|
|
avatarUrl = avatarUrl,
|
|
members = members,
|
|
joined = joined,
|
|
direct = direct?.let { User.getById(it) }
|
|
)
|
|
|
|
fun Room.toEntity(): RoomDB = RoomDB(
|
|
id = id,
|
|
updatedAt = Instant.now(),
|
|
name = name,
|
|
type = type,
|
|
creatorId = creatorId,
|
|
createTime = createTime,
|
|
avatarUrl = avatarUrl,
|
|
members = members,
|
|
joined = joined,
|
|
direct = direct?.id
|
|
)
|
|
|
|
|
|
@Dao
|
|
interface RoomDao {
|
|
@Query("SELECT * FROM room WHERE id LIKE :id LIMIT 1")
|
|
fun getById(id: String): RoomDB?
|
|
|
|
// @Transaction
|
|
// @Query("SELECT * FROM room WHERE ")
|
|
// fun getSpace(rid: String): Space
|
|
|
|
@Query("SELECT * FROM room WHERE joined = 1 AND id NOT IN (SELECT id FROM SpaceToRoom)")
|
|
fun getAllJoined(): List<RoomDB>
|
|
|
|
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
|
fun insert(vararg rooms: RoomDB)
|
|
|
|
@Delete
|
|
fun delete(room: RoomDB)
|
|
}
|
|
|
|
@Entity(primaryKeys = ["spaceId", "roomId"])
|
|
data class SpaceToRoom(
|
|
val spaceId: String,
|
|
val roomId: String
|
|
)
|
|
|
|
data class Space(
|
|
@Embedded val space: RoomDB,
|
|
@Relation(
|
|
parentColumn = "spaceId",
|
|
entityColumn = "roomId",
|
|
associateBy = Junction(SpaceToRoom::class)
|
|
)
|
|
val children: List<RoomDB>
|
|
) |