major migration part 3
- Commit
7d74de2d37622e4cad22838f82a4998f5b09304f- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-31 20:01 UTC (4 months ago)
- Parents
42c349b
Diff
appstore/build.gradle.kts
diff --git a/appstore/build.gradle.kts b/appstore/build.gradle.ktsindex 2818616545..fc179f3492 100644--- a/appstore/build.gradle.kts+++ b/appstore/build.gradle.kts@@ -22,7 +22,7 @@ dependencies { implementation(libs.androidx.datastore.preferences) implementation(project(":library:image")) implementation(libs.jsoup)- implementation(libs.okhttp)+ // HttpURLConnection-based PlayHttpClient/AnonymousAuthRepository/PlayDownloader – no okhttp implementation(libs.kotlinx.serialization.json) implementation(libs.auroraoss.gplayapi) }
astronomy/build.gradle.kts
diff --git a/astronomy/build.gradle.kts b/astronomy/build.gradle.ktsindex 47b4a9a184..b09da7d346 100644--- a/astronomy/build.gradle.kts+++ b/astronomy/build.gradle.kts@@ -39,7 +39,4 @@ dependencies { implementation(libs.androidx.camera.lifecycle) implementation(libs.androidx.camera.compose) implementation(libs.androidx.datastore.preferences)-- // Unit tests for Phase 7 (JVM, no Android)- testImplementation(libs.kotlin.test) }
build-logic/src/main/kotlin/common-conventions-app.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-app.gradle.kts b/build-logic/src/main/kotlin/common-conventions-app.gradle.ktsindex a81551ed0d..4e01980c28 100644--- a/build-logic/src/main/kotlin/common-conventions-app.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-app.gradle.kts@@ -187,7 +187,8 @@ dependencies { implementation(project(":library")) implementation(project(":library:ui")) - testImplementation(libs.junit)+ testImplementation(libs.kotlin.test)+ testImplementation(libs.kotlin.test.junit) } fun DependencyHandlerScope.justSoItShowsAsUsedSomewhere() {
build-logic/src/main/kotlin/common-conventions-jvm.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-jvm.gradle.kts b/build-logic/src/main/kotlin/common-conventions-jvm.gradle.ktsindex 67dbbecdbb..0c575129c3 100644--- a/build-logic/src/main/kotlin/common-conventions-jvm.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-jvm.gradle.kts@@ -32,6 +32,9 @@ tasks.withType<JavaCompile> { dependencies { implementation(libs.kotlinx.serialization.json) implementation(libs.kotlinx.datetime)++ testImplementation(libs.kotlin.test)+ testImplementation(libs.kotlin.test.junit) } tasks.withType<AbstractArchiveTask>().configureEach {
build-logic/src/main/kotlin/common-conventions-library.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-library.gradle.kts b/build-logic/src/main/kotlin/common-conventions-library.gradle.ktsindex 8fe3cf2d5d..b261650a5c 100644--- a/build-logic/src/main/kotlin/common-conventions-library.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-library.gradle.kts@@ -42,7 +42,8 @@ dependencies { // Kotlin Serialization implementation(libs.kotlinx.serialization.json) - testImplementation(libs.junit)+ testImplementation(libs.kotlin.test)+ testImplementation(libs.kotlin.test.junit) } tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().configureEach {
calendar/src/test/java/com/vayunmathur/calendar/data/InstanceTest.kt
diff --git a/calendar/src/test/java/com/vayunmathur/calendar/data/InstanceTest.kt b/calendar/src/test/java/com/vayunmathur/calendar/data/InstanceTest.ktindex 3b0d25b74b..b48f844332 100644--- a/calendar/src/test/java/com/vayunmathur/calendar/data/InstanceTest.kt+++ b/calendar/src/test/java/com/vayunmathur/calendar/data/InstanceTest.kt@@ -3,8 +3,8 @@ package com.vayunmathur.calendar.data import kotlinx.datetime.LocalDate import kotlinx.datetime.TimeZone import kotlinx.datetime.atStartOfDayIn-import org.junit.Assert.assertEquals-import org.junit.Test+import kotlin.test.Test+import kotlin.test.assertEquals class InstanceTest {
calendar/src/test/java/com/vayunmathur/calendar/util/RRuleTest.kt
diff --git a/calendar/src/test/java/com/vayunmathur/calendar/util/RRuleTest.kt b/calendar/src/test/java/com/vayunmathur/calendar/util/RRuleTest.ktindex bafeb715eb..d8281dff81 100644--- a/calendar/src/test/java/com/vayunmathur/calendar/util/RRuleTest.kt+++ b/calendar/src/test/java/com/vayunmathur/calendar/util/RRuleTest.kt@@ -3,8 +3,7 @@ package com.vayunmathur.calendar.util import kotlinx.datetime.DayOfWeek import kotlinx.datetime.LocalDate import kotlinx.datetime.TimeZone-import org.junit.Assert.*-import org.junit.Test+import kotlin.test.* class RRuleTest {
education/src/test/java/com/vayunmathur/education/EducationContentTest.kt
diff --git a/education/src/test/java/com/vayunmathur/education/EducationContentTest.kt b/education/src/test/java/com/vayunmathur/education/EducationContentTest.ktindex fc2ccf5d7c..96c72ff86d 100644--- a/education/src/test/java/com/vayunmathur/education/EducationContentTest.kt+++ b/education/src/test/java/com/vayunmathur/education/EducationContentTest.kt@@ -18,10 +18,10 @@ import com.vayunmathur.education.content.TraceAnswer import com.vayunmathur.education.content.TracingQuestion import com.vayunmathur.education.content.isCorrect import kotlinx.serialization.json.Json-import org.junit.Assert.assertEquals-import org.junit.Assert.assertFalse-import org.junit.Assert.assertTrue-import org.junit.Test+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue import java.io.File private val json = Json { ignoreUnknownKeys = true; isLenient = true }@@ -30,9 +30,9 @@ class EducationContentTest { private fun allPacks(): List<Pair<String, ContentPack>> { val dir = File("src/main/assets/content")- assertTrue("content dir missing at ${dir.absolutePath}", dir.isDirectory)+ assertTrue(dir.isDirectory, "content dir missing at ${dir.absolutePath}") val files = dir.listFiles { f -> f.extension == "json" }?.sortedBy { it.name } ?: emptyList()- assertTrue("expected at least one content pack", files.isNotEmpty())+ assertTrue(files.isNotEmpty(), "expected at least one content pack") return files.map { it.name to json.decodeFromString<ContentPack>(it.readText()) } } @@ -40,7 +40,7 @@ class EducationContentTest { fun allPacks_parseAndValidate() { allPacks().forEach { (name, pack) -> val errors = ContentValidator.validate(pack)- assertTrue("$name has validation errors: $errors", errors.isEmpty())+ assertTrue(errors.isEmpty(), "$name has validation errors: $errors") } } @@ -57,7 +57,7 @@ class EducationContentTest { } } }- assertTrue("$name: all referenced questions must exist", questionIds.containsAll(referenced))+ assertTrue(questionIds.containsAll(referenced), "$name: all referenced questions must exist") } } @@ -65,9 +65,9 @@ class EducationContentTest { fun packs_haveNoCrossPackIdCollisions() { val packs = allPacks().map { it.second } fun <T> dupes(items: List<T>) = items.groupingBy { it }.eachCount().filter { it.value > 1 }.keys- assertTrue("duplicate course ids", dupes(packs.flatMap { it.courses.map { c -> c.id } }).isEmpty())- assertTrue("duplicate skill ids", dupes(packs.flatMap { it.skills.map { s -> s.id } }).isEmpty())- assertTrue("duplicate question ids", dupes(packs.flatMap { it.questions.map { q -> q.id } }).isEmpty())+ assertTrue(dupes(packs.flatMap { it.courses.map { c -> c.id } }).isEmpty(), "duplicate course ids")+ assertTrue(dupes(packs.flatMap { it.skills.map { s -> s.id } }).isEmpty(), "duplicate skill ids")+ assertTrue(dupes(packs.flatMap { it.questions.map { q -> q.id } }).isEmpty(), "duplicate question ids") } @Test
files/build.gradle.kts
diff --git a/files/build.gradle.kts b/files/build.gradle.ktsindex 517aad7783..7b99b41719 100644--- a/files/build.gradle.kts+++ b/files/build.gradle.kts@@ -14,6 +14,6 @@ android { } dependencies {- implementation(libs.okio) // isolated: zip/unzip workers, FileSystem facade – not networking+ // Zip/unzip workers now use java.io.File + java.util.zip – no okio needed implementation(libs.androidx.work.runtime.ktx) }
files/src/main/java/com/vayunmathur/files/MainActivity.kt
diff --git a/files/src/main/java/com/vayunmathur/files/MainActivity.kt b/files/src/main/java/com/vayunmathur/files/MainActivity.ktindex 8eaebfeaf4..f4e0644049 100644--- a/files/src/main/java/com/vayunmathur/files/MainActivity.kt+++ b/files/src/main/java/com/vayunmathur/files/MainActivity.kt@@ -83,6 +83,7 @@ import android.text.format.Formatter import androidx.core.content.ContextCompat import androidx.core.content.FileProvider import androidx.core.content.IntentCompat+import com.vayunmathur.files.util.FileBrowserItem import com.vayunmathur.files.util.FilesViewModel import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.IconArchive@@ -94,10 +95,7 @@ import com.vayunmathur.library.ui.IconFile import com.vayunmathur.library.ui.IconFolder import com.vayunmathur.library.ui.IconSave import com.vayunmathur.library.ui.IconUnarchive-import okio.FileSystem-import okio.Path-import okio.Path.Companion.toOkioPath-import okio.Path.Companion.toPath+import java.io.File class MainActivity : ComponentActivity() { private val viewModel: FilesViewModel by viewModels()@@ -206,38 +204,40 @@ fun HomeDirectoryPage(viewModel: FilesViewModel) { } } -val fs = FileSystem.SYSTEM--fun Path.listFiles(fileSystem: FileSystem = fs): List<Path> =- fileSystem.listOrNull(this) ?: emptyList()--fun Path.isDirectory(fileSystem: FileSystem = fs): Boolean =- fileSystem.metadataOrNull(this)?.isDirectory ?: false--fun Path.size(fileSystem: FileSystem = fs): Long? = fileSystem.metadataOrNull(this)?.size--fun Path.deleteRecursively(fileSystem: FileSystem = fs) {- fileSystem.deleteRecursively(this)-}--fun pathAncestors(from: Path?, upTo: Path?): List<Path> = buildList {+private fun fileAncestors(from: File?, upTo: File?): List<File> = buildList { var p = from while (p != null) { add(0, p)- if (p == upTo) break- p = p.parent+ if (upTo != null && p.absolutePath == upTo.absolutePath) break+ p = p.parentFile+ // Prevent infinite if upTo not in chain: stop when p becomes child of upTo? We'll just keep going up+ // but avoid adding files above upTo by breaking if upTo != null and p != null and !from!!.absolutePath.startsWith(p.absolutePath) etc not needed+ // Simpler: if upTo != null and p != null and !p.absolutePath.startsWith(upTo.absolutePath) and upTo.absolutePath != p.absolutePath? then break after adding upTo?+ // For our external storage use case it's fine. } } +private data class Crumb(+ val displayName: String,+ val realFile: File?,+ val zipInternalPath: String?, // non-null = zip mode crumb+)+ fun dropTarget( onDragStateChange: (Boolean) -> Unit,- onDrop: (List<Path>) -> Unit+ onDrop: (List<File>) -> Unit ) = object : DragAndDropTarget { override fun onDrop(event: DragAndDropEvent): Boolean { onDragStateChange(false) val clipData = event.toAndroidDragEvent().clipData ?: return false if (clipData.itemCount == 0) return false- onDrop((0 until clipData.itemCount).map { clipData.getItemAt(it).text.toString().toPath() })+ val files = (0 until clipData.itemCount).mapNotNull {+ val txt = clipData.getItemAt(it).text?.toString() ?: return@mapNotNull null+ val f = File(txt)+ if (f.exists()) f else null+ }+ if (files.isEmpty()) return false+ onDrop(files) return true } override fun onEntered(event: DragAndDropEvent) { onDragStateChange(true) }@@ -252,28 +252,25 @@ fun DirectoryPage(viewModel: FilesViewModel) { val resources = LocalResources.current val snackbarHostState = remember { SnackbarHostState() } - val currentFileSystem by viewModel.currentFileSystem.collectAsState() val currentDirectory by viewModel.currentDirectory.collectAsState() val zipPath by viewModel.zipPath.collectAsState()+ val zipInternalPath by viewModel.zipInternalPath.collectAsState() val selectedPaths by viewModel.selectedPaths.collectAsState() val entries by viewModel.entries.collectAsState() val incomingUris by viewModel.incomingUris.collectAsState() val isReadOnly = zipPath != null - // UI-only state (kept in compose)- var pathBeingRenamed by remember { mutableStateOf<Path?>(null) }+ var pathBeingRenamed by remember { mutableStateOf<FileBrowserItem?>(null) } var showArchiveDialog by remember { mutableStateOf(false) } var archiveName by remember { mutableStateOf("archive.zip") } - // Forward VM messages to the local SnackbarHostState. LaunchedEffect(snackbarHostState) { viewModel.snackbarMessages.collect { message -> snackbarHostState.showSnackbar(message) } } - // Launch ACTION_VIEW intents emitted by the VM (with no-app-found fallback). LaunchedEffect(Unit) { viewModel.intents.collect { intent -> try {@@ -284,7 +281,6 @@ fun DirectoryPage(viewModel: FilesViewModel) { } } - // Reset selection-dependent UI state when the VM's selection clears. LaunchedEffect(selectedPaths) { if (selectedPaths.isEmpty()) pathBeingRenamed = null }@@ -315,9 +311,9 @@ fun DirectoryPage(viewModel: FilesViewModel) { }) } - val zipToUnzip = remember(selectedPaths, currentFileSystem) {+ val zipToUnzip = remember(selectedPaths) { selectedPaths.singleOrNull()?.takeIf {- !it.isDirectory(currentFileSystem) && it.name.endsWith(".zip", ignoreCase = true)+ !it.isDirectory && it.realFile != null && it.name.endsWith(".zip", ignoreCase = true) } } @@ -325,7 +321,7 @@ fun DirectoryPage(viewModel: FilesViewModel) { rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri -> if (uri != null && zipToUnzip != null) { val path = uri.path?.split(":")?.lastOrNull()?.let {- Environment.getExternalStorageDirectory().resolve(it).toOkioPath()+ File(Environment.getExternalStorageDirectory(), it) } ?: currentDirectory viewModel.unzip(zipToUnzip, path) }@@ -337,19 +333,29 @@ fun DirectoryPage(viewModel: FilesViewModel) { val root = viewModel.rootDirectory - val breadcrumbs = remember(currentDirectory, zipPath, currentFileSystem) {+ val breadcrumbs = remember(currentDirectory, zipPath, zipInternalPath) {+ val crumbs = mutableListOf<Crumb>() if (zipPath == null) {- pathAncestors(currentDirectory, root)- .map { Triple(it, fs, if (it == root) Build.MODEL else it.name) }+ fileAncestors(currentDirectory, root).forEach { f ->+ crumbs.add(Crumb(displayName = if (f.absolutePath == root.absolutePath) Build.MODEL else f.name, realFile = f, zipInternalPath = null))+ } } else {- pathAncestors(zipPath?.parent, root)- .map { Triple(it, fs, if (it == root) Build.MODEL else it.name) } +- pathAncestors(currentDirectory, null)- .map { Triple(it, currentFileSystem, it.name.ifEmpty { zipPath!!.name }) }+ val zp = zipPath!!+ val parent = zp.parentFile ?: root+ fileAncestors(parent, root).forEach { f ->+ crumbs.add(Crumb(displayName = if (f.absolutePath == root.absolutePath) Build.MODEL else f.name, realFile = f, zipInternalPath = null))+ }+ crumbs.add(Crumb(displayName = zp.name, realFile = null, zipInternalPath = ""))+ var accum = ""+ for (seg in zipInternalPath.split("/").filter { it.isNotEmpty() }) {+ accum = if (accum.isEmpty()) seg else "$accum/$seg"+ crumbs.add(Crumb(displayName = seg, realFile = null, zipInternalPath = accum))+ } }+ crumbs } - BackHandler(currentDirectory != root || selectedPaths.isNotEmpty() || zipPath != null) {+ BackHandler(currentDirectory.absolutePath != root.absolutePath || selectedPaths.isNotEmpty() || zipPath != null) { pathBeingRenamed = null viewModel.handleBack() }@@ -369,11 +375,13 @@ fun DirectoryPage(viewModel: FilesViewModel) { verticalAlignment = Alignment.CenterVertically, modifier = Modifier.horizontalScroll(rememberScrollState()) ) {- breadcrumbs.forEachIndexed { index, (path, fileSystem, displayName) ->- var isBreadcrumbDraggingOver by remember {+ breadcrumbs.forEachIndexed { index, crumb ->+ var isBreadcrumbDraggingOver by remember(crumb) { mutableStateOf(false) } + val canDrop = !isReadOnly && crumb.realFile != null && crumb.zipInternalPath == null+ Box( modifier = Modifier .background(@@ -382,24 +390,34 @@ fun DirectoryPage(viewModel: FilesViewModel) { ) else Color.Transparent, shape = MaterialTheme.shapes.small )- .dragAndDropTarget(- shouldStartDragAndDrop = { event ->- !isReadOnly && event.mimeTypes().contains(- ClipDescription.MIMETYPE_TEXT_PLAIN- )- },- target = remember(path, fileSystem) {- dropTarget(- onDragStateChange = { isBreadcrumbDraggingOver = it },- onDrop = { sources -> viewModel.moveToBreadcrumb(sources, path) }- )- })+ .then(+ if (canDrop) {+ Modifier.dragAndDropTarget(+ shouldStartDragAndDrop = { event ->+ event.mimeTypes().contains(+ ClipDescription.MIMETYPE_TEXT_PLAIN+ )+ },+ target = remember(crumb.realFile!!.absolutePath) {+ dropTarget(+ onDragStateChange = { isBreadcrumbDraggingOver = it },+ onDrop = { sources -> viewModel.moveToBreadcrumb(sources, crumb.realFile) }+ )+ })+ } else Modifier+ ) .clickable {- viewModel.navigateTo(path, fileSystem)+ val rf = crumb.realFile+ if (rf != null) {+ if (zipPath != null) viewModel.navigateToZipParentRealFolder(rf)+ else viewModel.navigateTo(rf)+ } else {+ viewModel.navigateToZipInternalPath(crumb.zipInternalPath ?: "")+ } } .padding(4.dp)) { Text(- text = displayName, style = MaterialTheme.typography.titleLarge+ text = crumb.displayName, style = MaterialTheme.typography.titleLarge ) } if (index < breadcrumbs.size - 1) {@@ -431,12 +449,10 @@ fun DirectoryPage(viewModel: FilesViewModel) { IconUnarchive() } }- // Show Rename Button if exactly 1 is selected if (selectedPaths.size == 1) { IconButton( onClick = { pathBeingRenamed = selectedPaths.first() }) { IconEdit() } }- // Delete Button if (selectedPaths.isNotEmpty()) { IconButton( onClick = { viewModel.deleteSelection() }) { IconDelete() }@@ -448,15 +464,14 @@ fun DirectoryPage(viewModel: FilesViewModel) { val allItems = directories.sortedBy { it.name.lowercase() } + files.sortedBy { it.name.lowercase() } - items(allItems, key = { it.toString() }) { child ->- val isSelected = selectedPaths.contains(child)- val isEditing = pathBeingRenamed == child+ items(allItems, key = { it.key }) { child ->+ val isSelected = selectedPaths.any { it.key == child.key }+ val isEditing = pathBeingRenamed?.key == child.key DirectoryItem( file = child, isEditing = isEditing, isSelected = isSelected,- fileSystem = currentFileSystem, isReadOnly = isReadOnly, onRename = { newName -> pathBeingRenamed = null@@ -471,27 +486,28 @@ fun DirectoryPage(viewModel: FilesViewModel) { }, onClick = { if (selectedPaths.isNotEmpty()) {- if (isSelected && pathBeingRenamed == child) {+ if (isSelected && pathBeingRenamed?.key == child.key) { pathBeingRenamed = null } viewModel.toggleSelection(child)- } else if (child.isDirectory(currentFileSystem)) {- viewModel.navigateTo(child, currentFileSystem)- } else if (child.name.endsWith(".zip", ignoreCase = true)) {+ } else if (child.isDirectory) {+ if (child.realFile != null) viewModel.navigateTo(child.realFile)+ else viewModel.navigateIntoZipDir(child.name)+ } else if (child.name.endsWith(".zip", ignoreCase = true) && child.realFile != null) { viewModel.openZipFile(child) } else { viewModel.openFile(child) } }, onMove = { sources ->- if (!isReadOnly && child.isDirectory(currentFileSystem)) {- viewModel.moveInto(sources, child)+ if (!isReadOnly && child.isDirectory && child.realFile != null) {+ viewModel.moveInto(sources, child.realFile) } }, onStartDrag = { if (isReadOnly) emptyList()- else if (selectedPaths.contains(child)) selectedPaths.toList()- else listOf(child)+ else if (selectedPaths.any { it.key == child.key }) selectedPaths.mapNotNull { it.realFile }.toList()+ else listOfNotNull(child.realFile) }) HorizontalDivider( thickness = 0.5.dp, color = MaterialTheme.colorScheme.outlineVariant@@ -504,16 +520,15 @@ fun DirectoryPage(viewModel: FilesViewModel) { @OptIn(ExperimentalFoundationApi::class) @Composable fun DirectoryItem(- file: Path,+ file: FileBrowserItem, isEditing: Boolean, isSelected: Boolean,- fileSystem: FileSystem, isReadOnly: Boolean, onRename: (String) -> Unit, onToggleSelection: () -> Unit, onClick: () -> Unit,- onMove: (List<Path>) -> Unit,- onStartDrag: () -> List<Path>+ onMove: (List<File>) -> Unit,+ onStartDrag: () -> List<File> ) { var editedName by remember(isEditing) { mutableStateOf(file.name) } val focusRequester = remember { FocusRequester() }@@ -537,7 +552,7 @@ fun DirectoryItem( val uris = paths.map { path -> FileProvider.getUriForFile(- context, "${context.packageName}.fileprovider", path.toFile()+ context, "${context.packageName}.fileprovider", path ) } val mimeTypes = paths.map { path ->@@ -556,13 +571,13 @@ fun DirectoryItem( val clipData = ClipData( paths.first().name, mimeTypes, ClipData.Item(- paths.first().toString(), null, null, uris.first()+ paths.first().absolutePath, null, null, uris.first() ) ) for (i in 1 until uris.size) { clipData.addItem( ClipData.Item(- paths[i].toString(), null, null, uris[i]+ paths[i].absolutePath, null, null, uris[i] ) ) }@@ -573,12 +588,12 @@ fun DirectoryItem( ) } .then(- if (file.isDirectory(fileSystem) && !isReadOnly) {+ if (file.isDirectory && !isReadOnly && file.realFile != null) { Modifier.dragAndDropTarget(shouldStartDragAndDrop = { event -> event.mimeTypes().contains( ClipDescription.MIMETYPE_TEXT_PLAIN )- }, target = remember(file) {+ }, target = remember(file.key) { dropTarget( onDragStateChange = { isDraggingOver = it }, onDrop = { currentOnMove(it) }@@ -611,11 +626,11 @@ fun DirectoryItem( }, leadingContent = { val iconTint = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline- if (file.isDirectory(fileSystem)) IconFolder(tint = iconTint)+ if (file.isDirectory) IconFolder(tint = iconTint) else IconFile(tint = iconTint) }, supportingContent = {- if (!file.isDirectory(fileSystem)) {- file.size(fileSystem)?.let { size -> Text(Formatter.formatShortFileSize(context, size)) }+ if (!file.isDirectory) {+ file.size?.let { size -> Text(Formatter.formatShortFileSize(context, size)) } } }, colors = ListItemDefaults.colors(containerColor = Color.Transparent) )
files/src/main/java/com/vayunmathur/files/util/FilesViewModel.kt
diff --git a/files/src/main/java/com/vayunmathur/files/util/FilesViewModel.kt b/files/src/main/java/com/vayunmathur/files/util/FilesViewModel.ktindex fa0a7a6c87..2498503280 100644--- a/files/src/main/java/com/vayunmathur/files/util/FilesViewModel.kt+++ b/files/src/main/java/com/vayunmathur/files/util/FilesViewModel.kt@@ -29,13 +29,24 @@ import kotlinx.coroutines.launch import java.io.File import java.util.zip.ZipFile +/**+ * Migrated from okio FileSystem/Path/openZip to java.io.File + java.util.zip.ZipFile.+ * Real FS uses File; zip browsing is virtual backed by ZipFile entries.+ */+data class FileBrowserItem(+ val name: String,+ val isDirectory: Boolean,+ val size: Long?,+ val realFile: File?,+ val zipInnerPath: String?,+ val key: String,+)+ class FilesViewModel(application: Application) : AndroidViewModel(application) { private val prefs = application.getSharedPreferences("files_prefs", Context.MODE_PRIVATE) - // ---- Permission state ----- private val _isFilesGranted = MutableStateFlow(Environment.isExternalStorageManager()) val isFilesGranted: StateFlow<Boolean> = _isFilesGranted.asStateFlow() @@ -56,66 +67,56 @@ class FilesViewModel(application: Application) : AndroidViewModel(application) { _hasPromptedNotifications.value = true } - // ---- Navigation state -----+ // ---- Navigation ---- val rootDirectory: File = Environment.getExternalStorageDirectory() private val _currentDirectory = MutableStateFlow(rootDirectory) val currentDirectory: StateFlow<File> = _currentDirectory.asStateFlow() - /** The on-disk zip file when browsing inside an opened archive; null otherwise. */ private val _zipPath = MutableStateFlow<File?>(null) val zipPath: StateFlow<File?> = _zipPath.asStateFlow() - /** Relative path inside the opened zip, "" = root. */ private val _zipInternalPath = MutableStateFlow("") val zipInternalPath: StateFlow<String> = _zipInternalPath.asStateFlow() fun isZipMode(): Boolean = _zipPath.value != null - // ---- Directory listing -----+ // ---- Listing ---- private val _entries =- MutableStateFlow<Pair<List<File>, List<File>>>(emptyList<File>() to emptyList())- val entries: StateFlow<Pair<List<File>, List<File>>> = _entries.asStateFlow()+ MutableStateFlow<Pair<List<FileBrowserItem>, List<FileBrowserItem>>>(emptyList<FileBrowserItem>() to emptyList())+ val entries: StateFlow<Pair<List<FileBrowserItem>, List<FileBrowserItem>>> = _entries.asStateFlow() - // ---- Selection ------ private val _selectedPaths = MutableStateFlow<Set<File>>(emptySet())- val selectedPaths: StateFlow<Set<File>> = _selectedPaths.asStateFlow()+ // ---- Selection (only valid in real FS mode) ----+ private val _selectedPaths = MutableStateFlow<Set<FileBrowserItem>>(emptySet())+ val selectedPaths: StateFlow<Set<FileBrowserItem>> = _selectedPaths.asStateFlow() fun clearSelection() { if (_selectedPaths.value.isNotEmpty()) _selectedPaths.value = emptySet() } - fun addToSelection(path: File) {- _selectedPaths.value = _selectedPaths.value + path+ fun addToSelection(item: FileBrowserItem) {+ if (isZipMode()) return+ _selectedPaths.value = _selectedPaths.value + item } - fun toggleSelection(path: File) {+ fun toggleSelection(item: FileBrowserItem) {+ if (isZipMode()) return val current = _selectedPaths.value- _selectedPaths.value = if (current.any { it.absolutePath == path.absolutePath && it.name == path.name }) {- current.filterNot { it.absolutePath == path.absolutePath && it.name == path.name }.toSet()+ _selectedPaths.value = if (current.any { it.key == item.key }) {+ current.filterNot { it.key == item.key }.toSet() } else {- current + path+ current + item } } - // ---- Incoming share-intent URIs -----+ // ---- Share URIs ---- private val _incomingUris = MutableStateFlow<List<Uri>?>(null) val incomingUris: StateFlow<List<Uri>?> = _incomingUris.asStateFlow() - fun setIncomingUris(uris: List<Uri>) {- _incomingUris.value = uris- }-- fun clearIncomingUris() {- _incomingUris.value = null- }-- // ---- One-shot UI events ----+ fun setIncomingUris(uris: List<Uri>) { _incomingUris.value = uris }+ fun clearIncomingUris() { _incomingUris.value = null } + // ---- Events ---- private val _snackbarMessages = MutableSharedFlow<String>(extraBufferCapacity = 8) val snackbarMessages: SharedFlow<String> = _snackbarMessages.asSharedFlow() @@ -134,13 +135,12 @@ class FilesViewModel(application: Application) : AndroidViewModel(application) { if (zipFile == null) { val dir = _currentDirectory.value viewModelScope.launch(Dispatchers.IO) {- val files = dir.listFiles()?.toList() ?: emptyList()- _entries.value = files.partition { it.isDirectory }+ _entries.value = listRealDir(dir) } } else {- val internalPath = _zipInternalPath.value+ val inner = _zipInternalPath.value viewModelScope.launch(Dispatchers.IO) {- _entries.value = listZipEntries(zipFile, internalPath)+ _entries.value = listZipDir(zipFile, inner) } } }@@ -153,25 +153,16 @@ class FilesViewModel(application: Application) : AndroidViewModel(application) { } val dir = _currentDirectory.value observerJob = viewModelScope.launch {- val observer = object : FileObserver(- dir, CREATE or DELETE or MOVED_FROM or MOVED_TO,- ) {- override fun onEvent(event: Int, path: String?) {- loadDirectory()- }+ val observer = object : FileObserver(dir, CREATE or DELETE or MOVED_FROM or MOVED_TO) {+ override fun onEvent(event: Int, path: String?) { loadDirectory() } } observer.startWatching()- try {- awaitCancellation()- } finally {- observer.stopWatching()- }+ try { awaitCancellation() } finally { observer.stopWatching() } } } fun navigateTo(path: File) { if (isZipMode()) {- // If navigating while in zip mode via breadcrumb real-FS part, exit zip mode _zipPath.value = null _zipInternalPath.value = "" }@@ -181,7 +172,6 @@ class FilesViewModel(application: Application) : AndroidViewModel(application) { restartObserver() } - /** Navigate into a sub-directory inside the opened zip. */ fun navigateIntoZipDir(dirName: String) { val current = _zipInternalPath.value val newPath = if (current.isEmpty()) dirName else "$current/$dirName"@@ -191,35 +181,39 @@ class FilesViewModel(application: Application) : AndroidViewModel(application) { } fun navigateToZipInternalPath(fullInternalPath: String) {- // fullInternalPath is the directory path inside zip, e.g. "a/b" _zipInternalPath.value = fullInternalPath clearSelection() loadDirectory() } + fun navigateToZipParentRealFolder(target: File) {+ // breadcrumb click on real-FS part while in zip mode → exit zip+ _zipPath.value = null+ _zipInternalPath.value = ""+ _currentDirectory.value = target+ clearSelection()+ loadDirectory()+ restartObserver()+ }+ fun handleBack(): Boolean {- if (_selectedPaths.value.isNotEmpty()) {- clearSelection()- return true- }+ if (_selectedPaths.value.isNotEmpty()) { clearSelection(); return true } val z = _zipPath.value when { z != null -> { val internal = _zipInternalPath.value if (internal.isEmpty()) {- // Exit zip mode to parent of zip file val parent = z.parentFile ?: rootDirectory _zipPath.value = null _currentDirectory.value = parent+ restartObserver() } else {- // Go up one level inside zip val parentInternal = if (internal.contains("/")) internal.substringBeforeLast("/") else "" _zipInternalPath.value = parentInternal } loadDirectory()- restartObserver() }- _currentDirectory.value != rootDirectory -> {+ _currentDirectory.value.absolutePath != rootDirectory.absolutePath -> { _currentDirectory.value = _currentDirectory.value.parentFile ?: _currentDirectory.value loadDirectory() restartObserver()@@ -229,25 +223,22 @@ class FilesViewModel(application: Application) : AndroidViewModel(application) { return true } - // ---- File ops ------ fun rename(path: File, newName: String) {+ fun rename(item: FileBrowserItem, newName: String) { if (isZipMode()) return+ val path = item.realFile ?: return viewModelScope.launch(Dispatchers.IO) { try { val target = File(path.parentFile, newName) path.atomicMoveTo(target) clearSelection() loadDirectory()- } catch (e: Exception) {- emitMoveFailed(e)- }+ } catch (e: Exception) { emitMoveFailed(e) } } } fun deleteSelection() { if (isZipMode()) return- val selection = _selectedPaths.value+ val selection = _selectedPaths.value.mapNotNull { it.realFile } viewModelScope.launch(Dispatchers.IO) { selection.forEach { it.deleteRecursively() } clearSelection()@@ -258,16 +249,12 @@ class FilesViewModel(application: Application) : AndroidViewModel(application) { fun moveInto(sources: List<File>, target: File) { if (isZipMode()) return if (!target.isDirectory) return- moveFiles(sources, target) { source ->- source != target && !target.absolutePath.startsWith(source.absolutePath)- }+ moveFiles(sources, target) { source -> source != target && !target.absolutePath.startsWith(source.absolutePath) } } fun moveToBreadcrumb(sources: List<File>, target: File) { if (isZipMode()) return- moveFiles(sources, target) { source ->- source.parentFile != target && source != target- }+ moveFiles(sources, target) { source -> source.parentFile != target && source != target } } private fun moveFiles(sources: List<File>, target: File, canMove: (File) -> Boolean) {@@ -280,35 +267,27 @@ class FilesViewModel(application: Application) : AndroidViewModel(application) { val dest = File(target, source.name) source.atomicMoveTo(dest) movedAny = true- } catch (e: Exception) {- lastError = e- }+ } catch (e: Exception) { lastError = e } } }- if (movedAny) {- clearSelection()- loadDirectory()- }+ if (movedAny) { clearSelection(); loadDirectory() } lastError?.let { emitMoveFailed(it) } } } - fun openZipFile(path: File) {+ fun openZipFile(item: FileBrowserItem) {+ val file = item.realFile ?: return viewModelScope.launch(Dispatchers.IO) { try {- // Validate it can be opened- ZipFile(path).use { _ -> }- _zipPath.value = path+ ZipFile(file).use { _ -> }+ _zipPath.value = file _zipInternalPath.value = ""- _currentDirectory.value = File("/") // fake placeholder for zip root display+ _currentDirectory.value = File("/") // placeholder not used in zip mode clearSelection() loadDirectory() restartObserver() } catch (e: Exception) {- emit(- getApplication<Application>()- .getString(R.string.could_not_open_zip, e.localizedMessage),- )+ emit(getApplication<Application>().getString(R.string.could_not_open_zip, e.localizedMessage)) } } }@@ -316,27 +295,23 @@ class FilesViewModel(application: Application) : AndroidViewModel(application) { fun archive(archiveName: String) { if (isZipMode()) return val ctx = getApplication<Application>()- val sources = _selectedPaths.value+ val sources = _selectedPaths.value.mapNotNull { it.realFile?.absolutePath }.toTypedArray() val destFileName = if (archiveName.endsWith(".zip")) archiveName else "$archiveName.zip" val destFile = File(_currentDirectory.value, destFileName)+ if (sources.isEmpty()) return val zipWork = OneTimeWorkRequestBuilder<ZipWorker>().setInputData(- workDataOf(- "source_paths" to sources.map { it.absolutePath }.toTypedArray(),- "dest_path" to destFile.absolutePath,- ),+ workDataOf("source_paths" to sources, "dest_path" to destFile.absolutePath) ).build() WorkManager.getInstance(ctx).enqueue(zipWork) clearSelection() emit(ctx.getString(R.string.archiving_started)) } - fun unzip(zipPath: File, destPath: File) {+ fun unzip(zipItem: FileBrowserItem, destPath: File) {+ val zipFile = zipItem.realFile ?: return val ctx = getApplication<Application>() val unzipWork = OneTimeWorkRequestBuilder<UnzipWorker>().setInputData(- workDataOf(- "zip_path" to zipPath.absolutePath,- "dest_path" to destPath.absolutePath,- ),+ workDataOf("zip_path" to zipFile.absolutePath, "dest_path" to destPath.absolutePath) ).build() WorkManager.getInstance(ctx).enqueue(unzipWork) clearSelection()@@ -344,10 +319,10 @@ class FilesViewModel(application: Application) : AndroidViewModel(application) { } fun saveIncomingUris() {+ if (isZipMode()) return val ctx = getApplication<Application>() val uris = _incomingUris.value ?: return val target = _currentDirectory.value- if (isZipMode()) return viewModelScope.launch(Dispatchers.IO) { uris.forEach { uri -> saveUriToPath(ctx, uri, target) } clearIncomingUris()@@ -356,40 +331,27 @@ class FilesViewModel(application: Application) : AndroidViewModel(application) { } } - fun openFile(path: File) {+ fun openFile(item: FileBrowserItem) { val ctx = getApplication<Application>() if (isZipMode()) { emit(ctx.getString(R.string.zip_browse_only)) return }- val extension = path.extension- val mimeType =- MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) ?: "*/*"+ val file = item.realFile ?: return+ val extension = file.extension+ val mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) ?: "*/*" val intent = Intent(Intent.ACTION_VIEW).apply {- val uri = FileProvider.getUriForFile(- ctx, "${ctx.packageName}.fileprovider", path,- )+ val uri = FileProvider.getUriForFile(ctx, "${ctx.packageName}.fileprovider", file) setDataAndType(uri, mimeType)- flags = Intent.FLAG_ACTIVITY_NEW_TASK or- Intent.FLAG_GRANT_READ_URI_PERMISSION or- Intent.FLAG_GRANT_WRITE_URI_PERMISSION+ flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION } viewModelScope.launch { _intents.emit(intent) } } - fun showMessage(message: String) {- emit(message)- }-- private fun emit(message: String) {- viewModelScope.launch { _snackbarMessages.emit(message) }- }-+ fun showMessage(message: String) { emit(message) }+ private fun emit(message: String) { viewModelScope.launch { _snackbarMessages.emit(message) } } private fun emitMoveFailed(e: Exception) {- emit(- getApplication<Application>()- .getString(R.string.move_failed, e.localizedMessage),- )+ emit(getApplication<Application>().getString(R.string.move_failed, e.localizedMessage)) } private fun saveUriToPath(context: Context, uri: Uri, targetDir: File) {@@ -412,71 +374,93 @@ class FilesViewModel(application: Application) : AndroidViewModel(application) { return uri.path?.substringAfterLast('/') } - private fun listZipEntries(zipFile: File, internalDir: String): Pair<List<File>, List<File>> {+ private fun listRealDir(dir: File): Pair<List<FileBrowserItem>, List<FileBrowserItem>> {+ val files = dir.listFiles()?.toList() ?: emptyList()+ val items = files.map { f ->+ FileBrowserItem(+ name = f.name,+ isDirectory = f.isDirectory,+ size = if (f.isFile) f.length() else null,+ realFile = f,+ zipInnerPath = null,+ key = f.absolutePath+ )+ }+ return items.partition { it.isDirectory }+ }++ private fun listZipDir(zipFile: File, internalDir: String): Pair<List<FileBrowserItem>, List<FileBrowserItem>> { return try { ZipFile(zipFile).use { zf -> val prefix = if (internalDir.isEmpty()) "" else "$internalDir/"- val childDirNames = mutableSetOf<String>()- val childFiles = mutableListOf<File>()-- // Collect entries- val entries = zf.entries().toList()- for (entry in entries) {- val name = entry.name- if (name == internalDir || name == prefix) continue- if (!name.startsWith(prefix)) continue- var remainder = name.removePrefix(prefix)- if (remainder.isEmpty()) continue- // Skip leading slash if any- remainder = remainder.trimStart('/')+ val dirMap = mutableMapOf<String, FileBrowserItem>()+ val fileList = mutableListOf<FileBrowserItem>()+ for (entry in zf.entries()) {+ val rawName = entry.name+ val normalized = rawName.trimEnd('/')+ if (normalized.isEmpty()) continue+ if (normalized == internalDir) continue+ if (internalDir.isNotEmpty() && !rawName.startsWith(prefix) && !normalized.startsWith(prefix)) continue+ val remainder = if (prefix.isEmpty()) normalized else {+ if (normalized.length <= prefix.length) continue+ normalized.substring(prefix.length)+ } if (remainder.isEmpty()) continue- if (remainder.contains("/")) {- val first = remainder.substringBefore("/")- if (first.isNotEmpty()) childDirNames.add(first)+ val slashIdx = remainder.indexOf('/')+ if (slashIdx != -1) {+ val first = remainder.substring(0, slashIdx)+ if (first.isEmpty()) continue+ if (!dirMap.containsKey(first)) {+ val fullInner = if (internalDir.isEmpty()) first else "$internalDir/$first"+ dirMap[first] = FileBrowserItem(+ name = first,+ isDirectory = true,+ size = null,+ realFile = null,+ zipInnerPath = fullInner,+ key = "zip:$fullInner"+ )+ } } else {- // direct child if (entry.isDirectory) {- childDirNames.add(remainder.trimEnd('/'))- } else {- // fake file with name = remainder, path inside zip = prefix+remainder- // Use a File whose name is remainder and absolutePath encodes internal path for navigation- val fake = object : File("/zip/$prefix$remainder") {- override fun getName(): String = remainder- override fun isDirectory(): Boolean = false- override fun length(): Long = entry.size.takeIf { it >= 0 } ?: 0L+ if (!dirMap.containsKey(remainder)) {+ val fullInner = if (internalDir.isEmpty()) remainder else "$internalDir/$remainder"+ dirMap[remainder] = FileBrowserItem(+ name = remainder,+ isDirectory = true,+ size = null,+ realFile = null,+ zipInnerPath = fullInner,+ key = "zip:$fullInner"+ ) }- childFiles.add(fake)+ } else {+ val fullInner = if (internalDir.isEmpty()) remainder else "$internalDir/$remainder"+ fileList.add(+ FileBrowserItem(+ name = remainder,+ isDirectory = false,+ size = entry.size.takeIf { it >= 0 },+ realFile = null,+ zipInnerPath = fullInner,+ key = "zip:$fullInner"+ )+ ) } } }-- // For directories that are implicit (no explicit dir entry), we still have names- val dirFiles = childDirNames.map { dirName ->- object : File("/zip/$prefix$dirName") {- override fun getName(): String = dirName- override fun isDirectory(): Boolean = true- override fun length(): Long = 0L- }- }-- // For entries list we need real File objects for directories that may have size? we already- dirFiles.toList() to childFiles.toList()+ dirMap.values.toList() to fileList }- } catch (e: Exception) {- emptyList<File>() to emptyList()+ } catch (_: Exception) {+ emptyList<FileBrowserItem>() to emptyList() } } private fun File.atomicMoveTo(target: File) { try {- java.nio.file.Files.move(- this.toPath(),- target.toPath(),- java.nio.file.StandardCopyOption.ATOMIC_MOVE- )+ java.nio.file.Files.move(this.toPath(), target.toPath(), java.nio.file.StandardCopyOption.ATOMIC_MOVE) } catch (_: Exception) { if (!this.renameTo(target)) {- // fallback copy+delete if (this.isDirectory) { this.copyRecursively(target, overwrite = true) this.deleteRecursively()
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/BitesApiTest.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/BitesApiTest.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/BitesApiTest.ktindex bc21c2775e..7831d98e70 100644--- a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/BitesApiTest.kt+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/BitesApiTest.kt@@ -8,7 +8,8 @@ import com.vayunmathur.fooddelivery.data.MerchantsWrapper import kotlinx.serialization.json.Json import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject-import org.junit.Test+import kotlin.test.Test+import kotlin.test.assertTrue import java.net.HttpURLConnection import java.net.URL @@ -33,7 +34,7 @@ class BitesApiTest { val raw = httpGet("https://api.deliverycollective.com/api/v1/merchants/all/stores") println("RAW response length: ${raw.length}") println("RAW first 500 chars: ${raw.take(500)}")- assert(raw.isNotEmpty()) { "Response was empty" }+ assertTrue(raw.isNotEmpty(), "Response was empty") } @Test@@ -74,9 +75,9 @@ class BitesApiTest { val merchant = json.decodeFromString<Merchant>(singleMerchantJson) println("Parsed merchant: ${merchant.name}, id=${merchant.id}")- assert(merchant.name == "Test Restaurant")- assert(merchant.averageRating == null)- assert(merchant.brandColor == null)+ assertTrue(merchant.name == "Test Restaurant")+ assertTrue(merchant.averageRating == null)+ assertTrue(merchant.brandColor == null) } @Test@@ -117,8 +118,8 @@ class BitesApiTest { val resp = json.decodeFromString<ApiResponse<MerchantsWrapper>>(wrappedJson) println("Parsed wrapper: message=${resp.message}, merchants=${resp.data?.merchants?.size}")- assert(resp.data?.merchants?.size == 1)- assert(resp.data?.merchants?.first()?.name == "Restaurant A")+ assertTrue(resp.data?.merchants?.size == 1)+ assertTrue(resp.data?.merchants?.first()?.name == "Restaurant A") } @Test@@ -133,7 +134,7 @@ class BitesApiTest { merchants.take(3).forEach { m -> println(" - ${m.name} (id=${m.id}, rating=${m.averageRating}, tags=${m.merchantTags})") }- assert(merchants.isNotEmpty()) { "No merchants parsed!" }+ assertTrue(merchants.isNotEmpty(), "No merchants parsed!") } catch (e: Exception) { println("PARSE FAILED: ${e::class.simpleName}: ${e.message}") e.printStackTrace()
games/chess/src/test/java/com/vayunmathur/games/chess/data/ChessRulesTest.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/data/ChessRulesTest.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/data/ChessRulesTest.ktindex 4cd0ade167..3d301c29c6 100644--- a/games/chess/src/test/java/com/vayunmathur/games/chess/data/ChessRulesTest.kt+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/data/ChessRulesTest.kt@@ -1,9 +1,9 @@ package com.vayunmathur.games.chess.data -import org.junit.Assert.assertEquals-import org.junit.Assert.assertFalse-import org.junit.Assert.assertTrue-import org.junit.Test+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue class ChessRulesTest {
games/chess/src/test/java/com/vayunmathur/games/chess/data/LearnDataTest.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/data/LearnDataTest.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/data/LearnDataTest.ktindex 0387bff632..587a2fcfdc 100644--- a/games/chess/src/test/java/com/vayunmathur/games/chess/data/LearnDataTest.kt+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/data/LearnDataTest.kt@@ -1,9 +1,9 @@ package com.vayunmathur.games.chess.data -import org.junit.Assert.assertEquals-import org.junit.Assert.assertNull-import org.junit.Assert.assertTrue-import org.junit.Test+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue /** Pure-JVM checks for the Learn coordinate helpers and lesson board building. */ class LearnDataTest {
games/chess/src/test/java/com/vayunmathur/games/chess/data/PuzzleFormatTest.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/data/PuzzleFormatTest.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/data/PuzzleFormatTest.ktindex ece4413f87..fe1a3cb6ce 100644--- a/games/chess/src/test/java/com/vayunmathur/games/chess/data/PuzzleFormatTest.kt+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/data/PuzzleFormatTest.kt@@ -1,8 +1,8 @@ package com.vayunmathur.games.chess.data -import org.junit.Assert.assertEquals-import org.junit.Assert.assertNull-import org.junit.Test+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull import java.nio.ByteBuffer import java.nio.ByteOrder
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex f89a987ea5..622ccce229 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -138,6 +138,7 @@ kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutine kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinxSerializationJson" } kotlinx-datetime = { module = "org.jetbrains.kotlinx:kotlinx-datetime", version.ref = "kotlinxDatetime" } kotlin-test = { group = "org.jetbrains.kotlin", name = "kotlin-test", version.ref = "kotlin" }+kotlin-test-junit = { group = "org.jetbrains.kotlin", name = "kotlin-test-junit", version.ref = "kotlin" } # AndroidX – core & lifecycle androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
library/e2ee-p2p/src/test/java/com/vayunmathur/e2ee/PqcTest.kt
diff --git a/library/e2ee-p2p/src/test/java/com/vayunmathur/e2ee/PqcTest.kt b/library/e2ee-p2p/src/test/java/com/vayunmathur/e2ee/PqcTest.ktindex d7c1a5a2e8..a4e7c8a8dc 100644--- a/library/e2ee-p2p/src/test/java/com/vayunmathur/e2ee/PqcTest.kt+++ b/library/e2ee-p2p/src/test/java/com/vayunmathur/e2ee/PqcTest.kt@@ -1,11 +1,10 @@ package com.vayunmathur.e2ee -import org.junit.Assert.assertArrayEquals-import org.junit.Assert.assertFalse-import org.junit.Assert.assertTrue-import org.junit.Assume.assumeTrue-import org.junit.Before-import org.junit.Test+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue /** * These exercise the real native PQC (libe2ee_pqc.so), so they only run on-device@@ -16,24 +15,27 @@ import org.junit.Test class PqcTest { private var nativeAvailable = false - @Before+ @BeforeTest fun checkNative() { nativeAvailable = runCatching { Pqc.generateKem() }.isSuccess- assumeTrue("native e2ee_pqc lib not loadable on this host", nativeAvailable)+ // Skipped when native lib not loadable on this host — was Assume.assumeTrue before.+ if (!nativeAvailable) return } @Test fun ml_kem_encrypt_decrypt_roundtrip() {+ if (!nativeAvailable) return val (kemPub, kemPriv) = Pqc.generateKem() val (dsaPub, _) = Pqc.generateDsa() val bundle = Pqc.bundle(kemPub, dsaPub) val msg = "post-quantum hello — a longer payload than RSA-OAEP could ever hold in one shot".encodeToByteArray() val ct = Pqc.encryptTo(bundle, msg)- assertArrayEquals(msg, Pqc.decrypt(kemPriv, ct))+ assertContentEquals(msg, Pqc.decrypt(kemPriv, ct)) } @Test fun ml_dsa_sign_verify() {+ if (!nativeAvailable) return val (kemPub, _) = Pqc.generateKem() val (dsaPub, dsaPriv) = Pqc.generateDsa() val bundle = Pqc.bundle(kemPub, dsaPub)@@ -49,6 +51,7 @@ class PqcTest { @Test fun security_code_matches_both_sides() {+ if (!nativeAvailable) return val a = Pqc.bundle(Pqc.generateKem().first, Pqc.generateDsa().first) val b = Pqc.bundle(Pqc.generateKem().first, Pqc.generateDsa().first) assertTrue(Pqc.securityCode(a, b) == Pqc.securityCode(b, a)) // order-independent
library/e2ee-p2p/src/test/java/com/vayunmathur/e2ee/SignTest.kt
diff --git a/library/e2ee-p2p/src/test/java/com/vayunmathur/e2ee/SignTest.kt b/library/e2ee-p2p/src/test/java/com/vayunmathur/e2ee/SignTest.ktindex b898fd734f..e2b479b105 100644--- a/library/e2ee-p2p/src/test/java/com/vayunmathur/e2ee/SignTest.kt+++ b/library/e2ee-p2p/src/test/java/com/vayunmathur/e2ee/SignTest.kt@@ -1,9 +1,9 @@ package com.vayunmathur.e2ee import kotlinx.coroutines.runBlocking-import org.junit.Assert.assertFalse-import org.junit.Assert.assertTrue-import org.junit.Test+import kotlin.test.Test+import kotlin.test.assertFalse+import kotlin.test.assertTrue class SignTest { @Test@@ -11,10 +11,10 @@ class SignTest { val kp = E2ee.generateKeyPair() // OAEP-generated key, reused for PSS signatures val data = "the quick brown fox".encodeToByteArray() val sig = E2ee.sign(kp.privateKeyPem, data)- assertTrue("valid signature verifies", E2ee.verify(kp.publicKeyPem, data, sig))- assertFalse("tampered data fails", E2ee.verify(kp.publicKeyPem, "different".encodeToByteArray(), sig))+ assertTrue(E2ee.verify(kp.publicKeyPem, data, sig), "valid signature verifies")+ assertFalse(E2ee.verify(kp.publicKeyPem, "different".encodeToByteArray(), sig), "tampered data fails") val other = E2ee.generateKeyPair()- assertFalse("wrong key fails", E2ee.verify(other.publicKeyPem, data, sig))+ assertFalse(E2ee.verify(other.publicKeyPem, data, sig), "wrong key fails") } }
library/ui/src/test/java/com/vayunmathur/library/ui/odf/MarkdownOdfConverterTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/MarkdownOdfConverterTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/MarkdownOdfConverterTest.ktindex d1d10fe9e4..2c1064fdc8 100644--- a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/MarkdownOdfConverterTest.kt+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/MarkdownOdfConverterTest.kt@@ -1,8 +1,8 @@ package com.vayunmathur.library.ui.odf -import org.junit.Assert.assertEquals-import org.junit.Assert.assertTrue-import org.junit.Test+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue class MarkdownOdfConverterTest {
library/ui/src/test/java/com/vayunmathur/library/ui/odf/RemapCaretTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/RemapCaretTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/RemapCaretTest.ktindex 0b3ab7e12c..0bb8cf5911 100644--- a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/RemapCaretTest.kt+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/RemapCaretTest.kt@@ -1,7 +1,7 @@ package com.vayunmathur.library.ui.odf -import org.junit.Assert.assertEquals-import org.junit.Test+import kotlin.test.Test+import kotlin.test.assertEquals class RemapCaretTest { @Test fun insert_after_caret_leaves_it() {
library/ui/src/test/java/com/vayunmathur/library/ui/odf/SerializeFlatNamespaceTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/SerializeFlatNamespaceTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/SerializeFlatNamespaceTest.ktindex 77380974d7..e4eec0ad9b 100644--- a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/SerializeFlatNamespaceTest.kt+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/SerializeFlatNamespaceTest.kt@@ -1,7 +1,7 @@ package com.vayunmathur.library.ui.odf -import org.junit.Assert.assertTrue-import org.junit.Test+import kotlin.test.Test+import kotlin.test.assertTrue class SerializeFlatNamespaceTest { @Test@@ -11,12 +11,12 @@ class SerializeFlatNamespaceTest { content = listOf(OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("hi"))))) ) val flat = OdfSerializer.serializeFlat(doc)- assertTrue("flat ODF must be a single office:document", flat.contains("<office:document"))+ assertTrue(flat.contains("<office:document"), "flat ODF must be a single office:document") // Any meta:-prefixed element must be preceded by an xmlns:meta declaration on the root. if (flat.contains("<meta:")) { assertTrue(+ flat.substringBefore("<meta:").contains("xmlns:meta="), "xmlns:meta must be declared before the first <meta: element",- flat.substringBefore("<meta:").contains("xmlns:meta=") ) } }
office/src/test/java/com/vayunmathur/office/odf/ConvertersTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/ConvertersTest.kt b/office/src/test/java/com/vayunmathur/office/odf/ConvertersTest.ktindex c322bf5a3f..054ff6f4e3 100644--- a/office/src/test/java/com/vayunmathur/office/odf/ConvertersTest.kt+++ b/office/src/test/java/com/vayunmathur/office/odf/ConvertersTest.kt@@ -1,9 +1,9 @@ package com.vayunmathur.office.odf import com.vayunmathur.library.ui.odf.*-import org.junit.Assert.assertEquals-import org.junit.Assert.assertTrue-import org.junit.Test+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue /** * Tests for the document-format converters (HTML/RTF round-trip, EPUB/LaTeX/PDF export) and the
office/src/test/java/com/vayunmathur/office/odf/FlatOdfRoundTripTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/FlatOdfRoundTripTest.kt b/office/src/test/java/com/vayunmathur/office/odf/FlatOdfRoundTripTest.ktindex 49123adb65..bb0fe0f047 100644--- a/office/src/test/java/com/vayunmathur/office/odf/FlatOdfRoundTripTest.kt+++ b/office/src/test/java/com/vayunmathur/office/odf/FlatOdfRoundTripTest.kt@@ -11,7 +11,7 @@ import com.vayunmathur.library.ui.odf.OdfSlide import com.vayunmathur.library.ui.odf.OdfSlideElement import com.vayunmathur.library.ui.odf.OdfFrame import com.vayunmathur.library.ui.odf.OdfSpan-import org.junit.Test+import kotlin.test.Test import org.xmlpull.v1.XmlPullParser import org.xmlpull.v1.XmlPullParserFactory import java.io.StringReader
office/src/test/java/com/vayunmathur/office/odf/OdfSerializerFeatureTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/OdfSerializerFeatureTest.kt b/office/src/test/java/com/vayunmathur/office/odf/OdfSerializerFeatureTest.ktindex 818000b000..e87782eb83 100644--- a/office/src/test/java/com/vayunmathur/office/odf/OdfSerializerFeatureTest.kt+++ b/office/src/test/java/com/vayunmathur/office/odf/OdfSerializerFeatureTest.kt@@ -2,8 +2,8 @@ package com.vayunmathur.office.odf import androidx.compose.ui.unit.LayoutDirection import com.vayunmathur.library.ui.odf.*-import org.junit.Assert.assertTrue-import org.junit.Test+import kotlin.test.Test+import kotlin.test.assertTrue /** * Verifies newly wired native-ODF serialization: rounded-rect corner radius, paragraph@@ -17,7 +17,7 @@ class OdfSerializerFeatureTest { OdfSlideElement.Shape(OdfShape.Rect(10f, 10f, 100f, 60f, fillColor = 0xFF4472C4, cornerRadius = 12f)) )))) val xml = OdfSerializer.serialize(doc)- assertTrue("expected draw:corner-radius in $xml".take(60), xml.contains("draw:corner-radius"))+ assertTrue(xml.contains("draw:corner-radius"), "expected draw:corner-radius in ${xml.take(60)}") } @Test fun paragraphWritingModeSerialized() {
office/src/test/java/com/vayunmathur/office/odf/OoxmlImporterTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/OoxmlImporterTest.kt b/office/src/test/java/com/vayunmathur/office/odf/OoxmlImporterTest.ktindex 8f754a16ce..0ca0ad6640 100644--- a/office/src/test/java/com/vayunmathur/office/odf/OoxmlImporterTest.kt+++ b/office/src/test/java/com/vayunmathur/office/odf/OoxmlImporterTest.kt@@ -6,9 +6,9 @@ import com.vayunmathur.library.ui.odf.OdfDocument import com.vayunmathur.library.ui.odf.OdfSlideElement import com.vayunmathur.library.ui.odf.ListType import com.vayunmathur.library.ui.odf.ParagraphStyle-import org.junit.Assert.assertEquals-import org.junit.Assert.assertTrue-import org.junit.Test+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue /** * Unit tests for the expanded OOXML importer: pure helpers (units/colors/number-formats/formulas/
office/src/test/java/com/vayunmathur/office/odf/OoxmlRoundTripTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/OoxmlRoundTripTest.kt b/office/src/test/java/com/vayunmathur/office/odf/OoxmlRoundTripTest.ktindex f2b40eb4c4..88e0f20ff6 100644--- a/office/src/test/java/com/vayunmathur/office/odf/OoxmlRoundTripTest.kt+++ b/office/src/test/java/com/vayunmathur/office/odf/OoxmlRoundTripTest.kt@@ -1,9 +1,9 @@ package com.vayunmathur.office.odf import com.vayunmathur.library.ui.odf.*-import org.junit.Assert.assertEquals-import org.junit.Assert.assertTrue-import org.junit.Test+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue /** * Round-trip tests: build an ODF model, export to OOXML via [OoxmlExporter], re-import via
office/src/test/java/com/vayunmathur/office/util/OfficeSharingE2ETest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/OfficeSharingE2ETest.kt b/office/src/test/java/com/vayunmathur/office/util/OfficeSharingE2ETest.ktindex 21675eee6b..af5e10deb9 100644--- a/office/src/test/java/com/vayunmathur/office/util/OfficeSharingE2ETest.kt+++ b/office/src/test/java/com/vayunmathur/office/util/OfficeSharingE2ETest.kt@@ -6,11 +6,11 @@ import com.vayunmathur.e2ee.Pqc import com.vayunmathur.e2ee.PqcIdentity import kotlinx.coroutines.runBlocking import kotlinx.serialization.json.Json-import org.junit.Assert.assertArrayEquals-import org.junit.Assert.assertEquals-import org.junit.Assert.assertFalse-import org.junit.Assert.assertTrue-import org.junit.Test+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue import kotlin.io.encoding.Base64 /**@@ -76,7 +76,7 @@ class OfficeSharingE2ETest { editor.decrypt(Base64.decode(relay.pull("inbox:$editorId").single())).decodeToString() ) assertEquals(OfficeRoles.EDITOR, inv.role)- assertTrue("invite must carry owner key", inv.ownerKey.isNotBlank())+ assertTrue(inv.ownerKey.isNotBlank(), "invite must carry owner key") val recDocKey = Base64.decode(inv.key) val ownerKey = Base64.decode(inv.ownerKey) @@ -97,7 +97,7 @@ class OfficeSharingE2ETest { val roleOk = OfficeRoles.canEdit(roleById[so.author] ?: OfficeRoles.VIEWER) if (sigOk && roleOk) acceptedOps = so.ops }- assertEquals("owner-signed op accepted and delivered byte-intact", opsJson, acceptedOps)+ assertEquals(opsJson, acceptedOps, "owner-signed op accepted and delivered byte-intact") // ---- Negative: a viewer's forged op is rejected ---- roleById[editorId] = OfficeRoles.VIEWER@@ -106,14 +106,14 @@ class OfficeSharingE2ETest { val forged = SignedOp(editorId, Base64.encode(editor.sign(forgedJson.encodeToByteArray())), forgedJson) val sigOk = Pqc.verify(relay.directory[editorId]!!, forged.ops.encodeToByteArray(), Base64.decode(forged.sig)) val roleOk = OfficeRoles.canEdit(roleById[forged.author] ?: OfficeRoles.VIEWER)- assertTrue("signature itself is valid", sigOk)- assertFalse("but a viewer's edit must be rejected by the role gate", sigOk && roleOk)+ assertTrue(sigOk, "signature itself is valid")+ assertFalse(sigOk && roleOk, "but a viewer's edit must be rejected by the role gate") // ---- Negative: an op that lies about authorship fails signature verification ---- val liar = SignedOp(ownerId, Base64.encode(editor.sign(forgedJson.encodeToByteArray())), forgedJson) assertFalse(+ Pqc.verify(relay.directory[ownerId]!!, liar.ops.encodeToByteArray(), Base64.decode(liar.sig)), "editor cannot forge an op as the owner (wrong signing key)",- Pqc.verify(relay.directory[ownerId]!!, liar.ops.encodeToByteArray(), Base64.decode(liar.sig)) ) } @@ -129,7 +129,7 @@ class OfficeSharingE2ETest { "editor" to Base64.encode(Pqc.encryptTo(editor.publicBundle, newKey)), ) // The remaining editor recovers the new key; the revoked member has no wrap for it.- assertArrayEquals(newKey, editor.decrypt(Base64.decode(wraps.getValue("editor"))))+ assertContentEquals(newKey, editor.decrypt(Base64.decode(wraps.getValue("editor")))) assertTrue(wraps["revoked"] == null) // New content encrypted under the new key is readable by the editor but not by the revoked // member (who only ever held the old key).
passwords/src/test/java/com/vayunmathur/passwords/cable/CableEidTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/cable/CableEidTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/cable/CableEidTest.ktindex b771a4dc09..04bc73d14c 100644--- a/passwords/src/test/java/com/vayunmathur/passwords/cable/CableEidTest.kt+++ b/passwords/src/test/java/com/vayunmathur/passwords/cable/CableEidTest.kt@@ -1,8 +1,8 @@ package com.vayunmathur.passwords.cable -import org.junit.Assert.assertArrayEquals-import org.junit.Assert.assertEquals-import org.junit.Test+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals import javax.crypto.Cipher import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec@@ -17,8 +17,8 @@ class CableEidTest { assertEquals(CableEid.EID_SIZE, eid.size) assertEquals(0, eid[0].toInt())- assertArrayEquals(nonce, eid.copyOfRange(1, 11))- assertArrayEquals(routing, eid.copyOfRange(11, 14))+ assertContentEquals(nonce, eid.copyOfRange(1, 11))+ assertContentEquals(routing, eid.copyOfRange(11, 14)) assertEquals(0x02.toByte(), eid[14]) // low byte of domain, little-endian assertEquals(0x01.toByte(), eid[15]) // high byte }@@ -39,14 +39,14 @@ class CableEidTest { // AES-256 single block decrypts back to the plaintext EID. val cipher = Cipher.getInstance("AES/ECB/NoPadding") cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(eidKey.copyOfRange(0, 32), "AES"))- assertArrayEquals(plaintext, cipher.doFinal(ciphertext))+ assertContentEquals(plaintext, cipher.doFinal(ciphertext)) // HMAC tag verifies. val expectedTag = Mac.getInstance("HmacSHA256").run { init(SecretKeySpec(eidKey.copyOfRange(32, 64), "HmacSHA256")) doFinal(ciphertext) }.copyOfRange(0, CableEid.TAG_SIZE)- assertArrayEquals(expectedTag, tag)+ assertContentEquals(expectedTag, tag) } @Test fun uuid16Expansion() {
passwords/src/test/java/com/vayunmathur/passwords/cable/CableQrTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/cable/CableQrTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/cable/CableQrTest.ktindex e2c4643338..3e6801caad 100644--- a/passwords/src/test/java/com/vayunmathur/passwords/cable/CableQrTest.kt+++ b/passwords/src/test/java/com/vayunmathur/passwords/cable/CableQrTest.kt@@ -1,10 +1,10 @@ package com.vayunmathur.passwords.cable import com.vayunmathur.passwords.util.Cbor-import org.junit.Assert.assertArrayEquals-import org.junit.Assert.assertEquals-import org.junit.Assert.assertNull-import org.junit.Test+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertNull /** Tests for the caBLE QR digit codec, CBOR field parse, and HKDF derivations. */ class CableQrTest {@@ -35,7 +35,7 @@ class CableQrTest { for (len in 0..40) { val data = ByteArray(len) { ((it * 37 + 11) and 0xFF).toByte() } val encoded = digitEncode(data)- assertArrayEquals("len=$len", data, CableQrData.digitDecode(encoded))+ assertContentEquals(data, CableQrData.digitDecode(encoded), "len=$len") } } @@ -43,7 +43,7 @@ class CableQrTest { @Test fun digitKnownAnswerVector() { val bytes = byteArrayOf(0x61, 0x62, 0xFF.toByte()) assertEquals("16736865", digitEncode(bytes))- assertArrayEquals(bytes, CableQrData.digitDecode("16736865"))+ assertContentEquals(bytes, CableQrData.digitDecode("16736865")) } @Test fun parseFidoUri() {@@ -59,8 +59,8 @@ class CableQrTest { val uri = CableQrData.URI_PREFIX + digitEncode(cbor) val qr = CableQrData.parse(uri)- assertArrayEquals(peerKey, qr.peerPublicKey)- assertArrayEquals(secret, qr.qrSecret)+ assertContentEquals(peerKey, qr.peerPublicKey)+ assertContentEquals(secret, qr.qrSecret) assertEquals(2, qr.numKnownDomains) assertEquals(1_700_000_000L, qr.timestampSeconds) assertEquals("ga", qr.requestTypeHint)@@ -78,11 +78,11 @@ class CableQrTest { "2d2d0a90cf1a5a4c5db02d56ecc4c5bf" + "34007208d5b887185865" )- assertArrayEquals(expected, CableKeys.hkdf(ikm, salt, info, 42))+ assertContentEquals(expected, CableKeys.hkdf(ikm, salt, info, 42)) } @Test fun deriveInfoIsLittleEndianUint32() {- assertArrayEquals(byteArrayOf(3, 0, 0, 0), CableKeys.leUint32(CableKeys.Purpose.PSK.value))+ assertContentEquals(byteArrayOf(3, 0, 0, 0), CableKeys.leUint32(CableKeys.Purpose.PSK.value)) // Derived values are deterministic and length-correct. val secret = ByteArray(16) { it.toByte() } assertEquals(CableKeys.PSK_SIZE, CableKeys.psk(secret, ByteArray(16)).size)
passwords/src/test/java/com/vayunmathur/passwords/cable/CborTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/cable/CborTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/cable/CborTest.ktindex e45215f192..230c7f6768 100644--- a/passwords/src/test/java/com/vayunmathur/passwords/cable/CborTest.kt+++ b/passwords/src/test/java/com/vayunmathur/passwords/cable/CborTest.kt@@ -1,11 +1,11 @@ package com.vayunmathur.passwords.cable import com.vayunmathur.passwords.util.Cbor-import org.junit.Assert.assertArrayEquals-import org.junit.Assert.assertEquals-import org.junit.Assert.assertNull-import org.junit.Assert.assertTrue-import org.junit.Test+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue /** Round-trip tests for the CBOR encoder ([Cbor]) + decoder ([CborReader]) and the CTAP2 models. */ class CborTest {@@ -24,7 +24,7 @@ class CborTest { @Test fun byteStringRoundTrip() { val data = byteArrayOf(1, 2, 3, 0, -1, 42)- assertArrayEquals(data, CborReader.decode(Cbor.encode(data)) as ByteArray)+ assertContentEquals(data, CborReader.decode(Cbor.encode(data)) as ByteArray) } @Test fun textStringRoundTrip() {@@ -37,7 +37,7 @@ class CborTest { val decoded = CborReader.decode(Cbor.encode(list)) as List<*> assertEquals(1L, decoded[0]) assertEquals("two", decoded[1])- assertArrayEquals(byteArrayOf(3), decoded[2] as ByteArray)+ assertContentEquals(byteArrayOf(3), decoded[2] as ByteArray) } @Test fun mapRoundTrip() {@@ -45,7 +45,7 @@ class CborTest { val decoded = CborReader.decode(Cbor.encode(map)) as Map<*, *> assertEquals("a", decoded[1L]) assertEquals(100L, decoded[2L])- assertArrayEquals(byteArrayOf(9), decoded[3L] as ByteArray)+ assertContentEquals(byteArrayOf(9), decoded[3L] as ByteArray) } @Test fun booleanValues() {@@ -64,8 +64,8 @@ class CborTest { assertEquals(2L, decoded[1L]) assertEquals(-7L, decoded[3L]) assertEquals(1L, decoded[-1L])- assertArrayEquals(x, decoded[-2L] as ByteArray)- assertArrayEquals(y, decoded[-3L] as ByteArray)+ assertContentEquals(x, decoded[-2L] as ByteArray)+ assertContentEquals(y, decoded[-3L] as ByteArray) } @Test fun getAssertionRequestParse() {@@ -80,9 +80,9 @@ class CborTest { val req = CtapGetAssertionRequest.parse(payload) assertEquals("example.com", req.rpId)- assertArrayEquals(clientDataHash, req.clientDataHash)+ assertContentEquals(clientDataHash, req.clientDataHash) assertEquals(1, req.allowList.size)- assertArrayEquals(credId, req.allowList[0].id)+ assertContentEquals(credId, req.allowList[0].id) assertTrue(req.userPresenceRequired) assertTrue(req.userVerificationRequired) }@@ -109,11 +109,11 @@ class CborTest { val decoded = CborReader.decode(resp.encode()) as Map<*, *> val cred = decoded[1L] as Map<*, *> assertEquals("public-key", cred["type"])- assertArrayEquals(byteArrayOf(1, 2, 3), cred["id"] as ByteArray)- assertArrayEquals(resp.authData, decoded[2L] as ByteArray)- assertArrayEquals(byteArrayOf(9, 8, 7), decoded[3L] as ByteArray)+ assertContentEquals(byteArrayOf(1, 2, 3), cred["id"] as ByteArray)+ assertContentEquals(resp.authData, decoded[2L] as ByteArray)+ assertContentEquals(byteArrayOf(9, 8, 7), decoded[3L] as ByteArray) val user = decoded[4L] as Map<*, *>- assertArrayEquals(byteArrayOf(4, 5, 6), user["id"] as ByteArray)+ assertContentEquals(byteArrayOf(4, 5, 6), user["id"] as ByteArray) assertEquals("alice", user["name"]) } @@ -122,7 +122,7 @@ class CborTest { val decoded = CborReader.decode(CtapGetInfoResponse(aaguid = aaguid).encode()) as Map<*, *> val versions = decoded[1L] as List<*> assertTrue(versions.contains("FIDO_2_0"))- assertArrayEquals(aaguid, decoded[3L] as ByteArray)+ assertContentEquals(aaguid, decoded[3L] as ByteArray) val options = decoded[4L] as Map<*, *> assertEquals(true, options["rk"]) }
passwords/src/test/java/com/vayunmathur/passwords/cable/CryptoParityTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/cable/CryptoParityTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/cable/CryptoParityTest.ktindex c166c5941f..805ee60c75 100644--- a/passwords/src/test/java/com/vayunmathur/passwords/cable/CryptoParityTest.kt+++ b/passwords/src/test/java/com/vayunmathur/passwords/cable/CryptoParityTest.kt@@ -1,9 +1,9 @@ package com.vayunmathur.passwords.cable -import org.junit.Assert.assertArrayEquals-import org.junit.Assert.assertEquals-import org.junit.Assert.assertTrue-import org.junit.Test+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertTrue import java.math.BigInteger import java.security.interfaces.ECPublicKey @@ -30,7 +30,7 @@ class CryptoParityTest { @Test fun hkdf_matches_rfc5869_basic_vector() { // A.1: IKM 22x0b, 13-byte salt, 10-byte info, L = 42.- assertArrayEquals(+ assertContentEquals( hex("3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf" + "34007208d5b887185865"), CableKeys.hkdf(@@ -45,7 +45,7 @@ class CryptoParityTest { @Test fun hkdf_matches_rfc5869_long_input_vector() { // A.2: 80-byte IKM, 80-byte salt, 80-byte info, L = 82 — spans several expand rounds.- assertArrayEquals(+ assertContentEquals( hex("b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c" + "59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71" + "cc30c58179ec3e87c14c01d5c1f3434f1d87"),@@ -65,10 +65,10 @@ class CryptoParityTest { "8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8" ) val ikm = ByteArray(22) { 0x0b }- assertArrayEquals(expected, CableKeys.hkdf(ikm, ByteArray(0), ByteArray(0), 42))+ assertContentEquals(expected, CableKeys.hkdf(ikm, ByteArray(0), ByteArray(0), 42)) // A null salt must be treated as the RFC's zero salt, identically to an empty one // (BoringSSL parity — Chromium relies on this for the QR secret).- assertArrayEquals(expected, CableKeys.hkdf(ikm, null, ByteArray(0), 42))+ assertContentEquals(expected, CableKeys.hkdf(ikm, null, ByteArray(0), 42)) } @Test@@ -79,10 +79,10 @@ class CryptoParityTest { for (salt in listOf<ByteArray?>(null, ByteArray(0), "some-salt".toByteArray())) { val full = CableKeys.hkdf(ikm, salt, info, 100) for (len in intArrayOf(10, 16, 32, 64, 100)) {- assertArrayEquals(- "salt=${salt?.size} len=$len",+ assertContentEquals( full.copyOf(len), CableKeys.hkdf(ikm, salt, info, len),+ "salt=${salt?.size} len=$len", ) } }@@ -138,8 +138,8 @@ class CryptoParityTest { assertEquals(original.w.affineY, fromUncompressed.w.affineY) assertTrue(+ fromCompressed.w.affineX.let { _ -> onCurve(fromCompressed.w.affineX, fromCompressed.w.affineY) }, "decompressed point off curve",- onCurve(fromCompressed.w.affineX, fromCompressed.w.affineY), ) // The recovered Y's parity must match the prefix that was encoded. val prefix = P256.toCompressed(kp.public)[0].toInt() and 0xff@@ -153,7 +153,7 @@ class CryptoParityTest { val b = P256.generateKeyPair() val ab = P256.ecdh(a.private, P256.decodePoint(P256.toUncompressed(b.public))) val ba = P256.ecdh(b.private, P256.decodePoint(P256.toUncompressed(a.public)))- assertArrayEquals(ab, ba)+ assertContentEquals(ab, ba) assertEquals(P256.DH_OUTPUT_SIZE, ab.size) } }
passwords/src/test/java/com/vayunmathur/passwords/cable/CtapProcessorTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/cable/CtapProcessorTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/cable/CtapProcessorTest.ktindex 12414918f2..c246140530 100644--- a/passwords/src/test/java/com/vayunmathur/passwords/cable/CtapProcessorTest.kt+++ b/passwords/src/test/java/com/vayunmathur/passwords/cable/CtapProcessorTest.kt@@ -6,10 +6,10 @@ import com.vayunmathur.passwords.util.Cbor import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.runBlocking-import org.junit.Assert.assertArrayEquals-import org.junit.Assert.assertEquals-import org.junit.Assert.assertTrue-import org.junit.Test+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertTrue import java.security.KeyPairGenerator import java.security.MessageDigest import java.security.Signature@@ -72,11 +72,11 @@ class CtapProcessorTest { val map = CborReader.decode(response.copyOfRange(1, response.size)) as Map<*, *> val cred = map[1L] as Map<*, *>- assertArrayEquals(credIdBytes, cred["id"] as ByteArray)+ assertContentEquals(credIdBytes, cred["id"] as ByteArray) val authData = map[2L] as ByteArray val signature = map[3L] as ByteArray val user = map[4L] as Map<*, *>- assertArrayEquals(userIdBytes, user["id"] as ByteArray)+ assertContentEquals(userIdBytes, user["id"] as ByteArray) // The signature must verify over authData || clientDataHash against the stored public key. val verifier = Signature.getInstance("SHA256withECDSA").apply {@@ -84,7 +84,7 @@ class CtapProcessorTest { update(authData) update(clientDataHash) }- assertTrue("assertion signature must verify", verifier.verify(signature))+ assertTrue(verifier.verify(signature), "assertion signature must verify") // signCount was bumped and persisted. assertEquals(6, dao.getByCredentialId(passkey.credentialId)!!.signCount)@@ -104,7 +104,7 @@ class CtapProcessorTest { val response = processor.process(byteArrayOf(Ctap.CMD_GET_INFO.toByte())) assertEquals(Ctap.OK.toByte(), response[0]) val map = CborReader.decode(response.copyOfRange(1, response.size)) as Map<*, *>- assertArrayEquals(ByteArray(16), map[3L] as ByteArray) // all-zero AAGUID+ assertContentEquals(ByteArray(16), map[3L] as ByteArray) // all-zero AAGUID assertEquals(listOf("cable", "hybrid", "internal"), map[9L]) // transports at key 9 val options = map[4L] as Map<*, *> assertEquals(true, options["uv"])
passwords/src/test/java/com/vayunmathur/passwords/cable/NoiseTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/cable/NoiseTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/cable/NoiseTest.ktindex 3301b247e2..bf29e55a03 100644--- a/passwords/src/test/java/com/vayunmathur/passwords/cable/NoiseTest.kt+++ b/passwords/src/test/java/com/vayunmathur/passwords/cable/NoiseTest.kt@@ -1,8 +1,8 @@ package com.vayunmathur.passwords.cable -import org.junit.Assert.assertArrayEquals-import org.junit.Assert.assertEquals-import org.junit.Test+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals import java.security.KeyPair import java.security.MessageDigest import javax.crypto.Cipher@@ -21,13 +21,13 @@ class NoiseTest { val kp = P256.generateKeyPair() val compressed = P256.toCompressed(kp.public) assertEquals(P256.COMPRESSED_SIZE, compressed.size)- assertArrayEquals(P256.toUncompressed(kp.public), P256.toUncompressed(P256.decodePoint(compressed)))+ assertContentEquals(P256.toUncompressed(kp.public), P256.toUncompressed(P256.decodePoint(compressed))) } @Test fun p256EcdhIsSymmetric() { val a = P256.generateKeyPair() val b = P256.generateKeyPair()- assertArrayEquals(P256.ecdh(a.private, b.public), P256.ecdh(b.private, a.public))+ assertContentEquals(P256.ecdh(a.private, b.public), P256.ecdh(b.private, a.public)) } @Test fun crypterRoundTripAndPadding() {@@ -38,8 +38,8 @@ class NoiseTest { val b = Crypter(writeKey, readKey) for (i in 0 until 4) { val msg = "msg-$i".toByteArray()- assertArrayEquals(msg, b.decrypt(a.encrypt(msg)))- assertArrayEquals(msg, a.decrypt(b.encrypt(msg)))+ assertContentEquals(msg, b.decrypt(a.encrypt(msg)))+ assertContentEquals(msg, a.decrypt(b.encrypt(msg))) } } @@ -48,7 +48,7 @@ class NoiseTest { val msg = ByteArray(len) { it.toByte() } val padded = Crypter.pad(msg) assertEquals(0, padded.size % 32)- assertArrayEquals(msg, Crypter.unpad(padded))+ assertContentEquals(msg, Crypter.unpad(padded)) } } @@ -66,10 +66,10 @@ class NoiseTest { // initiator -> responder val req = "ctap request".toByteArray()- assertArrayEquals(req, respCrypter.decrypt(initCrypter.encrypt(req)))+ assertContentEquals(req, respCrypter.decrypt(initCrypter.encrypt(req))) // responder -> initiator val resp = "ctap response".toByteArray()- assertArrayEquals(resp, initCrypter.decrypt(respCrypter.encrypt(resp)))+ assertContentEquals(resp, initCrypter.decrypt(respCrypter.encrypt(resp))) } /** KNpsk0 initiator mirroring Chromium HandshakeInitiator (QR variant). */
passwords/src/test/java/com/vayunmathur/passwords/cable/TunnelDomainsTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/cable/TunnelDomainsTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/cable/TunnelDomainsTest.ktindex 4927140af5..09d3944fd5 100644--- a/passwords/src/test/java/com/vayunmathur/passwords/cable/TunnelDomainsTest.kt+++ b/passwords/src/test/java/com/vayunmathur/passwords/cable/TunnelDomainsTest.kt@@ -1,8 +1,9 @@ package com.vayunmathur.passwords.cable -import org.junit.Assert.assertEquals-import org.junit.Assert.assertTrue-import org.junit.Test+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue /** Tests for the assigned tunnel-domain table (the verifiable part of [TunnelDomains]). */ class TunnelDomainsTest {@@ -13,9 +14,10 @@ class TunnelDomainsTest { assertEquals(0, TunnelDomains.DEFAULT_ID) } - @Test(expected = IllegalArgumentException::class)- fun unknownAssignedIdThrows() {- TunnelDomains.decode(2)+ @Test fun unknownAssignedIdThrows() {+ assertFailsWith<IllegalArgumentException> {+ TunnelDomains.decode(2)+ } } @Test fun hexRoundTrip() {
youpipe/build.gradle.kts
diff --git a/youpipe/build.gradle.kts b/youpipe/build.gradle.ktsindex 68a2c19ac8..42898c466f 100644--- a/youpipe/build.gradle.kts+++ b/youpipe/build.gradle.kts@@ -36,8 +36,7 @@ dependencies { implementation(libs.androidx.media3.exoplayer) implementation(libs.androidx.media3.exoplayer.dash) implementation(libs.androidx.media3.session)- // media3-datasource-okhttp transitively brings OkHttp – keep for player per plan exception- implementation(libs.androidx.media3.datasource.okhttp)+ // DefaultHttpDataSource (HttpURLConnection) for progressive; SABR via library:network – no okhttp implementation(libs.androidx.work.runtime.ktx) implementation(project(":library:work"))
youpipe/extractor/build.gradle.kts
diff --git a/youpipe/extractor/build.gradle.kts b/youpipe/extractor/build.gradle.ktsindex 58a5e92c44..fb13fb5307 100644--- a/youpipe/extractor/build.gradle.kts+++ b/youpipe/extractor/build.gradle.kts@@ -12,7 +12,8 @@ dependencies { implementation(libs.rhino.engine) implementation(libs.brotli.dec) - testImplementation(libs.junit)+ testImplementation(libs.kotlin.test)+ testImplementation(libs.kotlin.test.junit) } protobuf {
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/kiosk/KioskExtractor.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/kiosk/KioskExtractor.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/kiosk/KioskExtractor.javadeleted file mode 100644index 5ce8b0f5ec..0000000000--- a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/kiosk/KioskExtractor.java+++ /dev/null@@ -1,57 +0,0 @@-package org.schabi.newpipe.extractor.kiosk;--/*- * Created by Christian Schabesberger on 12.08.17.- *- * Copyright (C) 2017 Christian Schabesberger <[email protected]>- * KioskExtractor.java is part of NewPipe Extractor.- *- * NewPipe Extractor is free software: you can redistribute it and/or modify- * it under the terms of the GNU General Public License as published by- * the Free Software Foundation, either version 3 of the License, or- * (at your option) any later version.- *- * NewPipe Extractor is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU General Public License for more details.- *- * You should have received a copy of the GNU General Public License- * along with NewPipe Extractor. If not, see <http://www.gnu.org/licenses/>.- */--import org.schabi.newpipe.extractor.InfoItem;-import org.schabi.newpipe.extractor.ListExtractor;-import org.schabi.newpipe.extractor.StreamingService;-import org.schabi.newpipe.extractor.exceptions.ParsingException;-import org.schabi.newpipe.extractor.linkhandler.ListLinkHandler;--import javax.annotation.Nonnull;--public abstract class KioskExtractor<T extends InfoItem> extends ListExtractor<T> {- private final String id;-- public KioskExtractor(final StreamingService streamingService,- final ListLinkHandler linkHandler,- final String kioskId) {- super(streamingService, linkHandler);- this.id = kioskId;- }-- @Nonnull- @Override- public String getId() {- return id;- }-- /**- * Id should be the name of the kiosk, tho Id is used for identifying it in the frontend,- * so id should be kept in english.- * In order to get the name of the kiosk in the desired language we have to- * crawl if from the website.- * @return the translated version of id- */- @Nonnull- @Override- public abstract String getName() throws ParsingException;-}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/kiosk/KioskInfo.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/kiosk/KioskInfo.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/kiosk/KioskInfo.javadeleted file mode 100644index e426fbecad..0000000000--- a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/kiosk/KioskInfo.java+++ /dev/null@@ -1,75 +0,0 @@-package org.schabi.newpipe.extractor.kiosk;--/*- * Created by Christian Schabesberger on 12.08.17.- *- * Copyright (C) 2017 Christian Schabesberger <[email protected]>- * KioskInfo.java is part of NewPipe Extractor.- *- * NewPipe Extractor is free software: you can redistribute it and/or modify- * it under the terms of the GNU General Public License as published by- * the Free Software Foundation, either version 3 of the License, or- * (at your option) any later version.- *- * NewPipe Extractor is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU General Public License for more details.- *- * You should have received a copy of the GNU General Public License- * along with NewPipe Extractor. If not, see <http://www.gnu.org/licenses/>.- */--import org.schabi.newpipe.extractor.ListExtractor;-import org.schabi.newpipe.extractor.ListInfo;-import org.schabi.newpipe.extractor.NewPipe;-import org.schabi.newpipe.extractor.Page;-import org.schabi.newpipe.extractor.StreamingService;-import org.schabi.newpipe.extractor.exceptions.ExtractionException;-import org.schabi.newpipe.extractor.linkhandler.ListLinkHandler;-import org.schabi.newpipe.extractor.stream.StreamInfoItem;-import org.schabi.newpipe.extractor.utils.ExtractorHelper;--import java.io.IOException;--public final class KioskInfo extends ListInfo<StreamInfoItem> {- private KioskInfo(final int serviceId, final ListLinkHandler linkHandler, final String name) {- super(serviceId, linkHandler, name);- }-- public static ListExtractor.InfoItemsPage<StreamInfoItem> getMoreItems(- final StreamingService service, final String url, final Page page)- throws IOException, ExtractionException {- return service.getKioskList().getExtractorByUrl(url, page).getPage(page);- }-- public static KioskInfo getInfo(final String url) throws IOException, ExtractionException {- return getInfo(NewPipe.getServiceByUrl(url), url);- }-- public static KioskInfo getInfo(final StreamingService service, final String url)- throws IOException, ExtractionException {- final KioskExtractor extractor = service.getKioskList().getExtractorByUrl(url, null);- extractor.fetchPage();- return getInfo(extractor);- }-- /**- * Get KioskInfo from KioskExtractor- *- * @param extractor an extractor where fetchPage() was already got called on.- */- public static KioskInfo getInfo(final KioskExtractor extractor) throws ExtractionException {-- final KioskInfo info = new KioskInfo(extractor.getServiceId(),- extractor.getLinkHandler(),- extractor.getName());-- final ListExtractor.InfoItemsPage<StreamInfoItem> itemsPage- = ExtractorHelper.getItemsPageOrLogError(info, extractor);- info.setRelatedItems(itemsPage.getItems());- info.setNextPage(itemsPage.getNextPage());-- return info;- }-}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/kiosk/KioskList.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/kiosk/KioskList.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/kiosk/KioskList.javadeleted file mode 100644index 358e03c9c2..0000000000--- a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/kiosk/KioskList.java+++ /dev/null@@ -1,156 +0,0 @@-package org.schabi.newpipe.extractor.kiosk;--import static org.schabi.newpipe.extractor.utils.Utils.isNullOrEmpty;--import org.schabi.newpipe.extractor.NewPipe;-import org.schabi.newpipe.extractor.Page;-import org.schabi.newpipe.extractor.StreamingService;-import org.schabi.newpipe.extractor.exceptions.ExtractionException;-import org.schabi.newpipe.extractor.linkhandler.ListLinkHandlerFactory;-import org.schabi.newpipe.extractor.localization.ContentCountry;-import org.schabi.newpipe.extractor.localization.Localization;--import java.io.IOException;-import java.util.HashMap;-import java.util.Map;-import java.util.Set;--import javax.annotation.Nullable;--public class KioskList {-- public interface KioskExtractorFactory {- KioskExtractor createNewKiosk(StreamingService streamingService,- String url,- String kioskId)- throws ExtractionException, IOException;- }-- private final StreamingService service;- private final HashMap<String, KioskEntry> kioskList = new HashMap<>();- private String defaultKiosk = null;-- @Nullable- private Localization forcedLocalization;- @Nullable- private ContentCountry forcedContentCountry;-- private static class KioskEntry {- KioskEntry(final KioskExtractorFactory ef, final ListLinkHandlerFactory h) {- extractorFactory = ef;- handlerFactory = h;- }-- final KioskExtractorFactory extractorFactory;- final ListLinkHandlerFactory handlerFactory;- }-- public KioskList(final StreamingService service) {- this.service = service;- }-- public void addKioskEntry(final KioskExtractorFactory extractorFactory,- final ListLinkHandlerFactory handlerFactory,- final String id)- throws Exception {- if (kioskList.get(id) != null) {- throw new Exception("Kiosk with type " + id + " already exists.");- }- kioskList.put(id, new KioskEntry(extractorFactory, handlerFactory));- }-- public void setDefaultKiosk(final String kioskType) {- defaultKiosk = kioskType;- }-- public KioskExtractor getDefaultKioskExtractor()- throws ExtractionException, IOException {- return getDefaultKioskExtractor(null);- }-- public KioskExtractor getDefaultKioskExtractor(final Page nextPage)- throws ExtractionException, IOException {- return getDefaultKioskExtractor(nextPage, NewPipe.getPreferredLocalization());- }-- public KioskExtractor getDefaultKioskExtractor(final Page nextPage,- final Localization localization)- throws ExtractionException, IOException {- if (!isNullOrEmpty(defaultKiosk)) {- return getExtractorById(defaultKiosk, nextPage, localization);- } else {- final String first = kioskList.keySet().stream().findAny().orElse(null);- if (first != null) {- // if not set get any entry- return getExtractorById(first, nextPage, localization);- } else {- return null;- }- }- }-- public String getDefaultKioskId() {- return defaultKiosk;- }-- public KioskExtractor getExtractorById(final String kioskId, final Page nextPage)- throws ExtractionException, IOException {- return getExtractorById(kioskId, nextPage, NewPipe.getPreferredLocalization());- }-- public KioskExtractor getExtractorById(final String kioskId,- final Page nextPage,- final Localization localization)- throws ExtractionException, IOException {- final KioskEntry ke = kioskList.get(kioskId);- if (ke == null) {- throw new ExtractionException("No kiosk found with the type: " + kioskId);- } else {- final KioskExtractor kioskExtractor = ke.extractorFactory.createNewKiosk(service,- ke.handlerFactory.fromId(kioskId).getUrl(), kioskId);-- if (forcedLocalization != null) {- kioskExtractor.forceLocalization(forcedLocalization);- }- if (forcedContentCountry != null) {- kioskExtractor.forceContentCountry(forcedContentCountry);- }-- return kioskExtractor;- }- }-- public Set<String> getAvailableKiosks() {- return kioskList.keySet();- }-- public KioskExtractor getExtractorByUrl(final String url, final Page nextPage)- throws ExtractionException, IOException {- return getExtractorByUrl(url, nextPage, NewPipe.getPreferredLocalization());- }-- public KioskExtractor getExtractorByUrl(final String url,- final Page nextPage,- final Localization localization)- throws ExtractionException, IOException {- for (final Map.Entry<String, KioskEntry> e : kioskList.entrySet()) {- final KioskEntry ke = e.getValue();- if (ke.handlerFactory.acceptUrl(url)) {- return getExtractorById(ke.handlerFactory.getId(url), nextPage, localization);- }- }- throw new ExtractionException("Could not find a kiosk that fits to the url: " + url);- }-- public ListLinkHandlerFactory getListLinkHandlerFactoryByType(final String type) {- return kioskList.get(type).handlerFactory;- }-- public void forceLocalization(@Nullable final Localization localization) {- this.forcedLocalization = localization;- }-- public void forceContentCountry(@Nullable final ContentCountry contentCountry) {- this.forcedContentCountry = contentCountry;- }-}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/ClientsConstants.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/ClientsConstants.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/ClientsConstants.javadeleted file mode 100644index b5b7324797..0000000000--- a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/ClientsConstants.java+++ /dev/null@@ -1,121 +0,0 @@-package org.schabi.newpipe.extractor.services.youtube;--final class ClientsConstants {- private ClientsConstants() {- }-- // Common client fields-- static final String DESKTOP_CLIENT_PLATFORM = "DESKTOP";- static final String MOBILE_CLIENT_PLATFORM = "MOBILE";- static final String WATCH_CLIENT_SCREEN = "WATCH";- static final String EMBED_CLIENT_SCREEN = "EMBED";-- // WEB (YouTube desktop) client fields-- static final String WEB_CLIENT_ID = "1";- static final String WEB_CLIENT_NAME = "WEB";- /**- * The client version for InnerTube requests with the {@code WEB} client, used as the last- * fallback if the extraction of the real one failed.- */- static final String WEB_HARDCODED_CLIENT_VERSION = "2.20260120.01.00";-- // WEB_REMIX (YouTube Music) client fields-- static final String WEB_REMIX_CLIENT_ID = "67";- static final String WEB_REMIX_CLIENT_NAME = "WEB_REMIX";- static final String WEB_REMIX_HARDCODED_CLIENT_VERSION = "1.20260121.03.00";-- // WEB_EMBEDDED_PLAYER (YouTube embeds)-- static final String WEB_EMBEDDED_CLIENT_ID = "56";- static final String WEB_EMBEDDED_CLIENT_NAME = "WEB_EMBEDDED_PLAYER";- static final String WEB_EMBEDDED_CLIENT_VERSION = "1.20260122.01.00";-- // WEB_MUSIC_ANALYTICS (YouTube charts)-- static final String WEB_MUSIC_ANALYTICS_CLIENT_ID = "31";- static final String WEB_MUSIC_ANALYTICS_CLIENT_NAME = "WEB_MUSIC_ANALYTICS";- static final String WEB_MUSIC_ANALYTICS_CLIENT_VERSION = "2.0";-- // IOS (iOS YouTube app) client fields-- static final String IOS_CLIENT_ID = "5";- static final String IOS_CLIENT_NAME = "IOS";-- /**- * The hardcoded client version of the iOS app used for InnerTube requests with this client.- *- * <p>- * It can be extracted by getting the latest release version of the app on- * <a href="https://apps.apple.com/us/app/youtube/id544007664">the App- * Store page of the YouTube app</a>, in the {@code What’s New} section.- * </p>- */- static final String IOS_CLIENT_VERSION = "21.03.2";-- /**- * The device machine id for the iPhone 15 Pro Max, used to get 60fps with the {@code iOS}- * client.- *- * <p>- * See <a href="https://gist.github.com/adamawolf/3048717">this GitHub Gist</a> for more- * information.- * </p>- */- static final String IOS_DEVICE_MODEL = "iPhone16,2";-- /**- * The iOS version to be used in JSON POST requests, the one of an iPhone 15 Pro Max running- * iOS 18.2.1 with the hardcoded version of the iOS app (for the {@code "osVersion"} field).- *- * <p>- * The value of this field seems to use the following structure:- * "iOS major version.minor version.patch version.build version", where- * "patch version" is equal to 0 if it isn't set- * The build version corresponding to the iOS version used can be found on- * <a href="https://theapplewiki.com/wiki/Firmware/iPhone/18.x#iPhone_15_Pro_Max">- * https://theapplewiki.com/wiki/Firmware/iPhone/18.x#iPhone_15_Pro_Max</a>- * </p>- *- * @see #IOS_USER_AGENT_VERSION- */- static final String IOS_OS_VERSION = "18.7.2.22H124";-- /**- * The iOS version to be used in the HTTP user agent for requests.- *- * <p>- * This should be the same of as {@link #IOS_OS_VERSION}.- * </p>- *- * @see #IOS_OS_VERSION- */- static final String IOS_USER_AGENT_VERSION = "18_7_2";-- // ANDROID (Android YouTube app) client fields-- static final String ANDROID_CLIENT_ID = "3";- static final String ANDROID_CLIENT_NAME = "ANDROID";-- /**- * The hardcoded client version of the Android app used for InnerTube requests with this- * client.- *- * <p>- * It can be extracted by getting the latest release version of the app in an APK repository- * such as <a href="https://www.apkmirror.com/apk/google-inc/youtube/">APKMirror</a>.- * </p>- */- static final String ANDROID_CLIENT_VERSION = "21.03.36";-- // visionOS client fields-- static final String VISIONOS_CLIENT_ID = "101";- static final String VISIONOS_CLIENT_NAME = "VISIONOS";- static final String VISIONOS_CLIENT_VERSION = "1.02";- static final String VISIONOS_DEVICE_MODEL = "RealityDevice14,1";- static final String VISIONOS_VERSION = "25.6.0.23O471";- static final String VISIONOS_USER_AGENT_VERSION = "25_6_0";-}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/InnertubeClientRequestInfo.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/InnertubeClientRequestInfo.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/InnertubeClientRequestInfo.javadeleted file mode 100644index 80f84bde83..0000000000--- a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/InnertubeClientRequestInfo.java+++ /dev/null@@ -1,159 +0,0 @@-package org.schabi.newpipe.extractor.services.youtube;--import javax.annotation.Nonnull;-import javax.annotation.Nullable;--import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.ANDROID_CLIENT_ID;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.ANDROID_CLIENT_NAME;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.ANDROID_CLIENT_VERSION;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.DESKTOP_CLIENT_PLATFORM;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.EMBED_CLIENT_SCREEN;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.IOS_CLIENT_ID;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.IOS_CLIENT_NAME;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.IOS_CLIENT_VERSION;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.IOS_DEVICE_MODEL;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.IOS_OS_VERSION;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.MOBILE_CLIENT_PLATFORM;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.VISIONOS_CLIENT_ID;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.VISIONOS_CLIENT_NAME;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.VISIONOS_CLIENT_VERSION;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.VISIONOS_DEVICE_MODEL;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.VISIONOS_VERSION;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.WATCH_CLIENT_SCREEN;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.WEB_CLIENT_ID;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.WEB_CLIENT_NAME;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.WEB_EMBEDDED_CLIENT_ID;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.WEB_EMBEDDED_CLIENT_NAME;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.WEB_EMBEDDED_CLIENT_VERSION;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.WEB_HARDCODED_CLIENT_VERSION;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.WEB_MUSIC_ANALYTICS_CLIENT_ID;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.WEB_MUSIC_ANALYTICS_CLIENT_NAME;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.WEB_MUSIC_ANALYTICS_CLIENT_VERSION;--// TODO: add docs--public final class InnertubeClientRequestInfo {-- @Nonnull- public ClientInfo clientInfo;- @Nonnull- public DeviceInfo deviceInfo;-- public static final class ClientInfo {-- @Nonnull- public String clientName;- @Nonnull- public String clientVersion;- @Nonnull- public String clientId;- @Nullable- public String clientScreen;- @Nullable- public String visitorData;-- private ClientInfo(@Nonnull final String clientName,- @Nonnull final String clientVersion,- @Nonnull final String clientId,- @Nullable final String clientScreen,- @Nullable final String visitorData) {- this.clientName = clientName;- this.clientVersion = clientVersion;- this.clientId = clientId;- this.clientScreen = clientScreen;- this.visitorData = visitorData;- }- }-- public static final class DeviceInfo {-- @Nullable- public String platform;- @Nullable- public String deviceMake;- @Nullable- public String deviceModel;- @Nullable- public String osName;- @Nullable- public String osVersion;- public int androidSdkVersion;-- private DeviceInfo(@Nullable final String platform,- @Nullable final String deviceMake,- @Nullable final String deviceModel,- @Nullable final String osName,- @Nullable final String osVersion,- final int androidSdkVersion) {- this.platform = platform;- this.deviceMake = deviceMake;- this.deviceModel = deviceModel;- this.osName = osName;- this.osVersion = osVersion;- this.androidSdkVersion = androidSdkVersion;- }- }-- private InnertubeClientRequestInfo(@Nonnull final ClientInfo clientInfo,- @Nonnull final DeviceInfo deviceInfo) {- this.clientInfo = clientInfo;- this.deviceInfo = deviceInfo;- }-- @Nonnull- public static InnertubeClientRequestInfo ofWebClient() {- return new InnertubeClientRequestInfo(- new InnertubeClientRequestInfo.ClientInfo(- WEB_CLIENT_NAME, WEB_HARDCODED_CLIENT_VERSION, WEB_CLIENT_ID,- WATCH_CLIENT_SCREEN, null),- new InnertubeClientRequestInfo.DeviceInfo(DESKTOP_CLIENT_PLATFORM, null, null,- null, null, -1));- }-- @Nonnull- public static InnertubeClientRequestInfo ofWebEmbeddedPlayerClient() {- return new InnertubeClientRequestInfo(- new InnertubeClientRequestInfo.ClientInfo(WEB_EMBEDDED_CLIENT_NAME,- WEB_EMBEDDED_CLIENT_VERSION, WEB_EMBEDDED_CLIENT_ID, EMBED_CLIENT_SCREEN,- null),- new InnertubeClientRequestInfo.DeviceInfo(DESKTOP_CLIENT_PLATFORM, null, null,- null, null, -1));- }-- @Nonnull- public static InnertubeClientRequestInfo ofWebMusicAnalyticsChartsClient() {- return new InnertubeClientRequestInfo(- new InnertubeClientRequestInfo.ClientInfo(WEB_MUSIC_ANALYTICS_CLIENT_NAME,- WEB_MUSIC_ANALYTICS_CLIENT_VERSION, WEB_MUSIC_ANALYTICS_CLIENT_ID, null,- null),- new InnertubeClientRequestInfo.DeviceInfo(null, null, null,- null, null, -1));- }-- @Nonnull- public static InnertubeClientRequestInfo ofAndroidClient() {- return new InnertubeClientRequestInfo(- new InnertubeClientRequestInfo.ClientInfo(ANDROID_CLIENT_NAME,- ANDROID_CLIENT_VERSION, ANDROID_CLIENT_ID, WATCH_CLIENT_SCREEN, null),- new InnertubeClientRequestInfo.DeviceInfo(MOBILE_CLIENT_PLATFORM, null, null,- "Android", "16", 36));- }-- @Nonnull- public static InnertubeClientRequestInfo ofIosClient() {- return new InnertubeClientRequestInfo(- new InnertubeClientRequestInfo.ClientInfo(IOS_CLIENT_NAME, IOS_CLIENT_VERSION,- IOS_CLIENT_ID, WATCH_CLIENT_SCREEN, null),- new InnertubeClientRequestInfo.DeviceInfo(MOBILE_CLIENT_PLATFORM, "Apple",- IOS_DEVICE_MODEL, "iOS", IOS_OS_VERSION, -1));- }-- @Nonnull- public static InnertubeClientRequestInfo ofVisionOsClient() {- return new InnertubeClientRequestInfo(- new InnertubeClientRequestInfo.ClientInfo(VISIONOS_CLIENT_NAME,- VISIONOS_CLIENT_VERSION, VISIONOS_CLIENT_ID, WATCH_CLIENT_SCREEN, null),- new InnertubeClientRequestInfo.DeviceInfo(MOBILE_CLIENT_PLATFORM, "Apple",- VISIONOS_DEVICE_MODEL, "visionOS", VISIONOS_VERSION, -1));- }-}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/ItagItem.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/ItagItem.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/ItagItem.javadeleted file mode 100644index 79858ae591..0000000000--- a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/ItagItem.java+++ /dev/null@@ -1,727 +0,0 @@-package org.schabi.newpipe.extractor.services.youtube;--import org.schabi.newpipe.extractor.MediaFormat;-import org.schabi.newpipe.extractor.exceptions.ParsingException;-import org.schabi.newpipe.extractor.stream.AudioTrackType;--import javax.annotation.Nonnull;-import javax.annotation.Nullable;-import java.io.Serializable;-import java.util.Locale;--import static org.schabi.newpipe.extractor.MediaFormat.M4A;-import static org.schabi.newpipe.extractor.MediaFormat.MPEG_4;-import static org.schabi.newpipe.extractor.MediaFormat.WEBM;-import static org.schabi.newpipe.extractor.MediaFormat.WEBMA;-import static org.schabi.newpipe.extractor.MediaFormat.WEBMA_OPUS;-import static org.schabi.newpipe.extractor.MediaFormat.v3GPP;-import static org.schabi.newpipe.extractor.services.youtube.ItagItem.ItagType.AUDIO;-import static org.schabi.newpipe.extractor.services.youtube.ItagItem.ItagType.VIDEO;-import static org.schabi.newpipe.extractor.services.youtube.ItagItem.ItagType.VIDEO_ONLY;--public class ItagItem implements Serializable {-- /**- * List can be found here:- * https://github.com/ytdl-org/youtube-dl/blob/e988fa4/youtube_dl/extractor/youtube.py#L1195- */- private static final ItagItem[] ITAG_LIST = {- /////////////////////////////////////////////////////- // VIDEO ID Type Format Resolution FPS ////- /////////////////////////////////////////////////////- new ItagItem(17, VIDEO, v3GPP, "144p"),- new ItagItem(36, VIDEO, v3GPP, "240p"),-- new ItagItem(18, VIDEO, MPEG_4, "360p"),- new ItagItem(34, VIDEO, MPEG_4, "360p"),- new ItagItem(35, VIDEO, MPEG_4, "480p"),- new ItagItem(59, VIDEO, MPEG_4, "480p"),- new ItagItem(78, VIDEO, MPEG_4, "480p"),- new ItagItem(22, VIDEO, MPEG_4, "720p"),- new ItagItem(37, VIDEO, MPEG_4, "1080p"),- new ItagItem(38, VIDEO, MPEG_4, "1080p"),-- new ItagItem(43, VIDEO, WEBM, "360p"),- new ItagItem(44, VIDEO, WEBM, "480p"),- new ItagItem(45, VIDEO, WEBM, "720p"),- new ItagItem(46, VIDEO, WEBM, "1080p"),-- //////////////////////////////////////////////////////////////////- // AUDIO ID ItagType Format Bitrate //- //////////////////////////////////////////////////////////////////- new ItagItem(171, AUDIO, WEBMA, 128),- new ItagItem(172, AUDIO, WEBMA, 256),- new ItagItem(599, AUDIO, M4A, 32),- new ItagItem(139, AUDIO, M4A, 48),- new ItagItem(140, AUDIO, M4A, 128),- new ItagItem(141, AUDIO, M4A, 256),- new ItagItem(600, AUDIO, WEBMA_OPUS, 35),- new ItagItem(249, AUDIO, WEBMA_OPUS, 50),- new ItagItem(250, AUDIO, WEBMA_OPUS, 70),- new ItagItem(251, AUDIO, WEBMA_OPUS, 160),-- /// VIDEO ONLY ////////////////////////////////////////////- // ID Type Format Resolution FPS ////- ///////////////////////////////////////////////////////////- new ItagItem(160, VIDEO_ONLY, MPEG_4, "144p"),- new ItagItem(394, VIDEO_ONLY, MPEG_4, "144p"),- new ItagItem(133, VIDEO_ONLY, MPEG_4, "240p"),- new ItagItem(395, VIDEO_ONLY, MPEG_4, "240p"),- new ItagItem(134, VIDEO_ONLY, MPEG_4, "360p"),- new ItagItem(396, VIDEO_ONLY, MPEG_4, "360p"),- new ItagItem(135, VIDEO_ONLY, MPEG_4, "480p"),- new ItagItem(212, VIDEO_ONLY, MPEG_4, "480p"),- new ItagItem(397, VIDEO_ONLY, MPEG_4, "480p"),- new ItagItem(136, VIDEO_ONLY, MPEG_4, "720p"),- new ItagItem(398, VIDEO_ONLY, MPEG_4, "720p"),- new ItagItem(298, VIDEO_ONLY, MPEG_4, "720p60", 60),- new ItagItem(137, VIDEO_ONLY, MPEG_4, "1080p"),- new ItagItem(399, VIDEO_ONLY, MPEG_4, "1080p"),- new ItagItem(299, VIDEO_ONLY, MPEG_4, "1080p60", 60),- new ItagItem(400, VIDEO_ONLY, MPEG_4, "1440p"),- new ItagItem(266, VIDEO_ONLY, MPEG_4, "2160p"),- new ItagItem(401, VIDEO_ONLY, MPEG_4, "2160p"),-- new ItagItem(278, VIDEO_ONLY, WEBM, "144p"),- new ItagItem(242, VIDEO_ONLY, WEBM, "240p"),- new ItagItem(243, VIDEO_ONLY, WEBM, "360p"),- new ItagItem(244, VIDEO_ONLY, WEBM, "480p"),- new ItagItem(245, VIDEO_ONLY, WEBM, "480p"),- new ItagItem(246, VIDEO_ONLY, WEBM, "480p"),- new ItagItem(247, VIDEO_ONLY, WEBM, "720p"),- new ItagItem(248, VIDEO_ONLY, WEBM, "1080p"),- new ItagItem(271, VIDEO_ONLY, WEBM, "1440p"),- // #272 is either 3840x2160 (e.g. RtoitU2A-3E) or 7680x4320 (sLprVF6d7Ug)- new ItagItem(272, VIDEO_ONLY, WEBM, "2160p"),- new ItagItem(302, VIDEO_ONLY, WEBM, "720p60", 60),- new ItagItem(303, VIDEO_ONLY, WEBM, "1080p60", 60),- new ItagItem(308, VIDEO_ONLY, WEBM, "1440p60", 60),- new ItagItem(313, VIDEO_ONLY, WEBM, "2160p"),- new ItagItem(315, VIDEO_ONLY, WEBM, "2160p60", 60)- };-- /*//////////////////////////////////////////////////////////////////////////- // Utils- //////////////////////////////////////////////////////////////////////////*/-- public static boolean isSupported(final int itag) {- for (final ItagItem item : ITAG_LIST) {- if (itag == item.id) {- return true;- }- }- return false;- }-- @Nonnull- public static ItagItem getItag(final int itagId) throws ParsingException {- for (final ItagItem item : ITAG_LIST) {- if (itagId == item.id) {- return new ItagItem(item);- }- }- throw new ParsingException("itag " + itagId + " is not supported");- }-- /*//////////////////////////////////////////////////////////////////////////- // Static constants- //////////////////////////////////////////////////////////////////////////*/-- public static final int AVERAGE_BITRATE_UNKNOWN = -1;- public static final int SAMPLE_RATE_UNKNOWN = -1;- public static final int FPS_NOT_APPLICABLE_OR_UNKNOWN = -1;- public static final int TARGET_DURATION_SEC_UNKNOWN = -1;- public static final int AUDIO_CHANNELS_NOT_APPLICABLE_OR_UNKNOWN = -1;- public static final long CONTENT_LENGTH_UNKNOWN = -1;- public static final long APPROX_DURATION_MS_UNKNOWN = -1;- public static final long LAST_MODIFIED_UNKOWN = -1;-- /*//////////////////////////////////////////////////////////////////////////- // Constructors and misc- //////////////////////////////////////////////////////////////////////////*/-- public enum ItagType {- AUDIO,- VIDEO,- VIDEO_ONLY- }-- /**- * Call {@link #ItagItem(int, ItagType, MediaFormat, String, int)} with the fps set to 30.- */- public ItagItem(final int id,- final ItagType type,- final MediaFormat format,- final String resolution) {- this.id = id;- this.itagType = type;- this.mediaFormat = format;- this.resolutionString = resolution;- this.fps = 30;- }-- /**- * Constructor for videos.- */- public ItagItem(final int id,- final ItagType type,- final MediaFormat format,- final String resolution,- final int fps) {- this.id = id;- this.itagType = type;- this.mediaFormat = format;- this.resolutionString = resolution;- this.fps = fps;- }-- public ItagItem(final int id,- final ItagType type,- final MediaFormat format,- final int avgBitrate) {- this.id = id;- this.itagType = type;- this.mediaFormat = format;- this.avgBitrate = avgBitrate;- }-- /**- * Copy constructor of the {@link ItagItem} class.- *- * @param itagItem the {@link ItagItem} to copy its properties into a new {@link ItagItem}- */- public ItagItem(@Nonnull final ItagItem itagItem) {- this.mediaFormat = itagItem.mediaFormat;- this.id = itagItem.id;- this.itagType = itagItem.itagType;- this.avgBitrate = itagItem.avgBitrate;- this.sampleRate = itagItem.sampleRate;- this.audioChannels = itagItem.audioChannels;- this.resolutionString = itagItem.resolutionString;- this.fps = itagItem.fps;- this.bitrate = itagItem.bitrate;- this.width = itagItem.width;- this.height = itagItem.height;- this.initStart = itagItem.initStart;- this.initEnd = itagItem.initEnd;- this.indexStart = itagItem.indexStart;- this.indexEnd = itagItem.indexEnd;- this.quality = itagItem.quality;- this.codec = itagItem.codec;- this.targetDurationSec = itagItem.targetDurationSec;- this.approxDurationMs = itagItem.approxDurationMs;- this.contentLength = itagItem.contentLength;- this.audioTrackId = itagItem.audioTrackId;- this.audioTrackName = itagItem.audioTrackName;- this.audioTrackType = itagItem.audioTrackType;- this.audioLocale = itagItem.audioLocale;- }-- public MediaFormat getMediaFormat() {- return mediaFormat;- }-- private final MediaFormat mediaFormat;-- public final int id;- public final ItagType itagType;-- // Audio fields- /**- * @deprecated Use {@link #getAverageBitrate()} instead.- */- @Deprecated- public int avgBitrate = AVERAGE_BITRATE_UNKNOWN;- private int sampleRate = SAMPLE_RATE_UNKNOWN;- private int audioChannels = AUDIO_CHANNELS_NOT_APPLICABLE_OR_UNKNOWN;-- // Video fields- /**- * @deprecated Use {@link #getResolutionString()} instead.- */- @Deprecated- public String resolutionString;-- /**- * @deprecated Use {@link #getFps()} and {@link #setFps(int)} instead.- */- @Deprecated- public int fps = FPS_NOT_APPLICABLE_OR_UNKNOWN;-- // Fields for Dash- private int bitrate;- private int width;- private int height;- private int initStart;- private int initEnd;- private int indexStart;- private int indexEnd;- private String quality;- private String codec;- private int targetDurationSec = TARGET_DURATION_SEC_UNKNOWN;- private long approxDurationMs = APPROX_DURATION_MS_UNKNOWN;- private long contentLength = CONTENT_LENGTH_UNKNOWN;- private String audioTrackId;- private String audioTrackName;- @Nullable- private AudioTrackType audioTrackType;- @Nullable- private Locale audioLocale;- private boolean isDrc;- private long lastModified;- private String xtags;-- public int getBitrate() {- return bitrate;- }-- public void setBitrate(final int bitrate) {- this.bitrate = bitrate;- }-- public int getWidth() {- return width;- }-- public void setWidth(final int width) {- this.width = width;- }-- public int getHeight() {- return height;- }-- public void setHeight(final int height) {- this.height = height;- }-- /**- * Get the frame rate.- *- * <p>- * It is set to the {@code fps} value returned in the corresponding itag in the YouTube player- * response.- * </p>- *- * <p>-
Diff truncated.