Skip to content

An open-source cross-platform alternative to AirDrop

16.4 KB
Raw Blame
// This file is automatically generated, so please do not edit it.
// @generated by `flutter_rust_bridge`@ 2.12.0.

// ignore_for_file: invalid_use_of_internal_member, unused_import, unnecessary_import

import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart';
import 'package:freezed_annotation/freezed_annotation.dart' hide protected;
import 'package:localsend_isolates/rust/api/model.dart';
import 'package:localsend_isolates/rust/frb_generated.dart';

part 'discovery.freezed.dart';

// These functions are ignored because they are not marked as `pub`: `merged_event`, `millis_since_epoch`, `rs_device_channel`, `rs_device_log`, `rs_stored_channel`, `rs_stored_device`, `stop`, `unconfirmed_device`
// These types are ignored because they are neither used by any `pub` functions nor (for structs and enums) marked `#[frb(unignore)]`: `DiscoveryInstance`

/// Starts the discovery: binds the UDP multicast sockets on all usable
/// network interfaces, answers announcements of other devices with an HTTP
/// register request, and keeps the store of confirmed devices.
///
/// Announcements are received from the IPv4 [group] and, as a LocalSend
/// extension, from the (currently hardcoded) IPv6 group `ff12::fd3a:e420`.
///
/// [port] is used both to bind the multicast sockets and as the HTTP server
/// port announced to other devices. [cert_pem] and [private_key_pem] are this
/// device's TLS identity, sent as client certificate with every register
/// request; [fingerprint] must be the certificate's SHA-256 fingerprint.
///
/// Nothing is announced until [RsDiscovery::announce] is called.
///
/// Cannot fail besides an invalid [group]: when no multicast socket could be
/// bound (e.g. the port is taken by another process), discovery still runs
/// without multicast — see [RsDiscovery::multicast_error] — and still learns
/// about devices through [RsDiscovery::discover_staged],
/// [RsDiscovery::scan_subnet] and [RsDiscovery::observe_inbound].
Future<RsDiscovery> startDiscovery({
  required String group,
  required int port,
  List<String>? networkWhitelist,
  List<String>? networkBlacklist,
  required String alias,
  required String version,
  String? deviceModel,
  DeviceType? deviceType,
  required String fingerprint,
  required ProtocolType protocol,
  required bool download,
  required String certPem,
  required String privateKeyPem,
  required BigInt timeoutMs,
}) => RustLib.instance.api.crateApiDiscoveryStartDiscovery(
  group: group,
  port: port,
  networkWhitelist: networkWhitelist,
  networkBlacklist: networkBlacklist,
  alias: alias,
  version: version,
  deviceModel: deviceModel,
  deviceType: deviceType,
  fingerprint: fingerprint,
  protocol: protocol,
  download: download,
  certPem: certPem,
  privateKeyPem: privateKeyPem,
  timeoutMs: timeoutMs,
);

// Rust type: RustOpaqueMoi<flutter_rust_bridge::for_generated::RustAutoOpaqueInner<RsDiscovery>>
abstract class RsDiscovery implements RustOpaqueInterface {
  /// Announces this device to the network, which makes every other LocalSend
  /// device on it register with this device over HTTP.
  ///
  /// Devices registering in response arrive at the application as server
  /// events, not here: feed them back via [RsDiscovery::observe_inbound].
  ///
  /// Returns once the whole announcement burst has been sent, which takes a
  /// few seconds, or immediately once the discovery has been stopped or
  /// multicast is unavailable.
  Future<void> announce();

  /// The retained observations of a stored device, oldest first, capped at
  /// the store's log limit. Empty when the fingerprint is unknown.
  Future<List<RsDeviceLog>> deviceLogs({required String fingerprint});

  /// Discovers devices in stages, cheapest first: announces this device to
  /// the network and probes [channels] (e.g. the favorites), then falls
  /// back to scanning the `/24` subnets of the local interface addresses
  /// [interface_ips], for networks that do not carry multicast. The
  /// fallback only runs when nothing was confirmed until [grace_ms] after
  /// the channels have been probed.
  ///
  /// The found devices are emitted on [RsDiscovery::listen] as they answer;
  /// returns once every stage has finished, including the whole
  /// announcement burst.
  Future<void> discoverStaged({
    required List<RsDeviceChannel> channels,
    required List<String> interfaceIps,
    required int port,
    required ProtocolType protocol,
    required BigInt graceMs,
  });

  /// Emits a [RsDiscoveryEvent] for every observation of a device until
  /// the discovery is stopped. Can only be listened to once.
  ///
  /// Also ends when the multicast sockets failed permanently (e.g. because
  /// the OS invalidated them while the application was suspended): the
  /// application reacts to the ended stream by starting a new discovery,
  /// which rebinds the sockets.
  ///
  /// Also returns when the Dart side of the stream is gone (e.g. after a
  /// hot restart), so this call does not keep the discovery alive forever.
  Stream<RsDiscoveryEvent> listen();

  /// The reason the multicast sockets could not be bound, when they could
  /// not. Discovery then neither hears nor sends announcements.
  Future<String?> multicastError();

