Per-library storage: switching the folder switches the library
Stats, likes and thumbnail artwork now belong to the open folder instead of one global store. - Library.id(context) is the identity: the picked SAF tree, else the default folder path - StatsDb opens stats-<12-hex>.db derived from that id (StatsStore, pure and unit tested), so a different folder has its own sessions, likes and export - exports are stats-<tag>.json and carry a "library" field - thumbnails live under filesDir/thumbs/<tag>/, so artwork never mixes between folders - MainActivity rebuilds its StatsDb when the library id changes; player and stats screen always open the current one - the single stats.db of earlier builds is copied once into the first library that opens, so the existing history and like survive; other folders start empty Built and tested locally only (21 unit tests, lint green) — the tablet still runs the previous build because the child was watching.
This commit is contained in:
1 parent
382bb2653c
commit
a43816a3ae
9 files changed
+139
-15
No files matched your search
@@ -87,7 +87,12 @@ Mandatory: from API 29 scoped storage forbids directory listing (the app uid get
|
||||
with the next episode; if the series is finished it starts another folder at
|
||||
its first episode.
|
||||
- `stats/StatsDb` — SQLite: `sessions` (plays, watched ms, per day) and `likes`.
|
||||
Mirrored to `getExternalFilesDir()/stats.json` for another process to pull.
|
||||
**One store per library**: the picked folder is the identity (`Library.id`), the
|
||||
file is `stats-<12-hex>.db` (`StatsStore`), thumbnails live under
|
||||
`filesDir/thumbs/<tag>/`, and the export is `stats-<tag>.json` with a `library`
|
||||
field. Switching the folder therefore switches stats, likes and artwork as if it
|
||||
were another library. The single `stats.db` of earlier builds is copied into the
|
||||
first library that opens, newer folders start empty.
|
||||
|
||||
## Pitfalls
|
||||
|
||||
|
||||
@@ -27,6 +27,13 @@ object Library {
|
||||
const val DEFAULT_FOLDER = "KidsTube"
|
||||
private const val KEY_TREE = "tree_uri"
|
||||
|
||||
/**
|
||||
* Identity of the currently open library. Switching the picked folder means
|
||||
* switching libraries: stats, likes and thumbnails are kept per id.
|
||||
*/
|
||||
fun id(context: Context): String =
|
||||
treeUri(context)?.toString() ?: defaultFolderPath()
|
||||
|
||||
fun treeUri(context: Context): Uri? =
|
||||
prefs(context).getString(KEY_TREE, null)?.let(Uri::parse)
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import android.util.Log
|
||||
import android.util.LruCache
|
||||
import dev.lotherk.kidstube.data.Library
|
||||
import dev.lotherk.kidstube.data.MediaItem
|
||||
import dev.lotherk.kidstube.stats.StatsStore
|
||||
import android.view.View
|
||||
import java.io.File
|
||||
import java.util.Locale
|
||||
@@ -158,8 +159,11 @@ object ThumbCache {
|
||||
return Bitmap.createScaledBitmap(source, width, height, true)
|
||||
}
|
||||
|
||||
private fun fileFor(context: Context, item: MediaItem): File =
|
||||
File(File(context.filesDir, "thumbs"), item.key + "_v2.jpg")
|
||||
private fun fileFor(context: Context, item: MediaItem): File {
|
||||
// One cache per library: switching the folder must not mix artwork.
|
||||
val libraryDir = File(File(context.filesDir, "thumbs"), StatsStore.libraryTag(Library.id(context)))
|
||||
return File(libraryDir, item.key + "_v2.jpg")
|
||||
}
|
||||
|
||||
private fun readDisk(context: Context, item: MediaItem): Bitmap? {
|
||||
val file = fileFor(context, item)
|
||||
|
||||
@@ -20,13 +20,35 @@ import java.util.Locale
|
||||
* is mirrored to a JSON file under the app's external files dir so another
|
||||
* process can read it with `adb pull`.
|
||||
*/
|
||||
class StatsDb(context: Context) :
|
||||
SQLiteOpenHelper(context.applicationContext, NAME, null, VERSION) {
|
||||
class StatsDb(context: Context, val libraryId: String) :
|
||||
SQLiteOpenHelper(context.applicationContext, StatsStore.dbNameFor(libraryId), null, VERSION) {
|
||||
|
||||
private val appContext: Context = context.applicationContext
|
||||
|
||||
init {
|
||||
// The single stats.db of earlier builds belongs to the first library that
|
||||
// opens after this change; every other folder starts empty.
|
||||
migrateLegacy(appContext)
|
||||
}
|
||||
|
||||
private fun migrateLegacy(ctx: Context) {
|
||||
try {
|
||||
val legacy = ctx.getDatabasePath("stats.db")
|
||||
val target = ctx.getDatabasePath(StatsStore.dbNameFor(libraryId))
|
||||
if (legacy.exists() && !target.exists()) {
|
||||
target.parentFile?.let { if (!it.exists()) it.mkdirs() }
|
||||
legacy.copyTo(target, overwrite = false)
|
||||
for (suffix in listOf("-wal", "-shm")) {
|
||||
val from = File(legacy.absolutePath + suffix)
|
||||
if (from.exists()) from.copyTo(File(target.absolutePath + suffix), overwrite = true)
|
||||
}
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
// A missing migration only costs the old history, never correctness.
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val NAME = "stats.db"
|
||||
private const val VERSION = 3
|
||||
private const val MIN_SESSION_MS = 1500L
|
||||
}
|
||||
@@ -238,6 +260,7 @@ class StatsDb(context: Context) :
|
||||
val totals = totals()
|
||||
val root = JSONObject().apply {
|
||||
put("updated_at", System.currentTimeMillis())
|
||||
put("library", libraryId)
|
||||
put("plays", totals[0])
|
||||
put("watched_ms", totals[1])
|
||||
put("videos", totals[2])
|
||||
@@ -257,7 +280,7 @@ class StatsDb(context: Context) :
|
||||
}
|
||||
})
|
||||
}
|
||||
File(dir, "stats.json").writeText(root.toString(2))
|
||||
File(dir, StatsStore.exportNameFor(libraryId)).writeText(root.toString(2))
|
||||
} catch (t: Throwable) {
|
||||
// Export is a convenience; the SQLite rows stay authoritative.
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package dev.lotherk.kidstube.stats
|
||||
|
||||
import java.security.MessageDigest
|
||||
|
||||
/**
|
||||
* Naming for the per-library store. One folder equals one library, so its
|
||||
* database file carries a hash of the library id instead of a shared name.
|
||||
*
|
||||
* Pure on purpose: the mapping is unit tested without Android.
|
||||
*/
|
||||
object StatsStore {
|
||||
|
||||
/** Short, filesystem-safe hash of a library id. */
|
||||
fun libraryTag(libraryId: String): String {
|
||||
val digest = MessageDigest.getInstance("SHA-1").digest(libraryId.toByteArray())
|
||||
val sb = StringBuilder(12)
|
||||
for (b in digest) {
|
||||
sb.append(String.format("%02x", b))
|
||||
if (sb.length >= 12) break
|
||||
}
|
||||
return sb.toString().take(12)
|
||||
}
|
||||
|
||||
fun dbNameFor(libraryId: String): String = "stats-" + libraryTag(libraryId) + ".db"
|
||||
|
||||
fun exportNameFor(libraryId: String): String = "stats-" + libraryTag(libraryId) + ".json"
|
||||
}
|
||||
@@ -30,7 +30,8 @@ class MainActivity : AppCompatActivity() {
|
||||
private lateinit var gridAdapter: VideoAdapter
|
||||
private lateinit var resultsAdapter: VideoAdapter
|
||||
private val executor = Executors.newSingleThreadExecutor()
|
||||
private lateinit var stats: StatsDb
|
||||
private var statsDb: StatsDb? = null
|
||||
private var statsLibrary: String? = null
|
||||
|
||||
private var all: List<MediaItem> = emptyList()
|
||||
private var folders: List<String> = emptyList()
|
||||
@@ -57,7 +58,6 @@ class MainActivity : AppCompatActivity() {
|
||||
super.onCreate(savedInstanceState)
|
||||
binding = ActivityMainBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
stats = StatsDb(this)
|
||||
|
||||
binding.grid.layoutManager = GridLayoutManager(this, columns())
|
||||
gridAdapter = VideoAdapter { openPlayer(it) }
|
||||
@@ -95,6 +95,20 @@ class MainActivity : AppCompatActivity() {
|
||||
start()
|
||||
}
|
||||
|
||||
/**
|
||||
* Stats and likes belong to the open library: picking another folder switches
|
||||
* to another store, as if it were a different library.
|
||||
*/
|
||||
private fun stats(): StatsDb {
|
||||
val id = Library.id(this)
|
||||
val existing = statsDb
|
||||
if (existing != null && statsLibrary == id) return existing
|
||||
val fresh = StatsDb(this, id)
|
||||
statsDb = fresh
|
||||
statsLibrary = id
|
||||
return fresh
|
||||
}
|
||||
|
||||
/** Always three across, so the overview reads as three rows of three. */
|
||||
private fun columns(): Int = 3
|
||||
|
||||
@@ -157,7 +171,7 @@ class MainActivity : AppCompatActivity() {
|
||||
buildChips(items)
|
||||
applyFolderFilter()
|
||||
if (activeTab == 1) applyFilter(binding.searchInput.text?.toString().orEmpty())
|
||||
if (activeTab == 2) resultsAdapter.submit(stats.likedItems(), stats.likedKeys())
|
||||
if (activeTab == 2) resultsAdapter.submit(stats().likedItems(), stats().likedKeys())
|
||||
refreshEmptyState()
|
||||
}
|
||||
}
|
||||
@@ -187,7 +201,7 @@ class MainActivity : AppCompatActivity() {
|
||||
// A single folder keeps its series order; "All" is shuffled so the child
|
||||
// does not walk through one series after the other.
|
||||
val list = if (folder == null) mixed else all.filter { it.folder == folder }
|
||||
gridAdapter.submit(list, stats.likedKeys())
|
||||
gridAdapter.submit(list, stats().likedKeys())
|
||||
refreshEmptyState()
|
||||
}
|
||||
|
||||
@@ -196,7 +210,7 @@ class MainActivity : AppCompatActivity() {
|
||||
val list = if (q.isEmpty()) all else all.filter {
|
||||
it.title.lowercase().contains(q) || it.folder.lowercase().contains(q)
|
||||
}
|
||||
resultsAdapter.submit(list, stats.likedKeys())
|
||||
resultsAdapter.submit(list, stats().likedKeys())
|
||||
}
|
||||
|
||||
private fun selectTab(index: Int) {
|
||||
@@ -222,7 +236,7 @@ class MainActivity : AppCompatActivity() {
|
||||
if (index != 1) binding.searchInput.setText("")
|
||||
when (index) {
|
||||
1 -> binding.searchInput.requestFocus()
|
||||
2 -> resultsAdapter.submit(stats.likedItems(), stats.likedKeys())
|
||||
2 -> resultsAdapter.submit(stats().likedItems(), stats().likedKeys())
|
||||
}
|
||||
refreshEmptyState()
|
||||
binding.grid.post { layoutTiles() }
|
||||
|
||||
@@ -66,7 +66,7 @@ class PlayerActivity : AppCompatActivity() {
|
||||
return
|
||||
}
|
||||
|
||||
stats = StatsDb(this)
|
||||
stats = StatsDb(this, Library.id(this))
|
||||
item = MediaItem(
|
||||
uri = Uri.parse(rawUri),
|
||||
title = intent.getStringExtra(EXTRA_TITLE).orEmpty(),
|
||||
|
||||
@@ -6,6 +6,7 @@ import android.widget.TextView
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.core.content.ContextCompat
|
||||
import dev.lotherk.kidstube.R
|
||||
import dev.lotherk.kidstube.data.Library
|
||||
import dev.lotherk.kidstube.databinding.ActivityStatsBinding
|
||||
import dev.lotherk.kidstube.stats.StatsDb
|
||||
import java.io.File
|
||||
@@ -20,7 +21,7 @@ class StatsActivity : AppCompatActivity() {
|
||||
super.onCreate(savedInstanceState)
|
||||
binding = ActivityStatsBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
stats = StatsDb(this)
|
||||
stats = StatsDb(this, Library.id(this))
|
||||
|
||||
val totals = stats.totals()
|
||||
binding.statPlays.text = totals[0].toString()
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package dev.lotherk.kidstube.stats
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class StatsStoreTest {
|
||||
|
||||
private val folder = "/storage/emulated/0/Movies/KidsTube"
|
||||
private val tree = "content://com.android.externalstorage.documents/tree/primary%3AMovies%2FOther"
|
||||
|
||||
@Test
|
||||
fun libraryTag_isStableWithinASession() {
|
||||
assertEquals(StatsStore.libraryTag(folder), StatsStore.libraryTag(folder))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun libraryTag_differsPerFolder() {
|
||||
assertNotEquals(StatsStore.libraryTag(folder), StatsStore.libraryTag(tree))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun libraryTag_isTwelveHexCharacters() {
|
||||
val tag = StatsStore.libraryTag(folder)
|
||||
assertEquals(12, tag.length)
|
||||
assertTrue(tag.all { it in "0123456789abcdef" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dbName_carriesTheTagAndStaysAscii() {
|
||||
val name = StatsStore.dbNameFor(folder)
|
||||
assertEquals("stats-" + StatsStore.libraryTag(folder) + ".db", name)
|
||||
assertTrue(name.all { it.code < 128 })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun twoFoldersNeverShareFiles() {
|
||||
assertNotEquals(StatsStore.dbNameFor(folder), StatsStore.dbNameFor(tree))
|
||||
assertNotEquals(StatsStore.exportNameFor(folder), StatsStore.exportNameFor(tree))
|
||||
assertNotEquals(StatsStore.dbNameFor(folder), StatsStore.exportNameFor(folder))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user