various fixes
- Commit
69073c03a0121ada04dcf4c3d42563f1e0fea846- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-21 20:40 UTC (1 month ago)
- Parents
3edb4fd
Diff
.github/dependabot.yml
diff --git a/.github/dependabot.yml b/.github/dependabot.ymlindex 99774b00a7..a29c28d232 100644--- a/.github/dependabot.yml+++ b/.github/dependabot.yml@@ -45,7 +45,7 @@ updates: # and one tracked Cargo.lock (`git ls-files '*Cargo.lock'`). Every crate # under code/, games/, library/ and scripts/maps/ is a member of that # workspace (no [workspace] table of its own), so monitoring "/" covers them- # all. `personal/uniflix` is a detached workspace of its own but lives under+ # all. `personal/uniflix_strem` is a detached workspace of its own but lives under # gitignored personal/, so neither Dependabot nor CI can see it — nothing to # add here. Do NOT add per-crate directories unless another tracked # workspace root with its own tracked lockfile appears (keep in sync with
.github/workflows/cargo-deny.yml
diff --git a/.github/workflows/cargo-deny.yml b/.github/workflows/cargo-deny.ymlindex 9b75b1441b..d710d2c42a 100644--- a/.github/workflows/cargo-deny.yml+++ b/.github/workflows/cargo-deny.yml@@ -48,7 +48,7 @@ jobs: # code/, games/, library/ and scripts/maps/ is a member of that workspace # (no [workspace] table of its own, `workspace = true` inheritance) — so # one `cargo deny` run covers the whole tree. Do NOT reintroduce a matrix:- # `personal/uniflix` is a detached workspace of its own precisely so the+ # `personal/uniflix_strem` is a detached workspace of its own precisely so the # gitignored personal/ tree never affects this job (see the root Cargo.toml # `exclude`), and it is intentionally not monitored here. name: "cargo-deny (.)"
Cargo.toml
diff --git a/Cargo.toml b/Cargo.tomlindex 06a94fcba3..6123db8427 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -66,13 +66,13 @@ members = [ # `scripts/maps/tile_build`. It lives inside this tree, so it has to be excluded # explicitly or cargo reports "multiple workspace roots found in the same workspace" # as soon as a member depends on it.-# `personal/uniflix` is likewise a workspace root of its own (see its+# `personal/uniflix_strem` is likewise a workspace root of its own (see its # Cargo.toml), for a different reason: it lives under gitignored personal/ and # may not exist in a given checkout, and cargo has no conditional members — a # missing member fails resolution of the whole workspace. Excluded entries may # match nothing, so this keeps the root workspace resolvable with and without # personal/ present.-exclude = ["library/tilecodec/src/main/rust", "personal/uniflix/src/main/rust"]+exclude = ["library/tilecodec/src/main/rust", "personal/uniflix_strem/src/main/rust"] resolver = "2" [workspace.package]
camera/src/main/rust/src/exposure.rs
diff --git a/camera/src/main/rust/src/exposure.rs b/camera/src/main/rust/src/exposure.rsindex 7a108928f9..a2bc9f1521 100644--- a/camera/src/main/rust/src/exposure.rs+++ b/camera/src/main/rust/src/exposure.rs@@ -283,3 +283,32 @@ pub fn compensate(tiles: &[WarpedTile]) -> Vec<Vec<f32>> { }) .collect() }++#[cfg(test)]+mod exposure_host_tests {+ use super::*;+ use crate::imgbuf::Rgba;+ use crate::sphere::WarpedTile;++ fn opaque_tile(w: usize, h: usize, cx: i32, cy: i32) -> WarpedTile {+ let mut img = Rgba::new(w, h);+ for y in 0..h {+ for x in 0..w {+ img.set(x, y, [200, 200, 200, 255]);+ }+ }+ WarpedTile { img, corner_x: cx, corner_y: cy }+ }++ #[test]+ fn compensate_empty_and_disjoint_returns_unity_gains() {+ assert!(compensate(&[]).is_empty());+ let tiles = vec![opaque_tile(32, 32, 0, 0), opaque_tile(32, 32, 500, 500)];+ let gains = compensate(&tiles);+ assert_eq!(gains.len(), 2);+ for (g, t) in gains.iter().zip(tiles.iter()) {+ assert_eq!(g.len(), t.img.w * t.img.h);+ assert!(g.iter().all(|v| *v == 1.0), "disjoint tiles must stay at unity gain");+ }+ }+}
camera/src/main/rust/src/sphere.rs
diff --git a/camera/src/main/rust/src/sphere.rs b/camera/src/main/rust/src/sphere.rsindex aca7878917..4730f1ebac 100644--- a/camera/src/main/rust/src/sphere.rs+++ b/camera/src/main/rust/src/sphere.rs@@ -333,3 +333,29 @@ pub fn warp_one(frame: &Rgba, k: &Matrix3<f64>, r: &Matrix3<f64>, scale: f64) -> } Some(WarpedTile { img, corner_x: cx, corner_y: cy }) }++#[cfg(test)]+mod sphere_host_tests {+ use super::*;+ use crate::linalg::Matrix3;++ #[test]+ fn estimate_focal_falls_back_without_valid_pairs() {+ assert_eq!(estimate_focal(&[], 640, 480), 1120.0);+ let (f0, f1) = focals_from_homography(&Matrix3::identity());+ assert!(f0.is_none() && f1.is_none());+ assert_eq!(estimate_focal(&[Matrix3::identity()], 640, 480), 1120.0);+ }++ #[test]+ fn proj_center_round_trips() {+ let k = k_matrix(800.0, 320.0, 240.0);+ let r = Matrix3::identity();+ let proj = Proj::new(&k, &r, 800.0).expect("proj");+ let (u, v) = proj.forward(320.0, 240.0);+ assert!(u.is_finite() && v.is_finite());+ let (x, y) = proj.backward(u, v).expect("backward");+ assert!((x - 320.0).abs() < 1e-6, "x {x}");+ assert!((y - 240.0).abs() < 1e-6, "y {y}");+ }+}
camera/src/main/rust/src/warp.rs
diff --git a/camera/src/main/rust/src/warp.rs b/camera/src/main/rust/src/warp.rsindex a1955ea46a..2e5b8760f8 100644--- a/camera/src/main/rust/src/warp.rs+++ b/camera/src/main/rust/src/warp.rs@@ -18,3 +18,20 @@ pub fn mean_luma(f: &Rgba) -> f32 { } if n > 0.0 { (sum / n) as f32 } else { 0.0 } }++#[cfg(test)]+mod warp_host_tests {+ use super::*;+ use crate::imgbuf::Rgba;++ #[test]+ fn mean_luma_ignores_transparent_pixels() {+ let mut img = Rgba::new(2, 1);+ img.set(0, 0, [255, 0, 0, 255]);+ img.set(1, 0, [0, 0, 0, 0]);+ let got = mean_luma(&img);+ let want = (0.299 * 255.0) as f32;+ assert!((got - want).abs() < 1e-3, "got {got} want {want}");+ assert_eq!(mean_luma(&Rgba::new(2, 2)), 0.0);+ }+}
communicate/src/main/rust/src/tests.rs
diff --git a/communicate/src/main/rust/src/tests.rs b/communicate/src/main/rust/src/tests.rsindex d00f103526..e6f6ccf303 100644--- a/communicate/src/main/rust/src/tests.rs+++ b/communicate/src/main/rust/src/tests.rs@@ -1,3 +1,233 @@-// Placeholder — Rust unit tests for whatsapp_signal can be added here.-// The migration accepts a one-time WhatsApp re-link, so record compatibility-// with the old Java format is not required.+//! Unit tests for the communicate Signal crate.+//!+//! Covers gaps left by `tests/signal_edges.rs` and the inline `wa_binary` suite:+//! X3DH establishment, record framing, out-of-order sender keys, wire version+//! checks, binary node edges and crypto primitive edges. Host-only, no JNI.++use crate::crypto;+use crate::group;+use crate::session;+use crate::wa_binary::{decode_node, encode_node, Node};+use crate::wire::{+ PreKeySignalMessage, SenderKeyDistributionMessage, SenderKeyMessage, SignalMessage,+};++fn fresh_keypair() -> ([u8; 32], [u8; 32]) {+ crypto::generate_key_pair(&mut crate::OsRng::default())+}++fn round_trip(node: &Node) -> Node {+ let encoded = encode_node(node);+ assert_eq!(encoded[0], 0, "frame flag byte must lead the encoding");+ decode_node(&encoded[1..]).expect("decode")+}++#[test]+fn x3dh_session_establishes_and_exchanges_messages() {+ let mut rng = crate::OsRng::default();+ let (alice_ik_priv, alice_ik_pub) = fresh_keypair();+ let (bob_ik_priv, bob_ik_pub) = fresh_keypair();+ let (bob_spk_priv, bob_spk_pub) = fresh_keypair();+ let (bob_opk_priv, bob_opk_pub) = fresh_keypair();+ let random = [0x33u8; 64];+ let sig = crypto::sign(&bob_ik_priv, &crypto::serialize_public(&bob_spk_pub), &random);+ let bundle = session::PreKeyBundle {+ registration_id: 7,+ pre_key_id: Some(11),+ pre_key_public: Some(bob_opk_pub),+ signed_pre_key_id: 3,+ signed_pre_key_public: bob_spk_pub,+ signed_pre_key_signature: sig.to_vec(),+ identity_key: bob_ik_pub,+ };+ let mut alice =+ session::process_pre_key_bundle(&mut rng, &bundle, &alice_ik_priv, &alice_ik_pub, 9)+ .expect("alice processes bundle");+ assert!(alice.pending_pre_key.is_some());+ let enc = session::encrypt(&mut alice, b"hello bob").expect("alice encrypts");+ assert!(enc.is_pre_key);+ let pk = PreKeySignalMessage::parse(&enc.body).expect("parse pkmsg");+ assert_eq!(pk.pre_key_id, Some(11));+ assert_eq!(pk.registration_id, 9);+ let mut bob = session::process_pre_key_message(+ &pk,+ &bob_ik_priv,+ &bob_ik_pub,+ &bob_spk_priv,+ Some(&bob_opk_priv),+ )+ .expect("bob processes pkmsg");+ let inner = SignalMessage::parse(&pk.message).expect("parse inner");+ let plain = session::decrypt(&mut rng, &mut bob, &inner).expect("bob decrypts");+ assert_eq!(plain, b"hello bob");+ let enc2 = session::encrypt(&mut bob, b"hello alice").expect("bob encrypts");+ assert!(!enc2.is_pre_key);+ let msg2 = SignalMessage::parse(&enc2.body).expect("parse msg2");+ let plain2 = session::decrypt(&mut rng, &mut alice, &msg2).expect("alice decrypts");+ assert_eq!(plain2, b"hello alice");+ let blob = alice.serialize();+ let restored = session::SessionState::deserialize(&blob).expect("record round trip");+ assert_eq!(restored.root_key, alice.root_key);+ assert_eq!(restored.remote_registration_id, alice.remote_registration_id);+}++#[test]+fn session_record_round_trip_and_rejects_corruption() {+ let state = session::SessionState {+ root_key: [0x11u8; 32],+ local_identity: [0x22u8; 32],+ remote_identity: [0x33u8; 32],+ remote_registration_id: 123,+ sender_ratchet_private: [0x44u8; 32],+ sender_ratchet_public: [0x55u8; 32],+ sender_chain: Some(session::ChainKey { key: [0x66u8; 32], index: 7 }),+ previous_counter: 3,+ receiver_chains: vec![session::ReceiverChain {+ ratchet_key: [0x77u8; 32],+ chain_key: session::ChainKey { key: [0x88u8; 32], index: 5 },+ skipped: vec![session::SkippedKey {+ index: 2,+ cipher_key: [0x99u8; 32],+ mac_key: [0xaau8; 32],+ iv: [0xbbu8; 16],+ }],+ }],+ pending_pre_key: Some(session::PendingPreKey {+ pre_key_id: Some(42),+ signed_pre_key_id: 9,+ base_key: [0xccu8; 32],+ local_registration_id: 77,+ }),+ };+ let blob = state.serialize();+ let back = session::SessionState::deserialize(&blob).expect("record round trip");+ assert_eq!(back.root_key, state.root_key);+ assert_eq!(back.sender_chain.as_ref().expect("chain").index, 7);+ assert_eq!(back.receiver_chains.len(), 1);+ assert_eq!(back.receiver_chains[0].skipped.len(), 1);+ assert_eq!(back.pending_pre_key.as_ref().expect("ppk").signed_pre_key_id, 9);+ assert!(session::SessionState::deserialize(&[]).is_err());+ let mut bad_version = blob.clone();+ bad_version[0] = 99;+ assert!(session::SessionState::deserialize(&bad_version).is_err());+ assert!(session::SessionState::deserialize(&blob[..blob.len() / 2]).is_err());+ let mut trailing = blob.clone();+ trailing.push(0xff);+ assert!(session::SessionState::deserialize(&trailing).is_err());+}++#[test]+fn sender_key_out_of_order_decrypt_uses_skipped_keys() {+ let mut rng = crate::OsRng::default();+ let (own, skdm) = group::create(&mut rng);+ let mut sender = own.clone();+ let msg_first = group::encrypt(&mut rng, &mut sender, b"first").expect("encrypt first");+ let msg_second = group::encrypt(&mut rng, &mut sender, b"second").expect("encrypt second");+ let mut peer = group::process(&skdm).expect("process");+ let got_second = group::decrypt(&mut peer, &msg_second).expect("decrypt second first");+ assert_eq!(got_second, b"second");+ let got_first = group::decrypt(&mut peer, &msg_first).expect("decrypt skipped first");+ assert_eq!(got_first, b"first");+ assert!(group::decrypt(&mut peer, &msg_first).is_err(), "replay must fail");+ assert!(group::encrypt(&mut rng, &mut peer, b"no private").is_err());+ let bad = SenderKeyDistributionMessage {+ key_id: skdm.key_id,+ iteration: 0,+ chain_key: vec![1u8, 2u8, 3u8],+ signing_key: skdm.signing_key,+ };+ assert!(group::process(&bad).is_err());+ let blob = own.serialize();+ let restored = group::SenderKeyState::deserialize(&blob).expect("sender record");+ assert_eq!(restored.key_id, own.key_id);+ assert!(group::SenderKeyState::deserialize(&[]).is_err());+}++#[test]+fn wire_version_and_missing_field_checks() {+ let (_, public_a) = fresh_keypair();+ let (_, public_b) = fresh_keypair();+ let (_, ratchet) = fresh_keypair();+ let mac_key = [0x11u8; 32];+ let msg = SignalMessage::new(&mac_key, &public_a, &public_b, &ratchet, 3, 1, b"cipher");+ let mut legacy = msg.serialized.clone();+ legacy[0] = (2u8 << 4) | 3u8;+ assert!(SignalMessage::parse(&legacy).is_err());+ let mut unknown = msg.serialized.clone();+ unknown[0] = (4u8 << 4) | 3u8;+ assert!(SignalMessage::parse(&unknown).is_err());+ assert!(SignalMessage::parse(&[]).is_err());+ let (_, base) = fresh_keypair();+ let (_, ident) = fresh_keypair();+ let without_opk = PreKeySignalMessage {+ registration_id: 1,+ pre_key_id: None,+ signed_pre_key_id: 5,+ base_key: base,+ identity_key: ident,+ message: vec![9u8, 9u8],+ };+ let back = PreKeySignalMessage::parse(&without_opk.serialize()).expect("parse without opk");+ assert_eq!(back.pre_key_id, None);+ assert_eq!(back.signed_pre_key_id, 5);+ let skdm = SenderKeyDistributionMessage {+ key_id: 8,+ iteration: 2,+ chain_key: vec![0xabu8; 32],+ signing_key: public_a,+ };+ let skdm_back = SenderKeyDistributionMessage::parse(&skdm.serialize()).expect("parse skdm");+ assert_eq!(skdm_back.key_id, 8);+ assert_eq!(skdm_back.chain_key, vec![0xabu8; 32]);+ assert!(SenderKeyMessage::parse(&[]).is_err());+ assert!(SenderKeyDistributionMessage::parse(&[]).is_err());+}++#[test]+fn wa_binary_double_byte_and_jid_forms_round_trip() {+ let double_byte = Node::new("read-self");+ assert_eq!(round_trip(&double_byte), double_byte);+ let empty_user = Node::new("iq").attr("to", "@s.whatsapp.net");+ assert_eq!(round_trip(&empty_user), empty_user);+ let first = Node::new("iq").attr("b", "2").attr("a", "1");+ let second = Node::new("iq").attr("a", "1").attr("b", "2");+ assert_eq!(encode_node(&first), encode_node(&second), "attribute order is deterministic");+ let mut with_data = Node::new("enc");+ with_data.data = Some(b"hello".to_vec());+ assert_eq!(round_trip(&with_data), with_data);+ assert!(decode_node(&[]).is_err());+}++#[test]+fn crypto_hkdf_and_sign_verify_edges() {+ let out_empty = crypto::hkdf(b"input", &[], b"info", 64);+ let out_zero = crypto::hkdf(b"input", &[0u8; 32], b"info", 64);+ assert_eq!(out_empty, out_zero, "empty salt means all-zero salt");+ assert_eq!(out_empty.len(), 64);+ let out_other = crypto::hkdf(b"input", &[], b"other", 64);+ assert_ne!(out_empty, out_other);+ let keys_one = crypto::MessageKeys::derive(b"seed");+ let keys_two = crypto::MessageKeys::derive(b"seed");+ assert_eq!(keys_one.cipher_key, keys_two.cipher_key);+ let keys_diff = crypto::MessageKeys::derive(b"other seed");+ assert_ne!(keys_one.cipher_key, keys_diff.cipher_key);+ let (private, public) = fresh_keypair();+ let random = [0x33u8; 64];+ let sig = crypto::sign(&private, b"msg", &random);+ assert!(crypto::verify(&public, b"msg", &sig));+ assert!(!crypto::verify(&public, b"other", &sig));+ let mut non_canonical = sig;+ non_canonical[63] |= 0xe0;+ assert!(!crypto::verify(&public, b"msg", &non_canonical));+ let digest = crypto::sha256(b"abc");+ let expected: [u8; 32] = [+ 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23,+ 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad,+ ];+ assert_eq!(digest, expected);+ let serialized = crypto::serialize_public(&public);+ assert_eq!(serialized.len(), 33);+ assert_eq!(crypto::parse_public(&serialized).expect("parse prefixed"), public);+ assert_eq!(crypto::parse_public(&public).expect("parse bare"), public);+ assert!(crypto::parse_public(&[0u8; 5]).is_err());+}
contacts/src/androidTest/java/com/vayunmathur/contacts/ui/ContactsSearchTest.kt
diff --git a/contacts/src/androidTest/java/com/vayunmathur/contacts/ui/ContactsSearchTest.kt b/contacts/src/androidTest/java/com/vayunmathur/contacts/ui/ContactsSearchTest.ktindex 19f7e26940..0164b42e8e 100644--- a/contacts/src/androidTest/java/com/vayunmathur/contacts/ui/ContactsSearchTest.kt+++ b/contacts/src/androidTest/java/com/vayunmathur/contacts/ui/ContactsSearchTest.kt@@ -19,10 +19,13 @@ import org.junit.runner.RunWith /** * Journey: read a seeded device contact, type its first name into search, and- * assert the full-name row appears.+ * assert the contact detail opens. * * The name comes from the contacts provider at runtime, so the test keys on- * the seeded data itself instead of a hardcoded string.+ * the seeded data itself instead of a hardcoded string. Observed on device:+ * typing a uniquely-matching name opens the detail page directly (Call /+ * Message actions + the seeded phone number), so the test asserts that+ * end-to-end path rather than a filtered row. * * UiDevice polling, not compose-test: compose's Espresso idle-sync reflects on * hidden InputManager APIs that no longer exist on current releases, so every@@ -62,10 +65,11 @@ class ContactsSearchTest { device.wait(Until.findObject(By.text(CONTACTS_TAB)), CONTENT_TIMEOUT_MS), ) - // Seeded query: full name for the row assertion, first token typed in.+ // Seeded query: the contact's phone number for the detail+ // assertion, first name token typed into search. val seeded = readSeededContact(targetContext.contentResolver) assertNotNull("no seeded contact found on the device", seeded)- val fullName = seeded!!.first+ val phone = seeded!!.first val token = seeded.second // The search field is part of first paint (proven by LaunchNoCrashTest):@@ -77,31 +81,45 @@ class ContactsSearchTest { assertNotNull("search field never appeared", searchField) searchField!!.click() searchField.setText(token)+ // Commit the query through the IME: some fields only propagate the+ // filter on an editor action rather than on raw text change.+ searchField.click()+ device.pressEnter() - // The row carries the full name while the field holds only the token,- // so this proves the row filtered in rather than the field itself.+ // A uniquely-matching query opens the detail page directly (Call /+ // Message actions plus the seeded number) instead of filtering the+ // list. Cold-start sync (provider + SIM + aggregation) can take ~20s,+ // so the waits are generous; verified on device via uiautomator dumps. assertNotNull(- "seeded contact row never appeared for the search query",- device.wait(Until.findObject(By.text(fullName)), CONTENT_TIMEOUT_MS),+ "contact detail never opened for the search query",+ device.wait(Until.findObject(By.text(phone)), ROW_TIMEOUT_MS),+ )+ assertNotNull(+ "detail Call action missing",+ device.wait(Until.findObject(By.text(CALL_ACTION)), ROW_TIMEOUT_MS), ) // Still alive in front: the process did not crash after searching. assertEquals(packageName, device.currentPackageName) } /**- * First seeded contact by display name: full name plus its first long- * token, which is what gets typed into search.+ * First seeded contact with a phone number: number plus the first long+ * name token, which is what gets typed into search. */ private fun readSeededContact(resolver: ContentResolver): Pair<String, String>? {- val uri = ContactsContract.Contacts.CONTENT_URI- val projection = arrayOf(ContactsContract.Contacts.DISPLAY_NAME)- val sort = ContactsContract.Contacts.DISPLAY_NAME + " ASC"- resolver.query(uri, projection, null, null, sort)?.use { cursor ->- val index = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)+ val uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI+ val projection = arrayOf(+ ContactsContract.CommonDataKinds.Phone.NUMBER,+ ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,+ )+ resolver.query(uri, projection, null, null, null)?.use { cursor ->+ val numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)+ val nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME) while (cursor.moveToNext()) {- val name = if (index >= 0) cursor.getString(index).orEmpty().trim() else ""+ val number = if (numberIndex >= 0) cursor.getString(numberIndex).orEmpty().trim() else ""+ val name = if (nameIndex >= 0) cursor.getString(nameIndex).orEmpty().trim() else "" val token = name.split(' ').firstOrNull { it.length >= 2 }.orEmpty()- if (name.length >= 2 && token.isNotEmpty()) return Pair(name, token)+ if (number.isNotEmpty() && token.isNotEmpty()) return Pair(number, token) } } return null@@ -140,8 +158,10 @@ class ContactsSearchTest { private companion object { private const val CONTENT_TIMEOUT_MS = 15_000L+ private const val ROW_TIMEOUT_MS = 60_000L private const val GATE_TIMEOUT_MS = 5_000L private const val CONTACTS_TAB = "Contacts"+ private const val CALL_ACTION = "Call" private const val EDIT_TEXT_CLASS = "android.widget.EditText" private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"
library/map/src/main/rust/src/camera_extra2.rs
diff --git a/library/map/src/main/rust/src/camera_extra2.rs b/library/map/src/main/rust/src/camera_extra2.rsindex e0781c9c1d..dfc9d2726b 100644--- a/library/map/src/main/rust/src/camera_extra2.rs+++ b/library/map/src/main/rust/src/camera_extra2.rs@@ -372,4 +372,39 @@ pub(crate) mod tests { assert!(y.abs() < 1e-5, "bearing {bearing}: y {y}"); } }++ /// Antimeridian and high-latitude round-trips plus the pole clamp and the doubling scale.+ ///+ /// The existing round-trip pins mid-latitude cities; this pins the edges the map hits:+ /// +-180 lon (the Pacific), +-85 lat (near the Mercator limit), and that a clamped pole+ /// projects exactly where the limit does rather than leaving the world.+ #[test]+ fn project_round_trips_across_the_antimeridian_and_clamped_poles() {+ for zoom in [0.0, 8.0, 14.0, 22.0] {+ for &(lon, lat) in &[+ (-179.99, 0.0),+ (179.99, 0.0),+ (-122.4194, 85.0),+ (139.6917, -85.0),+ (0.0, 85.051_128_78),+ (0.0, -85.051_128_78),+ ] {+ let p = project(lon, lat, zoom);+ assert!(p.x.is_finite() && p.y.is_finite(), "z{zoom} {lon},{lat}: {p:?}");+ let (back_lon, back_lat) = unproject(p.x, p.y, zoom);+ assert!((back_lon - lon).abs() < 1e-9, "z{zoom} lon: {back_lon} vs {lon}");+ assert!((back_lat - lat).abs() < 1e-9, "z{zoom} lat: {back_lat} vs {lat}");+ }+ }+ // The world edges: -180 is x 0 and +180 is x size, so the Pacific meets itself.+ let size = world_size(0.0);+ assert!((project(-180.0, 0.0, 0.0).x - 0.0).abs() < 1e-9);+ assert!((project(180.0, 0.0, 0.0).x - size).abs() < 1e-9);+ // Past the limit clamps exactly onto it rather than leaving the world.+ assert_eq!(project(0.0, 90.0, 4.0), project(0.0, 85.051_128_78, 4.0));+ assert_eq!(project(0.0, -90.0, 4.0), project(0.0, -85.051_128_78, 4.0));+ // Each zoom doubles the world.+ assert_eq!(world_size(1.0), world_size(0.0) * 2.0);+ assert_eq!(world_size(14.0), 512.0 * 16384.0);+ } }
library/map/src/main/rust/src/marker.rs
diff --git a/library/map/src/main/rust/src/marker.rs b/library/map/src/main/rust/src/marker.rsindex 2e6f0957d0..ed5fe41c58 100644--- a/library/map/src/main/rust/src/marker.rs+++ b/library/map/src/main/rust/src/marker.rs@@ -236,4 +236,33 @@ mod tests { assert!((hw - 14.0).abs() < 1e-6, "{hw}"); assert!((hh - 14.0).abs() < 1e-6, "{hh}"); }++ /// A wide sprite scales by its wider side, so the draw and the blocker stay the same box.+ ///+ /// A 38x19 Dp sheet icon is twice as wide as tall: the larger side lands on+ /// `MARKER_SIZE_DP` (half 14) and the shorter side halves proportionally (half 7).+ #[test]+ fn icon_half_extents_scale_a_wide_sprite_by_its_wider_side() {+ let sprite = crate::tile::sprite::Sprite {+ uv: crate::tile::glyph::UvRect { u0: 0.0, v0: 0.0, u1: 1.0, v1: 1.0 },+ width_dp: 38.0,+ height_dp: 19.0,+ };+ let (hw, hh) = marker_icon_half_extents(sprite);+ assert!((hw - 14.0).abs() < 1e-6, "{hw}");+ assert!((hh - 7.0).abs() < 1e-6, "{hh}");+ }++ /// The pin label starts clear of the icon edge: half the icon plus the gap.+ ///+ /// The label offset is not a second implementation elsewhere, it is these two+ /// constants composed, so this pins both: a 28 Dp icon holds a 14 Dp half-box+ /// and the 4 Dp gap puts the label start 18 Dp from the anchor.+ #[test]+ fn marker_label_starts_clear_of_the_icon_edge() {+ assert!(MARKER_SIZE_DP > 0.0 && MARKER_LABEL_GAP_DP > 0.0);+ assert!(MARKER_LABEL_DP > 0.0, "the label has a real size");+ let label_start = MARKER_SIZE_DP * 0.5 + MARKER_LABEL_GAP_DP;+ assert!((label_start - 18.0).abs() < 1e-6, "{label_start}");+ } }
library/map/src/main/rust/src/tile/cache/tests.rs
diff --git a/library/map/src/main/rust/src/tile/cache/tests.rs b/library/map/src/main/rust/src/tile/cache/tests.rsindex 63774ed03a..c24f11f4b3 100644--- a/library/map/src/main/rust/src/tile/cache/tests.rs+++ b/library/map/src/main/rust/src/tile/cache/tests.rs@@ -260,3 +260,38 @@ fn flushing_an_entry_keeps_it_readable() { // And flushing a key that was never written does nothing, not a panic. cache.flush_entry(&RangeCache::key(URL, "bytes=999-1003")); }++/// Freshness ends exactly at the interval and a clock behind the fetch reads as fresh.+///+/// `is_fresh` is `elapsed < interval` with a saturating clock, so an entry exactly+/// `REFRESH_INTERVAL_MS` old is stale (not `<=`), and a clock that went backwards+/// saturates to zero rather than wrapping to stale.+#[test]+fn freshness_ends_exactly_at_the_interval_and_saturates_backward_clocks() {+ let f = Fixture::new("fresh_math");+ let clock = Arc::new(AtomicU64::new(1_000_000));+ let cache = cache_with(&f.dir, clock.clone(), DEFAULT_MAX_BYTES);+ let key = RangeCache::key(URL, "bytes=0-3");+ cache.write(&key, &[1, 2, 3, 4]);+ clock.store(1_000_000 + REFRESH_INTERVAL_MS, Ordering::SeqCst);+ assert!(!cache.is_fresh(&cache.read(&key).unwrap()), "exactly at the interval is stale");+ clock.store(999_000, Ordering::SeqCst);+ assert!(cache.is_fresh(&cache.read(&key).unwrap()), "a backward clock saturates to fresh");+}++/// The eviction target is eighty percent of the cap, in integer bytes.+///+/// `evict_if_over_cap` stops at `max_bytes / 10 * 8`, not at the cap, so a session+/// sitting at the limit does one pass rather than one per tile. Integer division+/// truncates, which only lowers the target and never overshoots it.+#[test]+fn the_eviction_target_is_eighty_percent_of_the_cap() {+ assert_eq!(DEFAULT_MAX_BYTES, 64 * 1024 * 1024, "the 64 MB cap");+ assert_eq!(REFRESH_INTERVAL_MS, 24 * 60 * 60 * 1000, "the 24 h refresh");+ for cap in [1000u64, 100u64, DEFAULT_MAX_BYTES, 1u64] {+ let target = cap / 10 * 8;+ assert!(target <= cap, "cap {cap}: target {target} exceeds it");+ assert_eq!(target + (cap - target), cap, "cap {cap}: target plus headroom is the cap");+ }+ assert_eq!(1000u64 / 10 * 8, 800, "the eviction test's headroom number");+}
library/map/src/main/rust/src/tile/select/tests_part2.rs
diff --git a/library/map/src/main/rust/src/tile/select/tests_part2.rs b/library/map/src/main/rust/src/tile/select/tests_part2.rsindex fd0ebe79c7..5275e7eac9 100644--- a/library/map/src/main/rust/src/tile/select/tests_part2.rs+++ b/library/map/src/main/rust/src/tile/select/tests_part2.rs@@ -403,3 +403,28 @@ fn a_missing_tile_falls_back_through_its_parent_to_the_water_background() { assert_eq!(water.light, water_light, "water fill matches the light backdrop"); assert_eq!(water.dark, water_dark, "water fill matches the dark backdrop"); }++/// Ancestor levels halve the coordinates each step, level zero is the tile itself,+/// and anything past the root is `None` rather than a wrapped tile.+///+/// The keep list and the overzoom reader both rely on this: a wrong shift fetches+/// the neighbour's parent, and a wrapping root ancestor would pin the whole world+/// resident under every viewport.+#[test]+fn tile_ancestor_chain_halves_each_level_and_stops_at_root() {+ let tile = TileId { z: 12, x: 2048, y: 1362 };+ assert_eq!(tile.ancestor(0), Some(tile), "level zero is the tile itself");+ let parent = tile.ancestor(1).expect("z12 has a parent");+ assert_eq!((parent.z, parent.x, parent.y), (11, 1024, 681));+ let grandparent = tile.ancestor(2).expect("z12 has a grandparent");+ assert_eq!((grandparent.z, grandparent.x, grandparent.y), (10, 512, 340));+ assert_eq!(tile.ancestor(12), Some(TileId { z: 0, x: 0, y: 0 }), "the root");+ assert!(tile.ancestor(13).is_none(), "past the root is nothing, not a wrap");+ assert!(TileId { z: 0, x: 0, y: 0 }.ancestor(1).is_none(), "the root has no parent");+ // And the depth gate agrees: the tile stands in for itself and its parent chain only.+ let root = TileId { z: 0, x: 0, y: 0 };+ assert!(tile.descends_from(&tile, 0), "depth zero still covers self");+ assert!(!tile.descends_from(&parent, 0), "depth zero stops past self");+ assert!(tile.descends_from(&grandparent, 2), "depth two covers two levels");+ assert!(!root.descends_from(&tile, 4), "an ancestor never descends from its child");+}
library/ml/src/main/rust/tests/pure_logic.rs
diff --git a/library/ml/src/main/rust/tests/pure_logic.rs b/library/ml/src/main/rust/tests/pure_logic.rsnew file mode 100644index 0000000000..7bc306aaa0--- /dev/null+++ b/library/ml/src/main/rust/tests/pure_logic.rs@@ -0,0 +1,222 @@+//! Host-only pure logic for `modelrunner`: no device, no `.maml` asset, no network.+//!+//! `tests/assets.rs` proves the shipped files build the shipped passes. This file proves the+//! pieces underneath them behave before any asset is read: the fp16 math preprocessing stands+//! on, the letterbox geometry the detector shares with its post-processing, the tokenizer and+//! CTC edges that would otherwise decode to fluent nonsense, and the input/output shapes the+//! Kotlin uploads and reads back. Everything here runs on the host with `cargo test`.++use modelrunner::nets::{+ mobilefacenet, modnet, ppocr_det, ppocr_rec, scrfd, selfie, u2netp, Shape, WeightSource,+};+use modelrunner::post::ctc::{decode, Dictionary, DICTIONARY_ENTRIES, LOGITS};+use modelrunner::post::sentencepiece::Table;+use modelrunner::post::sentencepiece_flavours::{FAIRSEQ, GEMMA};+use modelrunner::preprocess::{+ f16_to_f32, f32_to_f16, to_planar_f16, Letterbox, RESCALE_ONLY,+};++/// A weight source that knows only how many tensors the pass wants.+///+/// Hands back the tensor index as the offset, which is meaningless as an address but makes the+/// plan reproducible. The net modules check every shape through `shaped`, so a transcription+/// that asks for the wrong dims still fails here — just against the stub rather than a file.+struct Stub {+ count: usize,+}++impl WeightSource for Stub {+ fn shaped(&self, index: usize, _dims: &[u32]) -> Result<u32, String> {+ Ok(index as u32)+ }++ fn shaped_words(&self, index: usize, _dims: &[u32]) -> Result<u32, String> {+ Ok(index as u32)+ }++ fn count(&self) -> usize {+ self.count+ }+}++/// The smallest table `Table::parse` accepts under the fairseq convention.+fn fairseq_fixture() -> Vec<u8> {+ let mut out = b"SPM1".to_vec();+ let pieces = ["<s>", "<pad>", "</s>", "<unk>"];+ out.extend((pieces.len() as u32).to_le_bytes());+ for (index, piece) in pieces.iter().enumerate() {+ out.extend((-(index as i32)).to_le_bytes());+ out.extend((piece.len() as u16).to_le_bytes());+ out.extend(piece.as_bytes());+ }+ out+}++/// A CTC dictionary of `a` repeated to the real length, so `decode` accepts it.+fn ctc_fixture() -> Dictionary {+ let mut text = String::new();+ for _ in 0..DICTIONARY_ENTRIES {+ text.push('a');+ text.push('\n');+ }+ Dictionary::parse(&text).expect("the fixture dictionary parses")+}++#[test]+fn half_precision_encodings_match_the_bit_layout_preprocessing_relies_on() {+ // Exact codes rather than round trips: the input path writes these bits and the mask path+ // reads them back, so a conversion that rounded correctly but placed the fields wrongly+ // would still pass a tolerance check and fail on device.+ assert_eq!(f32_to_f16(0.0), 0x0000);+ assert_eq!(f32_to_f16(-0.0), 0x8000);+ assert_eq!(f32_to_f16(1.0), 0x3c00);+ assert_eq!(f32_to_f16(-1.0), 0xbc00);+ assert_eq!(f32_to_f16(f32::INFINITY), 0x7c00);+ assert_eq!(f32_to_f16(f32::NEG_INFINITY), 0xfc00);+ // The border preprocessing pads with: raw zero through the SCRFD affine is about -0.996,+ // which must survive the trip rather than flush to zero.+ let border = (0.0 - 127.5) / 128.0;+ let back = f16_to_f32(f32_to_f16(border));+ assert!((back - border).abs() < 1e-3, "{back} vs {border}");+ // Overflow saturates and NaN stays a NaN; underflow keeps its sign.+ assert_eq!(f16_to_f32(f32_to_f16(1e30)), f32::INFINITY);+ assert!(f16_to_f32(f32_to_f16(f32::NAN)).is_nan());+ assert!(f16_to_f32(f32_to_f16(-1e-30)).is_sign_negative());+}++#[test]+fn letterbox_geometry_stays_on_multiples_and_centres_the_image() {+ // A square photo needs no padding and reports the input shape Kotlin uploads.+ let square = Letterbox::new(1000, 1000, 640, 32).expect("fits");+ assert_eq!(square.resized, (640, 640));+ assert_eq!(square.padded, (640, 640));+ assert_eq!(square.offset, (0, 0));+ assert_eq!(square.shape(), Shape::new(3, 640, 640));+ // A portrait photo pads left and right; the transposed case of the landscape test in+ // `post::nms`, which is where a swapped width and height shows up.+ let portrait = Letterbox::new(720, 1280, 640, 32).expect("fits");+ assert_eq!(portrait.resized, (360, 640));+ assert_eq!(portrait.padded, (384, 640));+ assert_eq!(portrait.offset, (12, 0));+ // An odd pad splits 2 above and 3 below under integer division, so the extra row lands+ // at the bottom rather than shifting every coordinate by half a pixel.+ let odd = Letterbox::new(640, 27, 640, 32).expect("fits");+ assert_eq!(odd.padded, (640, 32));+ assert_eq!(odd.offset.1, 2);+ // Truncation, not rounding: 1000x667 at scale 0.64 gives 426.88, which truncates to 426.+ let truncated = Letterbox::new(1000, 667, 640, 32).expect("fits");+ assert_eq!(truncated.resized.1, 426);+ // Every camera aspect ratio pads to multiples of 32, which is what the detector refuses+ // anything else for.+ for (width, height) in [(4032, 3024), (3024, 4032), (1920, 1080), (640, 480), (1, 1)] {+ let fit = Letterbox::new(width, height, 640, 32).expect("fits");+ assert!(fit.padded.0.is_multiple_of(32), "{width}x{height}: {fit:?}");+ assert!(fit.padded.1.is_multiple_of(32), "{width}x{height}: {fit:?}");+ }+ // Zero-sized inputs are refused, and a buffer of the wrong length is refused with the+ // element count rather than written short.+ assert!(Letterbox::new(0, 100, 640, 32).is_err());+ let pixels = vec![0i32; 4];+ let mut out = vec![0u16; 2];+ let error = to_planar_f16(&pixels, 2, 2, Shape::new(3, 2, 2), &RESCALE_ONLY, &mut out)+ .expect_err("wrong length");+ assert!(error.contains("output elements"), "{error}");+}++#[test]+fn ctc_decoding_refuses_malformed_inputs_before_touching_the_net() {+ let dictionary = ctc_fixture();+ assert_eq!(dictionary.labels(), LOGITS);+ assert_eq!(dictionary.label(0), None);+ assert_eq!(dictionary.label(1), Some("a"));+ assert_eq!(dictionary.label(LOGITS - 1), Some(" "));+ // A short table would shift every character above the gap, so it is refused at load.+ let error = Dictionary::parse("a\nb\nc\n").expect_err("too short");+ assert!(error.contains("3 dictionary entries"), "{error}");+ // An empty map means the recogniser produced nothing, which must not read as blank text.+ let error = decode(&[], 0, &dictionary).expect_err("an empty map");+ assert!(error.contains("no logits"), "{error}");+ // A ragged array is not a whole number of timesteps and is refused rather than read short.+ let error = decode(&vec![0.0; LOGITS + 3], 1, &dictionary).expect_err("ragged");+ assert!(error.contains("not a whole number"), "{error}");+ // Asking for more timesteps than the map holds is refused rather than read past the end.+ let mut two_steps = vec![0.0; LOGITS * 2];+ if let Some(slot) = two_steps.get_mut(1 * 2) {+ *slot = 10.0;+ }+ let error = decode(&two_steps, 3, &dictionary).expect_err("three of two");+ assert!(error.contains("3 of 2 timesteps"), "{error}");+ // One winning timestep decodes class-major: label 1 of step 0 sits at index `1 * steps`.+ let mut one_step = vec![0.0; LOGITS];+ if let Some(slot) = one_step.get_mut(1) {+ *slot = 10.0;+ }+ let got = decode(&one_step, 1, &dictionary).expect("decodes");+ assert_eq!(got.text, "a");+ assert!(got.confidence > 0.9, "{}", got.confidence);+}++#[test]+fn sentencepiece_tables_reject_malformed_bytes_before_decoding() {+ let bytes = fairseq_fixture();+ let table = Table::parse(&bytes).expect("the minimal table parses");+ assert_eq!(table.len(), 4);+ assert!(!table.has_byte_fallback());+ assert_eq!(table.piece(0), Some("<s>".as_bytes()));+ // Empty text encodes to nothing and decodes back to nothing; an id past the table is+ // skipped rather than replacing the whole string.+ assert!(table.encode("").is_empty());+ assert_eq!(table.decode(&[]), "");+ assert_eq!(table.decode(&[999]), "");+ // Not a table at all, a header cut short, and a table with bytes trailing it.+ let error = Table::parse(&[]).expect_err("empty");+ assert!(error.contains("SPM1"), "{error}");+ let error = Table::parse(b"BAD!").expect_err("bad magic");+ assert!(error.contains("SPM1"), "{error}");+ let cut = bytes.get(..10).unwrap_or(&[]).to_vec();+ assert!(Table::parse(&cut).is_err());+ let mut trailing = bytes.clone();+ trailing.push(0);+ let error = Table::parse(&trailing).expect_err("trailing byte");+ assert!(error.contains("bytes left"), "{error}");+ // The same bytes under the wrong convention are refused: id 0 is `<s>`, not `<pad>`.+ let error = Table::parse_with(&bytes, GEMMA).expect_err("wrong flavour");+ assert!(error.contains("not <pad>"), "{error}");+ // The flavour travelled with the parse, so callers read back what they asked for.+ assert_eq!(table.specials(), FAIRSEQ);+}++#[test]+fn vision_passes_advertise_the_shapes_the_kotlin_uploads() {+ // Fixed-shape nets: the input is what preprocessing writes and the output is what the+ // host reads back, so both are pinned without running anything on a device.+ let selfie = selfie::build(&Stub { count: selfie::TENSORS }).expect("selfie builds");+ assert_eq!(selfie.input().expect("one input").shape, Shape::new(3, selfie::SIZE, selfie::SIZE));+ assert_eq!(selfie.output().expect("one output").shape, Shape::new(1, selfie::SIZE, selfie::SIZE));+ let u2netp = u2netp::build(&Stub { count: u2netp::TENSORS }).expect("u2netp builds");+ assert_eq!(u2netp.input().expect("one input").shape, Shape::new(3, u2netp::SIZE, u2netp::SIZE));+ assert_eq!(u2netp.output().expect("one output").shape, Shape::new(1, u2netp::SIZE, u2netp::SIZE));+ let embed = mobilefacenet::build(&Stub { count: mobilefacenet::TENSORS }).expect("embedder builds");+ assert_eq!(embed.input().expect("one input").shape, Shape::new(3, mobilefacenet::SIZE, mobilefacenet::SIZE));+ assert_eq!(embed.output().expect("one output").shape, Shape::new(mobilefacenet::EMBEDDING, 1, 1));+ let matte = modnet::build(&Stub { count: modnet::TENSORS }).expect("modnet builds");+ assert_eq!(matte.input().expect("one input").shape, Shape::new(3, modnet::SIZE, modnet::SIZE));+ assert_eq!(matte.output().expect("one output").shape, Shape::new(1, modnet::SIZE, modnet::SIZE));+ // Dynamically shaped nets lower at the shape they are given: SCRFD groups nine maps by+ // stride, detection returns a full-resolution probability map, and recognition emits one+ // logit row per eighth of the width.+ let detect = scrfd::build(&Stub { count: scrfd::TENSORS }, 640, 640).expect("scrfd builds");+ assert_eq!(detect.outputs.len(), 9);+ assert_eq!(detect.outputs[0].shape, Shape::new(2, 80, 80));+ assert_eq!(detect.outputs[8].shape, Shape::new(20, 20, 20));+ let text = ppocr_det::build(&Stub { count: ppocr_det::TENSORS }, 960, 960).expect("detector builds");+ assert_eq!(text.output().expect("one output").shape.h, ppocr_det::LONG_SIDE);+ let line = ppocr_rec::build(&Stub { count: ppocr_rec::TENSORS }, 320).expect("recogniser builds");+ assert_eq!(line.output().expect("one output").shape, Shape::new(ppocr_rec::LOGITS, 1, 40));+ // Shapes the builders refuse rather than lower badly: a non-multiple SCRFD extent that+ // would break the neck, and a recognition width that would drop a column per stride.+ let error = scrfd::build(&Stub { count: scrfd::TENSORS }, 100, 640).expect_err("ragged extent");+ assert!(error.contains("multiple of 32"), "{error}");+ let error = ppocr_rec::build(&Stub { count: ppocr_rec::TENSORS }, 100).expect_err("ragged width");+ assert!(error.contains("multiple of 8"), "{error}");+}
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 05e650a69b..ddb48cbc79 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -135,8 +135,8 @@ if (file("personal/amazon").exists()) { if (file("personal/kaiser").exists()) { include(":personal:kaiser") }-if (file("personal/uniflix").exists()) {- include(":personal:uniflix")+if (file("personal/uniflix_strem").exists()) {+ include(":personal:uniflix_strem") } // Desktop JVM shells (Phase 2): host-side sync over the shared core.
uniflix/AGENTS.md
diff --git a/uniflix/AGENTS.md b/uniflix/AGENTS.mdindex 90ae52cf93..9a183174f8 100644--- a/uniflix/AGENTS.md+++ b/uniflix/AGENTS.md@@ -26,7 +26,7 @@ Watch/Detail link to the addon manager. - Manifest `resources` accepts Stremio string-or-object forms; only `stream` for movie/series validates - URL addons enforce HTTPS except loopback/private (dev); remote `http://` is rejected as `InsecureUrl` - `UniflixDatabase` v1→v2 migration adds `AddonEntity`; default addon id lives in DataStore, ordering in Room priority-- Private `personal/uniflix/` keeps the native Strem provider + hardcoded TMDB key — never copy those into `uniflix/`+- Private `personal/uniflix_strem/` keeps the native Strem provider + hardcoded TMDB key — never copy those into `uniflix/` ## Key files ### Root — entry + navigation
uniflix/src/main/java/com/vayunmathur/uniflix/data/AddonEntity.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/data/AddonEntity.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/data/AddonEntity.ktindex 6985e92a9a..2e60592a2c 100644--- a/uniflix/src/main/java/com/vayunmathur/uniflix/data/AddonEntity.kt+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/data/AddonEntity.kt@@ -4,6 +4,7 @@ import androidx.room3.Dao import androidx.room3.Entity import androidx.room3.PrimaryKey import androidx.room3.Query+import androidx.room3.Transaction import androidx.room3.Upsert import kotlinx.coroutines.flow.Flow @@ -55,6 +56,13 @@ interface AddonDao { @Query("UPDATE AddonEntity SET priority = :priority WHERE dbId = :dbId") suspend fun setPriority(dbId: Long, priority: Int) + /** Swaps two addons' priorities atomically so reorder never leaves a duplicate. */+ @Transaction+ suspend fun swapPriorities(first: AddonEntity, second: AddonEntity) {+ setPriority(first.dbId, second.priority)+ setPriority(second.dbId, first.priority)+ }+ @Query("UPDATE AddonEntity SET lastError = :error WHERE dbId = :dbId") suspend fun setError(dbId: Long, error: String?)
uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixDatabase.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixDatabase.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixDatabase.ktindex b16e10090f..ea28dfcee5 100644--- a/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixDatabase.kt+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixDatabase.kt@@ -156,8 +156,8 @@ abstract class UniflixDatabase : RoomDatabase() { override val migrations = listOf( object : Migration(1, 2) { override suspend fun migrate(connection: SQLiteConnection) {- // v1 shipped only on personal/dev devices; addons are new in the- // public app, so the table starts empty on every upgrade.+ // Addons are new in the public app, so the table starts+ // empty on every upgrade from the catalog-only v1. connection.execSQL( "CREATE TABLE IF NOT EXISTS AddonEntity (" + "dbId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixRepository.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixRepository.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixRepository.ktindex 6a25f56fd8..02fe118361 100644--- a/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixRepository.kt+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixRepository.kt@@ -57,7 +57,8 @@ class UniflixRepository private constructor(context: Context) : suspend fun addonCount(): Int = addonDao.count() suspend fun deleteAddon(dbId: Long) = addonDao.deleteById(dbId) suspend fun setAddonEnabled(dbId: Long, enabled: Boolean) = addonDao.setEnabled(dbId, enabled)- suspend fun setAddonPriority(dbId: Long, priority: Int) = addonDao.setPriority(dbId, priority)+ suspend fun swapAddonPriorities(first: AddonEntity, second: AddonEntity) =+ addonDao.swapPriorities(first, second) suspend fun setAddonError(dbId: Long, error: String?) = addonDao.setError(dbId, error) suspend fun setAddonConfig(dbId: Long, config: String) = addonDao.setConfig(dbId, config)
uniflix/src/main/java/com/vayunmathur/uniflix/platform/AddonsViewModel.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/platform/AddonsViewModel.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/platform/AddonsViewModel.ktindex 32d3f2ae44..8fb1f34c42 100644--- a/uniflix/src/main/java/com/vayunmathur/uniflix/platform/AddonsViewModel.kt+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/platform/AddonsViewModel.kt@@ -15,6 +15,7 @@ import com.vayunmathur.uniflix.data.UniflixRepository import com.vayunmathur.uniflix.domain.ManifestError import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch @@ -114,8 +115,36 @@ class AddonsViewModel(app: Application) : AndroidViewModel(app) { private fun swap(upper: AddonRow, lower: AddonRow) { viewModelScope.launch {- repository.setAddonPriority(upper.entity.dbId, lower.entity.priority)- repository.setAddonPriority(lower.entity.dbId, upper.entity.priority)+ repository.swapAddonPriorities(upper.entity, lower.entity)+ }+ }++ /** Re-fetches every installed manifest; per-addon failures land on that row's badge. */+ fun refreshAll() {+ viewModelScope.launch {+ refreshing = true+ val rows = addons.first()+ var failures = 0+ for (row in rows) {+ runCatching {+ val (base, manifest) = AddonStreamProvider.fetchManifest(row.entity.manifestUrl)+ repository.upsertAddon(+ row.entity.copy(+ baseUrl = base,+ addonId = manifest.id,+ name = manifest.name,+ version = manifest.version,+ lastError = null,+ updatedAt = System.currentTimeMillis(),+ ),+ )+ }.onFailure {+ failures+++ repository.setAddonError(row.entity.dbId, it.message ?: "Refresh failed")+ }+ }+ refreshing = false+ AppMessages.show(if (failures == 0) "Refreshed ${rows.size} addons" else "$failures of ${rows.size} addons failed to refresh") } }
uniflix/src/main/java/com/vayunmathur/uniflix/platform/DetailViewModel.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/platform/DetailViewModel.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/platform/DetailViewModel.ktindex 1826d54af6..3f45559a56 100644--- a/uniflix/src/main/java/com/vayunmathur/uniflix/platform/DetailViewModel.kt+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/platform/DetailViewModel.kt@@ -30,8 +30,8 @@ import kotlinx.coroutines.launch /** * Builds the live [PluginRegistry] from installed addons. Public- * implementations stay pure-HTTP; the personal overlay swaps this factory to- * also register its native provider.+ * implementations stay pure-HTTP; a private native-plugin overlay can swap+ * this factory to also register its own provider. */ fun interface RegistryFactory { suspend fun current(repository: UniflixRepository, prefs: AddonPrefs): PluginRegistry
uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonCard.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonCard.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonCard.ktindex 1358bd82c9..ba39ea3645 100644--- a/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonCard.kt+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonCard.kt@@ -57,12 +57,14 @@ fun AddonCard( Switch(checked = entity.enabled, onCheckedChange = { onToggle() }) } entity.lastError?.let { error ->- Row(- horizontalArrangement = Arrangement.spacedBy(8.dp),- verticalAlignment = Alignment.CenterVertically,- ) {- IconWarning()- Text(error, style = MaterialTheme.typography.bodySmall, modifier = Modifier.weight(1f))+ TextButton(onClick = onOpenDetail) {+ Row(+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ IconWarning()+ Text(error, style = MaterialTheme.typography.bodySmall, modifier = Modifier.weight(1f))+ } } } Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonsContent.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonsContent.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonsContent.ktindex dba1cd06ee..7c8d429d87 100644--- a/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonsContent.kt+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonsContent.kt@@ -15,6 +15,7 @@ import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.DesktopMaxWidthContainer import com.vayunmathur.library.ui.IconAdd import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconRefresh import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.appBarScrollBehavior@@ -38,6 +39,7 @@ fun AddonsContent( onMoveDown: (AddonRow) -> Unit, onRemove: (AddonRow) -> Unit, onRefresh: (AddonRow) -> Unit,+ onRefreshAll: () -> Unit, onOpenDetail: (addonDbId: Long) -> Unit, ) { AppScaffold(@@ -45,6 +47,7 @@ fun AddonsContent( onNavigateBack = onBack, scrollBehavior = appBarScrollBehavior(), actions = {+ IconButton(onClick = onRefreshAll, enabled = !refreshing) { IconRefresh() } IconButton(onClick = onAddClick) { IconAdd() } }, ) { padding ->
uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonsScreen.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonsScreen.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonsScreen.ktindex 5271586174..19754858a8 100644--- a/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonsScreen.kt+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonsScreen.kt@@ -34,6 +34,7 @@ fun AddonsScreen(onBack: () -> Unit, onOpenDetail: (addonDbId: Long) -> Unit) { onMoveDown = { row -> vm.moveDown(rows, row) }, onRemove = { row -> vm.remove(row) }, onRefresh = { row -> vm.refreshManifest(row) },+ onRefreshAll = { vm.refreshAll() }, onOpenDetail = onOpenDetail, )
uniflix/src/screenshotTest/kotlin/com/vayunmathur/uniflix/ui/MetadataPreviews.kt
diff --git a/uniflix/src/screenshotTest/kotlin/com/vayunmathur/uniflix/ui/MetadataPreviews.kt b/uniflix/src/screenshotTest/kotlin/com/vayunmathur/uniflix/ui/MetadataPreviews.ktindex 388142e8d7..937b72ecaa 100644--- a/uniflix/src/screenshotTest/kotlin/com/vayunmathur/uniflix/ui/MetadataPreviews.kt+++ b/uniflix/src/screenshotTest/kotlin/com/vayunmathur/uniflix/ui/MetadataPreviews.kt@@ -41,6 +41,7 @@ class MetadataPreviews { onMoveDown = {}, onRemove = {}, onRefresh = {},+ onRefreshAll = {}, onOpenDetail = {}, ) }@@ -94,6 +95,7 @@ class MetadataPreviews { onMoveDown = {}, onRemove = {}, onRefresh = {},+ onRefreshAll = {}, onOpenDetail = {}, ) }
uniflix/src/test/java/com/vayunmathur/uniflix/domain/AddonManifestTest.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/domain/AddonManifestTest.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/domain/AddonManifestTest.ktindex e463e1769d..80905e9642 100644--- a/uniflix/src/test/java/com/vayunmathur/uniflix/domain/AddonManifestTest.kt+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/domain/AddonManifestTest.kt@@ -1,5 +1,6 @@ package com.vayunmathur.uniflix.domain +import com.vayunmathur.uniflix.data.AddonStreamProvider import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith@@ -92,3 +93,61 @@ class AddonIdMappingTest { assertTrue(source.subtitles.single().url.endsWith("/en.vtt")) } }++/** Base-URL normalization: bare hosts, manifest URLs, slashes, scheme policy. */+class AddonUrlNormalizationTest {++ @Test+ fun strips_manifest_suffix_and_trailing_slash() {+ assertEquals(+ "https://example.com",+ AddonStreamProvider.normalizeBaseUrl("https://example.com/manifest.json"),+ )+ assertEquals(+ "https://example.com",+ AddonStreamProvider.normalizeBaseUrl("https://example.com///"),+ )+ }++ @Test+ fun defaults_bare_host_to_https() {+ assertEquals(+ "https://example.com",+ AddonStreamProvider.normalizeBaseUrl("example.com"),+ )+ }++ @Test+ fun keeps_path_and_port() {+ assertEquals(+ "https://example.com:8080/addon",+ AddonStreamProvider.normalizeBaseUrl("https://example.com:8080/addon/manifest.json"),+ )+ }++ @Test+ fun rejects_remote_http() {+ assertFailsWith<ManifestError.InsecureUrl> {+ AddonStreamProvider.normalizeBaseUrl("http://example.com/manifest.json")+ }+ }++ @Test+ fun allows_loopback_and_private_http() {+ assertEquals(+ "http://localhost:8080",+ AddonStreamProvider.normalizeBaseUrl("http://localhost:8080/manifest.json"),+ )+ assertEquals(+ "http://192.168.1.10:7000",+ AddonStreamProvider.normalizeBaseUrl("http://192.168.1.10:7000/manifest.json"),+ )+ }++ @Test+ fun rejects_non_http_schemes() {+ assertFailsWith<ManifestError.Parse> {+ AddonStreamProvider.normalizeBaseUrl("ftp://example.com/manifest.json")+ }+ }+}