  /// Puts a device that reached this device's HTTP server into the store,
  /// e.g. one that answered an announcement by registering. The device is
  /// emitted on [RsDiscovery::listen].
  ///
  /// Only the inbound direction of the address is confirmed: an address
  /// new to the device is stored with [RsOutbound::Untested] and dialed
  /// back in the background, whose outcome is emitted as well.
  Future<void> observeInbound({required RsDiscoveredDevice device});

  /// Records the outcome of a request the application sent to a stored
  /// device over [channel], e.g. a transfer: without an [error] the channel
  /// becomes [RsOutbound::Reachable], with one — the reason, for display —
  /// it becomes [RsOutbound::Failed], which ranks it behind the device's
  /// other channels. The device is emitted on [RsDiscovery::listen].
  ///
  /// Only report failures to reach the device at all, not requests that
  /// the device answered with an error.
  ///
  /// Returns `false` when no device has the fingerprint.
  Future<bool> reportOutbound({required String fingerprint, required RsDeviceChannel channel, String? error});

  /// Scans the `/24` subnet of the local interface address [interface_ip]
  /// by sending every other host a register request, for networks that do
  /// not carry multicast.
  ///
  /// The found devices are emitted on [RsDiscovery::listen] as they answer;
  /// this method returns once the whole scan has finished. At most one scan
  /// runs per interface: a call for an address that is still being scanned
  /// returns immediately.
  Future<void> scanSubnet({required String interfaceIp, required int port, required ProtocolType protocol});

  /// Sets whether announcements of other devices are answered with a
  /// register request (the answer is what makes the announcing device enter
  /// the store). On by default.
  ///
  /// Turned off while the HTTP server is not running: the answer would
  /// advertise a port that nobody listens on.
  Future<void> setAnswerAnnouncements({required bool answer});

  /// Stops the discovery, which also ends the [RsDiscovery::listen] stream.
  /// Returns after all sockets are closed, so the port can be bound again.
  Future<void> stop();
}

/// The address of a device's HTTP server.
class RsDeviceChannel {
  /// The host to dial: an IP address, or the scoped form `fe80::1%3` for
  /// link-local IPv6 (the Rust HTTP client accepts both back as a host).
  final String host;

  /// The port of the device's HTTP server at this address.
  final int port;
  final ProtocolType protocol;

  const RsDeviceChannel({
    required this.host,
    required this.port,
    required this.protocol,
  });

  @override
  int get hashCode => host.hashCode ^ port.hashCode ^ protocol.hashCode;

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is RsDeviceChannel && runtimeType == other.runtimeType && host == other.host && port == other.port && protocol == other.protocol;
}

/// One retained observation of a stored device, for the device details UI.
class RsDeviceLog {
  /// When the observation happened, in milliseconds since the Unix epoch.
  final BigInt timestampMillis;
  final RsDeviceLogEvent event;

  const RsDeviceLog({
    required this.timestampMillis,
    required this.event,
  });

  @override
  int get hashCode => timestampMillis.hashCode ^ event.hashCode;

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is RsDeviceLog && runtimeType == other.runtimeType && timestampMillis == other.timestampMillis && event == other.event;
}

@freezed
sealed class RsDeviceLogEvent with _$RsDeviceLogEvent {
  const RsDeviceLogEvent._();

  /// This device → the peer: a request over the channel was answered.
  const factory RsDeviceLogEvent.outbound({
    required RsDeviceChannel channel,
  }) = RsDeviceLogEvent_Outbound;

  /// This device → the peer: a request over the channel failed.
  const factory RsDeviceLogEvent.outboundFailed({
    required RsDeviceChannel channel,

    /// Why the request failed, for display.
    required String error,
  }) = RsDeviceLogEvent_OutboundFailed;

  /// The peer → this device: the peer sent a request to this device's
  /// server. The channel is the address the request came from, with the
  /// port the peer claims to serve on.
  const factory RsDeviceLogEvent.inbound({
    required RsDeviceChannel channel,
  }) = RsDeviceLogEvent_Inbound;

  /// The peer → this device: an announcement of the peer was heard.
  const factory RsDeviceLogEvent.multicastInbound({
    /// The address the announcement came from, in the scoped form
    /// `fe80::1%3` for link-local IPv6.
    required String host,
  }) = RsDeviceLogEvent_MulticastInbound;
}

/// A device that reached this device's HTTP server, fed into the store via
/// [RsDiscovery::observe_inbound]: its request arrived from
/// [RsDiscoveredDevice::host], which says nothing about whether it can be
/// dialed back there.
class RsDiscoveredDevice {
  final String alias;

  /// Protocol version (major.minor) implemented by the device.
  final String version;
  final String? deviceModel;
  final DeviceType? deviceType;

  /// Fingerprint identifying the device; devices are deduplicated by it.
  final String fingerprint;

  /// The host the request came from: an IP address, or the scoped form
  /// `fe80::1%3` for link-local IPv6 (the Rust HTTP client accepts both
  /// back as a host).
  final String host;

  /// The port the device claims its HTTP server listens on.
  final int port;
  final ProtocolType protocol;

