π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add native Cast transport and discovery
Neeraj Guptaa409bee22f52
diff --git a/mobile/apps/photos/ios/Podfile.lock b/mobile/apps/photos/ios/Podfile.lockindex bf24c3dc22..ad538295af 100644--- a/mobile/apps/photos/ios/Podfile.lock+++ b/mobile/apps/photos/ios/Podfile.lock@@ -16,6 +16,8 @@ PODS:- FlutterMacOS- device_info_plus (0.0.1):- Flutter+ - ente_cast (0.0.1):+ - Flutter- ente_photos_rust (0.0.1):- Flutter- ente_qr (0.0.1):@@ -259,6 +261,7 @@ DEPENDENCIES:- connectivity_plus (from `.symlinks/plugins/connectivity_plus/ios`)- cupertino_http (from `.symlinks/plugins/cupertino_http/darwin`)- device_info_plus (from `.symlinks/plugins/device_info_plus/ios`)+ - ente_cast (from `.symlinks/plugins/ente_cast/ios`)- ente_photos_rust (from `.symlinks/plugins/ente_photos_rust/ios`)- ente_qr (from `.symlinks/plugins/ente_qr/ios`)- ente_rust (from `.symlinks/plugins/ente_rust/ios`)@@ -352,6 +355,8 @@ EXTERNAL SOURCES::path: ".symlinks/plugins/cupertino_http/darwin"device_info_plus::path: ".symlinks/plugins/device_info_plus/ios"+ ente_cast:+ :path: ".symlinks/plugins/ente_cast/ios"ente_photos_rust::path: ".symlinks/plugins/ente_photos_rust/ios"ente_qr:@@ -470,6 +475,7 @@ SPEC CHECKSUMS:connectivity_plus: cb623214f4e1f6ef8fe7403d580fdad517d2f7ddcupertino_http: 94ac07f5ff090b8effa6c5e2c47871d48ab7c86cdevice_info_plus: 21fcca2080fbcd348be798aa36c3e5ed849eefbe+ ente_cast: a25feb3127397e5fc6aff03a12120916707757d4ente_photos_rust: 380a324fc22445a1281e206726ccddd86582ad28ente_qr: 86beaf5d2644705db9b565b32dd8b82c05fb36afente_rust: d0197ebd5460e8f67576579452b073d698404abediff --git a/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj b/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxprojindex 2cde566701..2e969ce9a4 100644--- a/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj+++ b/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj@@ -636,6 +636,7 @@"${BUILT_PRODUCTS_DIR}/connectivity_plus/connectivity_plus.framework","${BUILT_PRODUCTS_DIR}/cupertino_http/cupertino_http.framework","${BUILT_PRODUCTS_DIR}/device_info_plus/device_info_plus.framework",+ "${BUILT_PRODUCTS_DIR}/ente_cast/ente_cast.framework","${BUILT_PRODUCTS_DIR}/ente_photos_rust/ente_photos_rust.framework","${BUILT_PRODUCTS_DIR}/ente_qr/ente_qr.framework","${BUILT_PRODUCTS_DIR}/ente_rust/ente_rust.framework",@@ -736,6 +737,7 @@"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/connectivity_plus.framework","${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/cupertino_http.framework","${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/device_info_plus.framework",+ "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ente_cast.framework","${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ente_photos_rust.framework","${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ente_qr.framework","${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ente_rust.framework",diff --git a/mobile/apps/photos/plugins/ente_cast/android/build.gradle b/mobile/apps/photos/plugins/ente_cast/android/build.gradlenew file mode 100644index 0000000000..965550e3bb--- /dev/null+++ b/mobile/apps/photos/plugins/ente_cast/android/build.gradle@@ -0,0 +1,47 @@+group 'io.ente.cast'+version '1.0'++buildscript {+ ext.kotlin_version = '2.1.10'+ repositories {+ google()+ mavenCentral()+ }++ dependencies {+ classpath 'com.android.tools.build:gradle:8.10.1'+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"+ }+}++rootProject.allprojects {+ repositories {+ google()+ mavenCentral()+ }+}++apply plugin: 'com.android.library'+apply plugin: 'kotlin-android'++android {+ namespace 'io.ente.cast'+ compileSdk 36++ compileOptions {+ sourceCompatibility JavaVersion.VERSION_1_8+ targetCompatibility JavaVersion.VERSION_1_8+ }++ kotlinOptions {+ jvmTarget = '1.8'+ }++ sourceSets {+ main.java.srcDirs += 'src/main/kotlin'+ }++ defaultConfig {+ minSdkVersion 21+ }+}diff --git a/mobile/apps/photos/plugins/ente_cast/android/src/main/AndroidManifest.xml b/mobile/apps/photos/plugins/ente_cast/android/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..00434dd055--- /dev/null+++ b/mobile/apps/photos/plugins/ente_cast/android/src/main/AndroidManifest.xml@@ -0,0 +1,3 @@+<manifest xmlns:android="http://schemas.android.com/apk/res/android">+ <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />+</manifest>diff --git a/mobile/apps/photos/plugins/ente_cast/android/src/main/kotlin/io/ente/cast/EnteCastPlugin.kt b/mobile/apps/photos/plugins/ente_cast/android/src/main/kotlin/io/ente/cast/EnteCastPlugin.ktnew file mode 100644index 0000000000..20c83a12ec--- /dev/null+++ b/mobile/apps/photos/plugins/ente_cast/android/src/main/kotlin/io/ente/cast/EnteCastPlugin.kt@@ -0,0 +1,54 @@+package io.ente.cast++import android.content.Context+import android.net.wifi.WifiManager+import io.flutter.embedding.engine.plugins.FlutterPlugin+import io.flutter.plugin.common.MethodCall+import io.flutter.plugin.common.MethodChannel++class EnteCastPlugin : FlutterPlugin, MethodChannel.MethodCallHandler {+ private lateinit var channel: MethodChannel+ private lateinit var lock: WifiManager.MulticastLock+ private var holderCount = 0++ override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {+ val wifiManager = binding.applicationContext+ .getSystemService(Context.WIFI_SERVICE) as WifiManager+ lock = wifiManager.createMulticastLock("ente_cast_discovery").apply {+ setReferenceCounted(false)+ }+ channel = MethodChannel(binding.binaryMessenger, CHANNEL)+ channel.setMethodCallHandler(this)+ }++ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {+ when (call.method) {+ "acquire" -> {+ if (holderCount == 0) {+ lock.acquire()+ }+ holderCount+++ result.success(null)+ }+ "release" -> {+ if (holderCount > 0 && --holderCount == 0 && lock.isHeld) {+ lock.release()+ }+ result.success(null)+ }+ else -> result.notImplemented()+ }+ }++ override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {+ channel.setMethodCallHandler(null)+ holderCount = 0+ if (lock.isHeld) {+ lock.release()+ }+ }++ private companion object {+ const val CHANNEL = "io.ente.cast/multicast"+ }+}diff --git a/mobile/apps/photos/plugins/ente_cast/ios/Classes/EnteCastPlugin.swift b/mobile/apps/photos/plugins/ente_cast/ios/Classes/EnteCastPlugin.swiftnew file mode 100644index 0000000000..9f0bb1335a--- /dev/null+++ b/mobile/apps/photos/plugins/ente_cast/ios/Classes/EnteCastPlugin.swift@@ -0,0 +1,232 @@+import Darwin+import Flutter+import Foundation++public final class EnteCastPlugin: NSObject, FlutterPlugin {+ private var discoveries: [UUID: BonjourDiscovery] = [:]++ public static func register(with registrar: FlutterPluginRegistrar) {+ let channel = FlutterMethodChannel(+ name: "io.ente.cast/discovery",+ binaryMessenger: registrar.messenger()+ )+ let instance = EnteCastPlugin()+ registrar.addMethodCallDelegate(instance, channel: channel)+ }++ public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {+ guard call.method == "searchDevices" else {+ result(FlutterMethodNotImplemented)+ return+ }++ let arguments = call.arguments as? [String: Any]+ let timeoutMilliseconds =+ (arguments?["timeoutMilliseconds"] as? NSNumber)?.doubleValue ?? 7_000+ let discoveryID = UUID()+ let discovery = BonjourDiscovery(+ timeout: max(timeoutMilliseconds / 1_000, 0.5)+ ) { [weak self] outcome in+ self?.discoveries.removeValue(forKey: discoveryID)+ switch outcome {+ case let .success(devices):+ result(devices)+ case let .failure(error):+ result(+ FlutterError(+ code: "BONJOUR_DISCOVERY_FAILED",+ message: error.localizedDescription,+ details: nil+ )+ )+ }+ }+ discoveries[discoveryID] = discovery+ discovery.start()+ }+}++private final class BonjourDiscovery: NSObject {+ typealias Device = [String: Any]++ private let browser = NetServiceBrowser()+ private let timeout: TimeInterval+ private let completion: (Result<[Device], Error>) -> Void+ private var services: [String: NetService] = [:]+ private var devices: [String: Device] = [:]+ private var timer: Timer?+ private var isFinished = false++ init(+ timeout: TimeInterval,+ completion: @escaping (Result<[Device], Error>) -> Void+ ) {+ self.timeout = timeout+ self.completion = completion+ }++ func start() {+ browser.delegate = self+ browser.searchForServices(+ ofType: "_googlecast._tcp.",+ inDomain: "local."+ )+ timer = Timer.scheduledTimer(+ withTimeInterval: timeout,+ repeats: false+ ) { [weak self] _ in+ self?.finish(.success(self?.sortedDevices ?? []))+ }+ }++ private var sortedDevices: [Device] {+ devices.values.sorted {+ ($0["name"] as? String ?? "") < ($1["name"] as? String ?? "")+ }+ }++ private func finish(_ result: Result<[Device], Error>) {+ guard !isFinished else {+ return+ }+ isFinished = true+ timer?.invalidate()+ timer = nil+ browser.stop()+ for service in services.values {+ service.stop()+ service.delegate = nil+ }+ services.removeAll()+ completion(result)+ }++ private func serviceKey(_ service: NetService) -> String {+ "\(service.name).\(service.type)\(service.domain)"+ }++ private func deviceName(+ for service: NetService,+ attributes: [String: String]+ ) -> String {+ if let friendlyName = attributes["fn"], !friendlyName.isEmpty {+ return friendlyName+ }+ if let model = attributes["md"], !model.isEmpty {+ return model+ }+ return service.name.replacingOccurrences(of: "-", with: " ")+ }++ private func textAttributes(for service: NetService) -> [String: String] {+ guard let data = service.txtRecordData() else {+ return [:]+ }+ return NetService.dictionary(fromTXTRecord: data).reduce(into: [:]) {+ attributes,+ entry in+ if let value = String(data: entry.value, encoding: .utf8) {+ attributes[entry.key] = value+ }+ }+ }++ private func numericAddresses(for service: NetService) -> [String] {+ guard let serviceAddresses = service.addresses else {+ return []+ }+ var hosts: [String] = []+ var seenHosts = Set<String>()+ for family in [AF_INET, AF_INET6] {+ for address in serviceAddresses {+ let host = address.withUnsafeBytes { bytes -> String? in+ guard let socketAddress = bytes+ .bindMemory(to: sockaddr.self)+ .baseAddress,+ Int32(socketAddress.pointee.sa_family) == family else {+ return nil+ }+ var buffer = [CChar](+ repeating: 0,+ count: Int(NI_MAXHOST)+ )+ guard getnameinfo(+ socketAddress,+ socklen_t(address.count),+ &buffer,+ socklen_t(buffer.count),+ nil,+ 0,+ NI_NUMERICHOST+ ) == 0 else {+ return nil+ }+ return String(cString: buffer)+ }+ if let host, seenHosts.insert(host).inserted {+ hosts.append(host)+ }+ }+ }+ if hosts.isEmpty, let hostName = service.hostName {+ hosts.append(hostName)+ }+ return hosts+ }+}++extension BonjourDiscovery: NetServiceBrowserDelegate {+ func netServiceBrowser(+ _ browser: NetServiceBrowser,+ didFind service: NetService,+ moreComing: Bool+ ) {+ let key = serviceKey(service)+ services[key] = service+ service.delegate = self+ service.resolve(withTimeout: min(timeout, 5))+ }++ func netServiceBrowser(+ _ browser: NetServiceBrowser,+ didNotSearch errorDict: [String: NSNumber]+ ) {+ let code = errorDict[NetService.errorCode]?.intValue ?? -1+ let error = NSError(+ domain: "io.ente.cast.bonjour",+ code: code,+ userInfo: [+ NSLocalizedDescriptionKey:+ "Unable to browse for Cast devices on the local network."+ ]+ )+ finish(.failure(error))+ }++ func netServiceBrowser(+ _ browser: NetServiceBrowser,+ didRemove service: NetService,+ moreComing: Bool+ ) {+ let key = serviceKey(service)+ services.removeValue(forKey: key)+ devices.removeValue(forKey: key)+ }+}++extension BonjourDiscovery: NetServiceDelegate {+ func netServiceDidResolveAddress(_ sender: NetService) {+ let key = serviceKey(sender)+ let addresses = numericAddresses(for: sender)+ guard !addresses.isEmpty, sender.port > 0 else {+ return+ }+ let attributes = textAttributes(for: sender)+ devices[key] = [+ "serviceName": key,+ "name": deviceName(for: sender, attributes: attributes),+ "addresses": addresses,+ "port": sender.port,+ ]+ }+}diff --git a/mobile/apps/photos/plugins/ente_cast/ios/ente_cast.podspec b/mobile/apps/photos/plugins/ente_cast/ios/ente_cast.podspecnew file mode 100644index 0000000000..5f1f99f7c7--- /dev/null+++ b/mobile/apps/photos/plugins/ente_cast/ios/ente_cast.podspec@@ -0,0 +1,14 @@+Pod::Spec.new do |s|+ s.name = 'ente_cast'+ s.version = '0.0.1'+ s.summary = 'Chromecast sender transport for Ente.'+ s.homepage = 'https://ente.com'+ s.license = { :type => 'AGPL-3.0-only' }+ s.author = { 'Ente' => '[email protected]' }+ s.source = { :path => '.' }+ s.source_files = 'Classes/**/*'+ s.dependency 'Flutter'+ s.platform = :ios, '15.1'+ s.swift_version = '5.0'+ s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }+enddiff --git a/mobile/apps/photos/plugins/ente_cast/lib/src/cast/cast_message_codec.dart b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/cast_message_codec.dartnew file mode 100644index 0000000000..b798ed4c32--- /dev/null+++ b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/cast_message_codec.dart@@ -0,0 +1,179 @@+import "dart:convert";+import "dart:typed_data";++const maxCastFrameLength = 64 * 1024;++final class CastEnvelope {+ final String namespace;+ final String payload;++ const CastEnvelope({required this.namespace, required this.payload});+}++Uint8List encodeCastEnvelope({+ required String sourceID,+ required String destinationID,+ required String namespace,+ required String payload,+}) {+ final output = BytesBuilder(copy: false);+ _writeVarintField(output, 1, 0);+ _writeStringField(output, 2, sourceID);+ _writeStringField(output, 3, destinationID);+ _writeStringField(output, 4, namespace);+ _writeVarintField(output, 5, 0);+ _writeStringField(output, 6, payload);+ return output.takeBytes();+}++Uint8List encodeCastFrame({+ required String sourceID,+ required String destinationID,+ required String namespace,+ required String payload,+}) {+ final envelope = encodeCastEnvelope(+ sourceID: sourceID,+ destinationID: destinationID,+ namespace: namespace,+ payload: payload,+ );+ if (envelope.length > maxCastFrameLength) {+ throw const FormatException("Cast message exceeds the frame limit");+ }++ final frame = Uint8List(envelope.length + 4);+ ByteData.sublistView(frame).setUint32(0, envelope.length, Endian.big);+ frame.setRange(4, frame.length, envelope);+ return frame;+}++CastEnvelope decodeCastEnvelope(Uint8List bytes) {+ final cursor = _Cursor();+ String? namespace;+ String? payload;++ while (cursor.offset < bytes.length) {+ final tag = _readVarint(bytes, cursor);+ final field = tag >> 3;+ final wireType = tag & 7;+ if (wireType == 2) {+ final length = _readVarint(bytes, cursor);+ final end = cursor.offset + length;+ if (end > bytes.length) {+ throw const FormatException("Truncated Cast message field");+ }+ if (field == 4 || field == 6) {+ final value = utf8.decode(bytes.sublist(cursor.offset, end));+ if (field == 4) {+ namespace = value;+ } else {+ payload = value;+ }+ }+ cursor.offset = end;+ } else {+ _skipField(bytes, cursor, wireType);+ }+ }++ if (namespace == null || payload == null) {+ throw const FormatException("Incomplete Cast message");+ }+ return CastEnvelope(namespace: namespace, payload: payload);+}++final class CastFrameDecoder {+ Uint8List _pending = Uint8List(0);++ List<CastEnvelope> add(Uint8List chunk) {+ if (chunk.isNotEmpty) {+ final combined = Uint8List(_pending.length + chunk.length)+ ..setRange(0, _pending.length, _pending)+ ..setRange(_pending.length, _pending.length + chunk.length, chunk);+ _pending = combined;+ }++ final envelopes = <CastEnvelope>[];+ var consumed = 0;+ while (_pending.length - consumed >= 4) {+ final length = ByteData.sublistView(+ _pending,+ consumed,+ consumed + 4,+ ).getUint32(0, Endian.big);+ if (length == 0 || length > maxCastFrameLength) {+ throw FormatException("Invalid Cast frame length: $length");+ }+ if (_pending.length - consumed < length + 4) {+ break;+ }+ envelopes.add(+ decodeCastEnvelope(+ Uint8List.sublistView(_pending, consumed + 4, consumed + 4 + length),+ ),+ );+ consumed += length + 4;+ }++ if (consumed > 0) {+ _pending = Uint8List.fromList(_pending.sublist(consumed));+ }+ return envelopes;+ }+}++void _writeVarintField(BytesBuilder output, int field, int value) {+ _writeVarint(output, field << 3);+ _writeVarint(output, value);+}++void _writeStringField(BytesBuilder output, int field, String value) {+ final bytes = utf8.encode(value);+ _writeVarint(output, (field << 3) | 2);+ _writeVarint(output, bytes.length);+ output.add(bytes);+}++void _writeVarint(BytesBuilder output, int value) {+ var remaining = value;+ while (remaining >= 0x80) {+ output.addByte((remaining & 0x7f) | 0x80);+ remaining >>= 7;+ }+ output.addByte(remaining);+}++int _readVarint(Uint8List bytes, _Cursor cursor) {+ var value = 0;+ var shift = 0;+ while (cursor.offset < bytes.length && shift <= 63) {+ final byte = bytes[cursor.offset++];+ value |= (byte & 0x7f) << shift;+ if (byte & 0x80 == 0) {+ return value;+ }+ shift += 7;+ }+ throw const FormatException("Invalid Cast message varint");+}++void _skipField(Uint8List bytes, _Cursor cursor, int wireType) {+ switch (wireType) {+ case 0:+ _readVarint(bytes, cursor);+ case 1:+ cursor.offset += 8;+ case 5:+ cursor.offset += 4;+ default:+ throw FormatException("Unsupported Cast wire type $wireType");+ }+ if (cursor.offset > bytes.length) {+ throw const FormatException("Truncated Cast message field");+ }+}++final class _Cursor {+ int offset = 0;+}diff --git a/mobile/apps/photos/plugins/ente_cast/lib/src/cast/cast_pairing.dart b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/cast_pairing.dartnew file mode 100644index 0000000000..4edbbd3ebe--- /dev/null+++ b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/cast_pairing.dart@@ -0,0 +1,115 @@+import "dart:async";++import "package:ente_cast/src/cast/chromecast_channel.dart";+import "package:ente_cast/src/cast/chromecast_connection.dart";++const castPairRequestNamespace = "urn:x-cast:pair-request";++Future<String> waitForPairCode({+ required Stream<ChromecastMessage> messages,+ required Stream<ChromecastConnectionState> states,+ required ChromecastConnectionState initialState,+ required void Function() start,+ required void Function() sendPairRequest,+ required Duration timeout,+}) async {+ final pairCode = Completer<String>();+ var pairRequestSent = false;++ void completeError(Object error, [StackTrace? stackTrace]) {+ if (!pairCode.isCompleted) {+ pairCode.completeError(error, stackTrace);+ }+ }++ void requestPairCode() {+ if (pairRequestSent || pairCode.isCompleted) {+ return;+ }+ pairRequestSent = true;+ try {+ sendPairRequest();+ } catch (error, stackTrace) {+ completeError(error, stackTrace);+ }+ }++ final messageSubscription = messages.listen(+ (message) {+ final payload = message.payload;+ if (message.namespace == ChromecastConnection.receiverNamespace) {+ final type = payload["type"];+ if (type == "LAUNCH_ERROR" ||+ (type == "LAUNCH_STATUS" && payload["status"] == "USER_DENIED")) {+ completeError(+ CastPairingException(+ payload["reason"]?.toString() ??+ "The Cast receiver rejected launch",+ ),+ );+ return;+ }+ }+ if (message.namespace != castPairRequestNamespace) {+ return;+ }+ final code = payload["code"];+ if (code is String && code.isNotEmpty && !pairCode.isCompleted) {+ pairCode.complete(code);+ }+ },+ onError: completeError,+ cancelOnError: false,+ );+ final stateSubscription = states.listen(+ (state) {+ switch (state) {+ case ChromecastConnectionState.connecting:+ break;+ case ChromecastConnectionState.connected:+ requestPairCode();+ case ChromecastConnectionState.closed:+ completeError(+ const CastPairingException(+ "The Cast connection closed before pairing completed",+ ),+ );+ }+ },+ onError: completeError,+ cancelOnError: false,+ );++ try {+ start();+ } catch (error, stackTrace) {+ completeError(error, stackTrace);+ }+ if (initialState == ChromecastConnectionState.connected) {+ requestPairCode();+ }++ try {+ return await pairCode.future.timeout(+ timeout,+ onTimeout: () => throw TimeoutException(+ "The Cast receiver did not return a pairing code",+ timeout,+ ),+ );+ } finally {+ await Future.wait([+ messageSubscription.cancel(),+ stateSubscription.cancel(),+ ]);+ }+}++final class CastPairingException implements Exception {+ final String message;++ const CastPairingException(this.message);++ @override+ String toString() => "CastPairingException: $message";+}diff --git a/mobile/apps/photos/plugins/ente_cast/lib/src/cast/chromecast_channel.dart b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/chromecast_channel.dartnew file mode 100644index 0000000000..1f86f5a806--- /dev/null+++ b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/chromecast_channel.dart@@ -0,0 +1,122 @@+import "dart:async";+import "dart:convert";+import "dart:io";+import "dart:typed_data";++import "package:ente_cast/src/cast/cast_message_codec.dart";++final class ChromecastMessage {+ final String namespace;+ final Map<String, dynamic> payload;++ const ChromecastMessage({required this.namespace, required this.payload});+}++final class ChromecastChannel {+ final SecureSocket _socket;+ final _messages = StreamController<ChromecastMessage>.broadcast();+ final _frameDecoder = CastFrameDecoder();+ var _requestID = 0;+ Future<void>? _closeFuture;++ ChromecastChannel._(this._socket) {+ _socket.listen(+ _receive,+ onError: (Object error, StackTrace stackTrace) {+ _messages.addError(error, stackTrace);+ unawaited(close());+ },+ onDone: _messages.close,+ cancelOnError: false,+ );+ }++ Stream<ChromecastMessage> get messages => _messages.stream;++ static Future<ChromecastChannel> connect(+ List<String> addresses,+ int port, {+ Duration timeout = const Duration(seconds: 10),+ }) async {+ final uniqueAddresses = addresses.toSet().toList();+ if (uniqueAddresses.isEmpty) {+ throw ArgumentError.value(addresses, "addresses", "Must not be empty");+ }++ final deadline = DateTime.now().add(timeout);+ Object? lastError;+ StackTrace? lastStackTrace;+ for (var index = 0; index < uniqueAddresses.length; index++) {+ final remaining = deadline.difference(DateTime.now());+ if (remaining <= Duration.zero) {+ break;+ }+ final addressesLeft = uniqueAddresses.length - index;+ final attemptTimeout = Duration(+ microseconds: remaining.inMicroseconds ~/ addressesLeft,+ );+ try {+ final socket = await SecureSocket.connect(+ uniqueAddresses[index],+ port,+ timeout: attemptTimeout,+ onBadCertificate: (_) => true,+ );+ return ChromecastChannel._(socket);+ } catch (error, stackTrace) {+ lastError = error;+ lastStackTrace = stackTrace;+ }+ }++ if (lastError != null && lastStackTrace != null) {+ Error.throwWithStackTrace(lastError, lastStackTrace);+ }+ throw TimeoutException("Timed out connecting to Cast device", timeout);+ }++ void send({+ required String namespace,+ required String sourceID,+ required String destinationID,+ required Map<String, dynamic> payload,+ }) {+ final message = Map<String, dynamic>.of(payload)+ ..putIfAbsent("requestId", () => _requestID++);+ final frame = encodeCastFrame(+ sourceID: sourceID,+ destinationID: destinationID,+ namespace: namespace,+ payload: jsonEncode(message),+ );+ _socket.add(frame);+ }++ Future<void> flush() => _socket.flush();++ Future<void> close() => _closeFuture ??= _close();++ Future<void> _close() async {+ await _socket.close();+ }++ void _receive(Uint8List chunk) {+ try {+ for (final envelope in _frameDecoder.add(chunk)) {+ final decoded = jsonDecode(envelope.payload);+ if (decoded is! Map) {+ throw const FormatException("Cast payload is not an object");+ }+ _messages.add(+ ChromecastMessage(+ namespace: envelope.namespace,+ payload: Map<String, dynamic>.from(decoded),+ ),+ );+ }+ } catch (error, stackTrace) {+ _messages.addError(error, stackTrace);+ unawaited(close());+ }+ }+}diff --git a/mobile/apps/photos/plugins/ente_cast/lib/src/cast/chromecast_client.dart b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/chromecast_client.dartnew file mode 100644index 0000000000..c778ee00da--- /dev/null+++ b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/chromecast_client.dart@@ -0,0 +1,31 @@+import "dart:async";+import "dart:math";++import "package:ente_cast/src/cast/chromecast_connection.dart";+import "package:ente_cast/src/cast/chromecast_device.dart";++final class ChromecastClient {+ final _connections = <ChromecastConnection>[];+ final _random = Random.secure();++ Future<ChromecastConnection> connect(ChromecastDevice device) async {+ String sourceID;+ do {+ sourceID = "client-${_random.nextInt(1000000)}";+ } while (_connections.any((connection) => connection.sourceID == sourceID));++ final connection = await ChromecastConnection.connect(sourceID, device);+ _connections.add(connection);+ connection.states.listen((state) {+ if (state == ChromecastConnectionState.closed) {+ _connections.remove(connection);+ }+ });+ return connection;+ }++ Future<void> disconnect(ChromecastConnection connection) async {+ _connections.remove(connection);+ await connection.close();+ }+}diff --git a/mobile/apps/photos/plugins/ente_cast/lib/src/cast/chromecast_connection.dart b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/chromecast_connection.dartnew file mode 100644index 0000000000..b770766b3c--- /dev/null+++ b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/chromecast_connection.dart@@ -0,0 +1,152 @@+import "dart:async";++import "package:ente_cast/src/cast/chromecast_channel.dart";+import "package:ente_cast/src/cast/chromecast_device.dart";++enum ChromecastConnectionState { connecting, connected, closed }++final class ChromecastConnection {+ static const connectionNamespace = "urn:x-cast:com.google.cast.tp.connection";+ static const heartbeatNamespace = "urn:x-cast:com.google.cast.tp.heartbeat";+ static const receiverNamespace = "urn:x-cast:com.google.cast.receiver";+ static const _platformReceiverID = "receiver-0";++ final String sourceID;+ final ChromecastChannel _channel;+ final _messages = StreamController<ChromecastMessage>.broadcast();+ final _states = StreamController<ChromecastConnectionState>.broadcast();+ ChromecastConnectionState _state = ChromecastConnectionState.connecting;+ String? _applicationID;+ String? _transportID;+ bool _closing = false;++ ChromecastConnection._(this.sourceID, this._channel) {+ _channel.messages.listen(+ _handleMessage,+ onError: _messages.addError,+ onDone: _handleClosed,+ cancelOnError: false,+ );+ send(connectionNamespace, {"type": "CONNECT"});+ }++ Stream<ChromecastMessage> get messages => _messages.stream;+ Stream<ChromecastConnectionState> get states => _states.stream;+ ChromecastConnectionState get state => _state;++ static Future<ChromecastConnection> connect(+ String sourceID,+ ChromecastDevice device,+ ) async {+ final channel = await ChromecastChannel.connect(+ device.addresses,+ device.port,+ );+ return ChromecastConnection._(sourceID, channel);+ }++ void send(String namespace, Map<String, dynamic> payload) {+ _channel.send(+ namespace: namespace,+ sourceID: sourceID,+ destinationID: _transportID ?? _platformReceiverID,+ payload: payload,+ );+ }++ void sendToPlatformReceiver(String namespace, Map<String, dynamic> payload) {+ _channel.send(+ namespace: namespace,+ sourceID: sourceID,+ destinationID: _platformReceiverID,+ payload: payload,+ );+ }++ void launch(String applicationID) {+ _applicationID = applicationID;+ sendToPlatformReceiver(receiverNamespace, {+ "type": "LAUNCH",+ "appId": applicationID,+ });+ }++ Future<void> flush() => _channel.flush();++ Future<void> close() async {+ if (_closing || _state == ChromecastConnectionState.closed) {+ return;+ }+ _closing = true;+ try {+ send(connectionNamespace, {"type": "CLOSE"});+ await _channel.flush();+ } finally {+ await _channel.close();+ }+ }++ void _handleMessage(ChromecastMessage message) {+ final type = message.payload["type"];+ if (message.namespace == heartbeatNamespace && type == "PING") {+ sendToPlatformReceiver(heartbeatNamespace, {"type": "PONG"});+ return;+ }+ if (message.namespace == connectionNamespace && type == "CLOSE") {+ unawaited(close());+ return;+ }+ if (message.namespace == receiverNamespace && type == "RECEIVER_STATUS") {+ _updateTransport(message.payload);+ }+ _messages.add(message);+ }++ void _updateTransport(Map<String, dynamic> message) {+ final status = message["status"];+ final applications = status is Map ? status["applications"] : null;+ String? transportID;+ if (applications is List) {+ for (final application in applications) {+ if (application is Map &&+ application["appId"] == _applicationID &&+ application["transportId"] is String) {+ transportID = application["transportId"] as String;+ break;+ }+ }+ }++ if (transportID == null) {+ if (_transportID != null) {+ unawaited(close());+ }+ return;+ }+ if (transportID == _transportID) {+ return;+ }+ if (_transportID != null) {+ unawaited(close());+ return;+ }++ _transportID = transportID;+ send(connectionNamespace, {"type": "CONNECT"});+ if (_state != ChromecastConnectionState.connected) {+ _state = ChromecastConnectionState.connected;+ _states.add(_state);+ }+ }++ void _handleClosed() {+ if (_state == ChromecastConnectionState.closed) {+ return;+ }+ _state = ChromecastConnectionState.closed;+ _states+ ..add(_state)+ ..close();+ _messages.close();+ }+}diff --git a/mobile/apps/photos/plugins/ente_cast/lib/src/cast/chromecast_device.dart b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/chromecast_device.dartnew file mode 100644index 0000000000..013c3eb107--- /dev/null+++ b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/chromecast_device.dart@@ -0,0 +1,21 @@+final class ChromecastDevice {+ final String serviceName;+ final String name;+ final List<String> addresses;+ final int port;++ ChromecastDevice({+ required this.serviceName,+ required this.name,+ required Iterable<String> addresses,+ required this.port,+ }) : addresses = List.unmodifiable(addresses);++ @override+ bool operator ==(Object other) =>+ identical(this, other) ||+ other is ChromecastDevice && other.serviceName == serviceName;++ @override+ int get hashCode => serviceName.hashCode;+}diff --git a/mobile/apps/photos/plugins/ente_cast/lib/src/cast/chromecast_discovery.dart b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/chromecast_discovery.dartnew file mode 100644index 0000000000..43f65a8709--- /dev/null+++ b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/chromecast_discovery.dart@@ -0,0 +1,206 @@+import "dart:io";++import "package:ente_cast/src/cast/chromecast_device.dart";+import "package:ente_cast/src/cast/multicast_lock.dart";+import "package:flutter/services.dart";+import "package:multicast_dns/multicast_dns.dart";++const _serviceType = "_googlecast._tcp.local";+const _bonjourChannel = MethodChannel("io.ente.cast/discovery");++final class ChromecastDiscovery {+ const ChromecastDiscovery();++ Future<List<ChromecastDevice>> search({+ Duration timeout = const Duration(seconds: 5),+ }) {+ if (Platform.isIOS) {+ return _searchWithBonjour(timeout);+ }+ return withMulticastLock(() => _searchWithMdns(timeout));+ }++ Future<List<ChromecastDevice>> _searchWithBonjour(Duration timeout) async {+ final results = await _bonjourChannel.invokeListMethod<Object?>(+ "searchDevices",+ {"timeoutMilliseconds": timeout.inMilliseconds},+ );+ if (results == null) {+ return [];+ }++ final devices = <ChromecastDevice>[];+ for (final result in results) {+ if (result is! Map) {+ continue;+ }+ final serviceName = result["serviceName"];+ final name = result["name"];+ final addresses = result["addresses"];+ final port = result["port"];+ if (serviceName is String &&+ name is String &&+ addresses is List &&+ port is int) {+ final validAddresses = addresses.whereType<String>().toList();+ if (validAddresses.isEmpty) {+ continue;+ }+ devices.add(+ ChromecastDevice(+ serviceName: serviceName,+ name: name,+ addresses: validAddresses,+ port: port,+ ),+ );+ }+ }+ return devices;+ }++ Future<List<ChromecastDevice>> _searchWithMdns(Duration timeout) async {+ final client = MDnsClient();+ final devices = <String, ChromecastDevice>{};+ final deadline = DateTime.now().add(timeout);++ await client.start();+ try {+ final pointerTasks = <Future<void>>[];+ await for (final pointer in client.lookup<PtrResourceRecord>(+ ResourceRecordQuery.serverPointer(_serviceType),+ timeout: _remaining(deadline),+ )) {+ pointerTasks.add(_resolvePointer(client, pointer, deadline, devices));+ }+ await Future.wait(pointerTasks);+ } finally {+ client.stop();+ }++ return devices.values.toList()..sort((a, b) => a.name.compareTo(b.name));+ }++ Future<void> _resolvePointer(+ MDnsClient client,+ PtrResourceRecord pointer,+ DateTime deadline,+ Map<String, ChromecastDevice> devices,+ ) async {+ final serviceTasks = <Future<void>>[];+ await for (final service in client.lookup<SrvResourceRecord>(+ ResourceRecordQuery.service(pointer.domainName),+ timeout: _remaining(deadline),+ )) {+ serviceTasks.add(+ _resolveService(client, pointer, service, deadline, devices),+ );+ }+ await Future.wait(serviceTasks);+ }++ Future<void> _resolveService(+ MDnsClient client,+ PtrResourceRecord pointer,+ SrvResourceRecord service,+ DateTime deadline,+ Map<String, ChromecastDevice> devices,+ ) async {+ final attributesFuture = _readAttributes(+ client,+ pointer.domainName,+ deadline,+ );+ final addressesFuture = _resolveAddresses(client, service.target, deadline);+ final attributes = await attributesFuture;+ final addresses = await addressesFuture;+ devices[pointer.domainName] = ChromecastDevice(+ serviceName: pointer.domainName,+ name: _deviceName(pointer, attributes),+ addresses: addresses,+ port: service.port,+ );+ }++ Future<List<String>> _resolveAddresses(+ MDnsClient client,+ String target,+ DateTime deadline,+ ) async {+ final ipv4 = _lookupAddresses(+ client,+ ResourceRecordQuery.addressIPv4(target),+ deadline,+ );+ final ipv6 = _lookupAddresses(+ client,+ ResourceRecordQuery.addressIPv6(target),+ deadline,+ );+ final addresses = <String>{...await ipv4, ...await ipv6};+ if (addresses.isEmpty) {+ addresses.add(target);+ }+ return addresses.toList();+ }++ Future<Set<String>> _lookupAddresses(+ MDnsClient client,+ ResourceRecordQuery query,+ DateTime deadline,+ ) async {+ final addresses = <String>{};+ await for (final record in client.lookup<IPAddressResourceRecord>(+ query,+ timeout: _remaining(deadline),+ )) {+ addresses.add(record.address.address);+ }+ return addresses;+ }++ Future<Map<String, String>> _readAttributes(+ MDnsClient client,+ String serviceName,+ DateTime deadline,+ ) async {+ final attributes = <String, String>{};+ await for (final record in client.lookup<TxtResourceRecord>(+ ResourceRecordQuery.text(serviceName),+ timeout: _remaining(deadline),+ )) {+ for (final entry in record.text.split("\n")) {+ final separator = entry.indexOf("=");+ if (separator > 0) {+ attributes[entry.substring(0, separator)] = entry.substring(+ separator + 1,+ );+ }+ }+ }+ return attributes;+ }++ Duration _remaining(DateTime deadline) {+ final remaining = deadline.difference(DateTime.now());+ return remaining > Duration.zero ? remaining : Duration.zero;+ }++ String _deviceName(+ PtrResourceRecord pointer,+ Map<String, String> attributes,+ ) {+ final friendlyName = attributes["fn"];+ if (friendlyName != null && friendlyName.isNotEmpty) {+ return friendlyName;+ }+ final model = attributes["md"];+ if (model != null && model.isNotEmpty) {+ return model;+ }+ return pointer.domainName+ .replaceAll(".$_serviceType", "")+ .replaceAll("-", " ")+ .trim();+ }+}diff --git a/mobile/apps/photos/plugins/ente_cast/lib/src/cast/multicast_lock.dart b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/multicast_lock.dartnew file mode 100644index 0000000000..6db01b6009--- /dev/null+++ b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/multicast_lock.dart@@ -0,0 +1,24 @@+import "dart:io";++import "package:flutter/foundation.dart";+import "package:flutter/services.dart";++const _multicastChannel = MethodChannel("io.ente.cast/multicast");++Future<T> withMulticastLock<T>(+ Future<T> Function() action, {+ bool? acquireLock,+ MethodChannel channel = _multicastChannel,+}) async {+ final shouldAcquire = acquireLock ?? (!kIsWeb && Platform.isAndroid);+ if (!shouldAcquire) {+ return action();+ }++ await channel.invokeMethod<void>("acquire");+ try {+ return await action();+ } finally {+ await channel.invokeMethod<void>("release");+ }+}diff --git a/mobile/apps/photos/plugins/ente_cast/pubspec.yaml b/mobile/apps/photos/plugins/ente_cast/pubspec.yamlindex 181e226eea..4310a44c70 100644--- a/mobile/apps/photos/plugins/ente_cast/pubspec.yaml+++ b/mobile/apps/photos/plugins/ente_cast/pubspec.yaml@@ -3,6 +3,7 @@ name: ente_castresolution: workspaceenvironment:sdk: ">=3.10.0 <4.0.0"+ flutter: ">=3.38.0"dependencies:cast:@@ -13,8 +14,18 @@ dependencies:dio: 5.9.2flutter:sdk: flutter+ multicast_dns: 0.3.3+1dev_dependencies:flutter_lints: 6.0.0+ flutter_test:+ sdk: flutterflutter:+ plugin:+ platforms:+ android:+ package: io.ente.cast+ pluginClass: EnteCastPlugin+ ios:+ pluginClass: EnteCastPlugindiff --git a/mobile/apps/photos/plugins/ente_cast/test/cast_message_codec_test.dart b/mobile/apps/photos/plugins/ente_cast/test/cast_message_codec_test.dartnew file mode 100644index 0000000000..3fa5d5d145--- /dev/null+++ b/mobile/apps/photos/plugins/ente_cast/test/cast_message_codec_test.dart@@ -0,0 +1,95 @@+import "dart:typed_data";++import "package:ente_cast/src/cast/cast_message_codec.dart";+import "package:flutter_test/flutter_test.dart";++void main() {+ test("encodes the Cast message fields", () {+ final bytes = encodeCastEnvelope(+ sourceID: "s",+ destinationID: "d",+ namespace: "n",+ payload: "{}",+ );++ expect(+ bytes,+ Uint8List.fromList([+ 8,+ 0,+ 18,+ 1,+ 115,+ 26,+ 1,+ 100,+ 34,+ 1,+ 110,+ 40,+ 0,+ 50,+ 2,+ 123,+ 125,+ ]),+ );+ });++ test("decodes length-delimited Cast fields", () {+ final encoded = encodeCastEnvelope(+ sourceID: "client-123",+ destinationID: "receiver-0",+ namespace: "urn:x-cast:pair-request",+ payload: '{"collectionID":42}',+ );++ final decoded = decodeCastEnvelope(encoded);++ expect(decoded.namespace, "urn:x-cast:pair-request");+ expect(decoded.payload, '{"collectionID":42}');+ });++ test("rejects a truncated Cast message", () {+ expect(+ () => decodeCastEnvelope(Uint8List.fromList([34, 5, 1])),+ throwsFormatException,+ );+ });++ test("decodes fragmented and consecutive Cast frames", () {+ final first = encodeCastFrame(+ sourceID: "client-1",+ destinationID: "receiver-0",+ namespace: "first",+ payload: '{"value":1}',+ );+ final second = encodeCastFrame(+ sourceID: "client-1",+ destinationID: "receiver-0",+ namespace: "second",+ payload: '{"value":2}',+ );+ final decoder = CastFrameDecoder();++ expect(decoder.add(Uint8List.sublistView(first, 0, 3)), isEmpty);+ final decoded = decoder.add(+ Uint8List.fromList([...first.sublist(3), ...second]),+ );++ expect(decoded.map((message) => message.namespace), ["first", "second"]);+ expect(decoded.map((message) => message.payload), [+ '{"value":1}',+ '{"value":2}',+ ]);+ });++ test("rejects oversized Cast frames before buffering the payload", () {+ final header = Uint8List(4);+ ByteData.sublistView(+ header,+ ).setUint32(0, maxCastFrameLength + 1, Endian.big);++ expect(() => CastFrameDecoder().add(header), throwsFormatException);+ });+}diff --git a/mobile/apps/photos/plugins/ente_cast/test/cast_pairing_test.dart b/mobile/apps/photos/plugins/ente_cast/test/cast_pairing_test.dartnew file mode 100644index 0000000000..e76d2ed3e0--- /dev/null+++ b/mobile/apps/photos/plugins/ente_cast/test/cast_pairing_test.dart@@ -0,0 +1,99 @@+import "dart:async";++import "package:ente_cast/src/cast/cast_pairing.dart";+import "package:ente_cast/src/cast/chromecast_channel.dart";+import "package:ente_cast/src/cast/chromecast_connection.dart";+import "package:flutter_test/flutter_test.dart";++void main() {+ test("requests and returns the receiver pairing code", () async {+ final messages = StreamController<ChromecastMessage>.broadcast(sync: true);+ final states = StreamController<ChromecastConnectionState>.broadcast(+ sync: true,+ );+ var pairRequests = 0;+ final result = waitForPairCode(+ messages: messages.stream,+ states: states.stream,+ initialState: ChromecastConnectionState.connecting,+ start: () {},+ sendPairRequest: () => pairRequests++,+ timeout: const Duration(seconds: 1),+ );++ states.add(ChromecastConnectionState.connected);+ messages.add(+ const ChromecastMessage(+ namespace: castPairRequestNamespace,+ payload: {"code": "123456"},+ ),+ );++ expect(await result, "123456");+ expect(pairRequests, 1);+ await messages.close();+ await states.close();+ });++ test("surfaces receiver launch failures", () async {+ final messages = StreamController<ChromecastMessage>.broadcast(sync: true);+ final states = StreamController<ChromecastConnectionState>.broadcast(+ sync: true,+ );+ final result = waitForPairCode(+ messages: messages.stream,+ states: states.stream,+ initialState: ChromecastConnectionState.connecting,+ start: () => messages.add(+ const ChromecastMessage(+ namespace: ChromecastConnection.receiverNamespace,+ payload: {"type": "LAUNCH_ERROR", "reason": "NOT_FOUND"},+ ),+ ),+ sendPairRequest: () {},+ timeout: const Duration(seconds: 1),+ );++ await expectLater(result, throwsA(isA<CastPairingException>()));+ await messages.close();+ await states.close();+ });++ test("surfaces a connection that closes before pairing", () async {+ final messages = StreamController<ChromecastMessage>.broadcast(sync: true);+ final states = StreamController<ChromecastConnectionState>.broadcast(+ sync: true,+ );+ final result = waitForPairCode(+ messages: messages.stream,+ states: states.stream,+ initialState: ChromecastConnectionState.connecting,+ start: () => states.add(ChromecastConnectionState.closed),+ sendPairRequest: () {},+ timeout: const Duration(seconds: 1),+ );++ await expectLater(result, throwsA(isA<CastPairingException>()));+ await messages.close();+ await states.close();+ });++ test("times out when the receiver never returns a code", () async {+ final messages = StreamController<ChromecastMessage>.broadcast(sync: true);+ final states = StreamController<ChromecastConnectionState>.broadcast(+ sync: true,+ );+ final result = waitForPairCode(+ messages: messages.stream,+ states: states.stream,+ initialState: ChromecastConnectionState.connecting,+ start: () {},+ sendPairRequest: () {},+ timeout: const Duration(milliseconds: 1),+ );++ await expectLater(result, throwsA(isA<TimeoutException>()));+ await messages.close();+ await states.close();+ });+}diff --git a/mobile/apps/photos/plugins/ente_cast/test/multicast_lock_test.dart b/mobile/apps/photos/plugins/ente_cast/test/multicast_lock_test.dartnew file mode 100644index 0000000000..3debf7d8c8--- /dev/null+++ b/mobile/apps/photos/plugins/ente_cast/test/multicast_lock_test.dart@@ -0,0 +1,62 @@+import "package:ente_cast/src/cast/multicast_lock.dart";+import "package:flutter/services.dart";+import "package:flutter_test/flutter_test.dart";++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ const channel = MethodChannel("io.ente.cast/test-multicast");+ final events = <String>[];++ setUp(() {+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(channel, (call) async {+ events.add(call.method);+ return null;+ });+ });++ tearDown(() {+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(channel, null);+ events.clear();+ });++ test("holds the multicast lock for the action", () async {+ final result = await withMulticastLock(+ () async {+ events.add("action");+ return 42;+ },+ acquireLock: true,+ channel: channel,+ );++ expect(result, 42);+ expect(events, ["acquire", "action", "release"]);+ });++ test("releases the multicast lock when the action fails", () async {+ final result = withMulticastLock<void>(+ () async {+ events.add("action");+ throw StateError("discovery failed");+ },+ acquireLock: true,+ channel: channel,+ );++ await expectLater(result, throwsStateError);+ expect(events, ["acquire", "action", "release"]);+ });++ test("does not call the platform channel outside Android", () async {+ await withMulticastLock(+ () async => events.add("action"),+ acquireLock: false,+ channel: channel,+ );++ expect(events, ["action"]);+ });+}