package no.zyon.shade import no.zyon.shade.media.Album import no.zyon.shade.media.Albums import no.zyon.shade.media.FileRangeSource import no.zyon.shade.media.Grants import no.zyon.shade.media.MediaGrant import no.zyon.shade.media.MediaMeta import no.zyon.shade.media.MediaOwner import no.zyon.shade.media.MediaSealer import no.zyon.shade.media.MediaUploader import no.zyon.shade.media.UploadJobs import org.json.JSONObject import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotEquals import org.junit.Assert.assertTrue import org.junit.Assume.assumeTrue import org.junit.Test import java.io.File import java.security.MessageDigest import java.security.SecureRandom /** * Live cross-check of [MediaUploader] against the real TS relay — skipped * unless `SHADE_MEDIA_LIVE_SPEC` points at the spec file a TS driver wrote. * * Run it via `bun run scripts/media-live-kotlin.ts`: the driver serves * `createMediaService` with two faults injected on the pieces, uploads a file * with the TS client and writes `{ url, seed, tsLink, tsSha256, scratch, * kotlinOut }`. This test opens the TS file, uploads a film in pieces and a * photo in one PUT, and records the links in `kotlinOut`; the driver then * reads the film back with the TS reader. */ class MediaLiveTest { private fun sha256(b: ByteArray) = MessageDigest.getInstance("SHA-256").digest(b).joinToString("") { "%02x".format(it) } private fun fromHex(s: String) = ByteArray(s.length / 2) { ((Character.digit(s[it * 2], 16) shl 4) + Character.digit(s[it * 2 + 1], 16)).toByte() } @Test fun uploadsInPiecesThroughFaultsForTsToRead() { val specPath = System.getenv("SHADE_MEDIA_LIVE_SPEC") assumeTrue("SHADE_MEDIA_LIVE_SPEC not set — live cross-check skipped", !specPath.isNullOrEmpty()) val spec = JSONObject(File(specPath!!).readText()) val uploader = MediaUploader(spec.getString("url"), MediaOwner(fromHex(spec.getString("seed")))) // Read what TS uploaded, from its link. val tsGrant = Grants.fromCapabilityUrl(spec.getString("tsLink")) as MediaGrant tsGrant.open().use { r -> assertEquals(spec.getString("tsSha256"), sha256(r.read(0, r.size.toInt()))) } // A film from the phone: sealed to a file, up in three pieces (16 MiB each), // through a lost answer on the second and a refusal of the third. val plain = ByteArray(40 * 1024 * 1024).also { SecureRandom().nextBytes(it) } val sealedFile = File(spec.getString("scratch"), "film.smf") val meta = MediaMeta(name = "Fra telefonen — «Kveld».mp4", mime = "video/mp4", durationMs = 61_500, width = 1080, height = 1920) val progress = mutableListOf() val token = MediaUploader.newReadToken() val result = sealedFile.outputStream().buffered().use { MediaSealer.sealStream(plain.inputStream(), it, meta) } val film = FileRangeSource(sealedFile).use { body -> uploader.putSealed(result, body, token, meta) { acked, total -> synchronized(progress) { progress += acked } assertEquals(result.sealedSize, total) } } assertEquals(result.sealedSize, progress.last()) assertTrue("progress only grows: $progress", progress.zipWithNext().all { (a, b) -> a <= b }) film.open().use { r -> assertEquals(sha256(plain), sha256(r.read(0, r.size.toInt()))) } // The same film again (the app was killed after the upload): the relay // already has it, nothing is sent, the link is the same. val again = FileRangeSource(sealedFile).use { uploader.putSealed(result, it, token, meta) } assertEquals(film.capabilityUrl("https://watch.example/"), again.capabilityUrl("https://watch.example/")) // A shared video as an upload job: the app is killed after the first // piece; the next start resumes past it, and sharing it a third time // sends nothing and gives the same link. val jobs = UploadJobs(File(spec.getString("scratch"), "jobs")) val video = ByteArray(36 * 1024 * 1024).also { SecureRandom().nextBytes(it) } val key = jobs.key(spec.getString("url"), "content://media/external/video/42", video.size.toString()) val videoMeta = MediaMeta(name = "VID_0042.mp4", mime = "video/mp4") var opened = 0 val open = { opened++; video.inputStream() } class Killed : RuntimeException() try { uploader.upload(jobs, key, "VID_0042.mp4", videoMeta, open) { acked, _ -> if (acked > 0) throw Killed() } error("the upload should have been cut short") } catch (e: Killed) { // as if the app was killed mid-upload } assertEquals(1, jobs.unfinished().size) var firstSeen = -1L val resumed = uploader.upload(jobs, key, "VID_0042.mp4", videoMeta, open) { acked, _ -> if (firstSeen < 0) firstSeen = acked } assertTrue("resumed from $firstSeen", firstSeen > 0) assertEquals("sealed once", 1, opened) resumed.open().use { r -> assertEquals(sha256(video), sha256(r.read(0, r.size.toInt()))) } val third = uploader.upload(jobs, key, "VID_0042.mp4", videoMeta, open) assertEquals(resumed.encode(), third.encode()) assertEquals(1, opened) assertTrue(jobs.unfinished().isEmpty()) // Deleted from the relay since: the next share is a new upload with a new link. assertTrue(uploader.delete(resumed.mediaId)) val fresh = uploader.upload(jobs, key, "VID_0042.mp4", videoMeta, open) assertNotEquals(resumed.encode(), fresh.encode()) assertEquals(2, opened) // A photo: one PUT; then deleted. val photo = uploader.uploadBytes(ByteArray(300_000).also { SecureRandom().nextBytes(it) }, MediaMeta(name = "IMG_0001.jpg", mime = "image/jpeg")) photo.open().use { assertEquals("IMG_0001.jpg", it.meta.name) } assertTrue(uploader.delete(photo.mediaId)) assertFalse(uploader.delete(photo.mediaId)) // The photos of a trip, shared at once: one album link for all of them. val album = uploader.uploadAlbum(Album("Tur — «Lofoten»", listOf(film, fresh))) album.open().use { r -> val back = Albums.read(r) assertEquals("Tur — «Lofoten»", back.title) assertEquals(listOf(film.encode(), fresh.encode()), back.items.map { it.encode() }) } File(spec.getString("kotlinOut")).writeText( JSONObject() .put("film", JSONObject().put("link", film.capabilityUrl("https://watch.example/")).put("sha256", sha256(plain)).put("size", plain.size)) .put("again", again.capabilityUrl("https://watch.example/")) .put("photo", JSONObject().put("url", photo.url)) .put("album", album.capabilityUrl("https://watch.example/")) .toString(), ) sealedFile.delete() } }