  /// Whether the device's download API is active.
  final bool download;

  const RsDiscoveredDevice({
    required this.alias,
    required this.version,
    this.deviceModel,
    this.deviceType,
    required this.fingerprint,
    required this.host,
    required this.port,
    required this.protocol,
    required this.download,
  });

  @override
  int get hashCode =>
      alias.hashCode ^
      version.hashCode ^
      deviceModel.hashCode ^
      deviceType.hashCode ^
      fingerprint.hashCode ^
      host.hashCode ^
      port.hashCode ^
      protocol.hashCode ^
      download.hashCode;

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is RsDiscoveredDevice &&
          runtimeType == other.runtimeType &&
          alias == other.alias &&
          version == other.version &&
          deviceModel == other.deviceModel &&
          deviceType == other.deviceType &&
          fingerprint == other.fingerprint &&
          host == other.host &&
          port == other.port &&
          protocol == other.protocol &&
          download == other.download;
}

@freezed
sealed class RsDiscoveryEvent with _$RsDiscoveryEvent {
  const RsDiscoveryEvent._();

  /// The state of a confirmed device changed: it was discovered or
  /// confirmed again (answered announcements, scan results and devices fed
  /// in via [RsDiscovery::observe_inbound]), or a request to it failed.
  /// Carries the merged state, so the device re-appears with everything
  /// known about its channels so far.
  const factory RsDiscoveryEvent.device(
    RsStoredDevice field0,
  ) = RsDiscoveryEvent_Device;

  /// A device was heard announcing itself but did not answer the register
  /// request, typically because a firewall blocks its server.
  ///
  /// Nothing about such a device is verified (announcements are
  /// unauthenticated): it is for diagnostics only and must not be offered
  /// as a transfer target.
  const factory RsDiscoveryEvent.unreachable({
    /// The merged state of the device, as its announcements claim it.
    required RsStoredDevice device,

    /// Why the most recent register request failed, for display.
    required String error,
  }) = RsDiscoveryEvent_Unreachable;
}

/// Whether a peer can be dialed on a channel.
enum RsOutbound {
  /// No request was sent over the channel yet: the peer reached this
  /// device from it, which says nothing about the way back.
  untested,

  /// The last request over the channel was answered.
  reachable,

  /// The last request over the channel failed.
  failed,
}

/// An address of a stored device with what is known about each direction: a
/// channel that works one way does not have to work the other way (e.g.
/// because of a firewall on one of the devices).
class RsStoredChannel {
  /// The host to dial: an IP address, or the scoped form `fe80::1%3` for
  /// link-local IPv6 (the Rust HTTP client accepts both back as a host).
  final String host;

  /// The port of the device's HTTP server at this address.
  final int port;
  final ProtocolType protocol;

  /// This device → the peer: whether the peer can be dialed at this address.
  final RsOutbound outbound;

  /// The peer → this device: when the peer last reached this device's
  /// server from this address, in milliseconds since the Unix epoch.
  /// `None` when it never did.
  final BigInt? inboundAtMillis;

  const RsStoredChannel({
    required this.host,
    required this.port,
    required this.protocol,
    required this.outbound,
    this.inboundAtMillis,
  });

  @override
  int get hashCode => host.hashCode ^ port.hashCode ^ protocol.hashCode ^ outbound.hashCode ^ inboundAtMillis.hashCode;

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is RsStoredChannel &&
          runtimeType == other.runtimeType &&
          host == other.host &&
          port == other.port &&
          protocol == other.protocol &&
          outbound == other.outbound &&
          inboundAtMillis == other.inboundAtMillis;
}

/// The merged stored state of a discovered device: one entry per fingerprint,
/// carrying every address the device was observed on. A multi-homed device
/// that is reachable over several network interfaces is still one
/// [RsStoredDevice].
class RsStoredDevice {
  final String alias;

  /// Protocol version (major.minor) implemented by the device.
  final String version;
  final String? deviceModel;
  final DeviceType? deviceType;

  /// Fingerprint identifying the device; devices are deduplicated by it.
  final String fingerprint;

  /// Whether the device's download API is active.
  final bool download;

  /// Every address the device was observed on, in the order to dial them
  /// (reachable before untested before failed, then global IPv6 before IPv4
  /// before link-local, then most recently confirmed first). Never empty:
  /// a device only enters the store through an observation on one of its addresses.
  final List<RsStoredChannel> channels;

  const RsStoredDevice({
    required this.alias,
    required this.version,
    this.deviceModel,
    this.deviceType,
    required this.fingerprint,
    required this.download,
    required this.channels,
  });

  @override
  int get hashCode =>
      alias.hashCode ^ version.hashCode ^ deviceModel.hashCode ^ deviceType.hashCode ^ fingerprint.hashCode ^ download.hashCode ^ channels.hashCode;

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is RsStoredDevice &&
          runtimeType == other.runtimeType &&
          alias == other.alias &&
          version == other.version &&
          deviceModel == other.deviceModel &&
          deviceType == other.deviceType &&
          fingerprint == other.fingerprint &&
          download == other.download &&
          channels == other.channels;
}