Skip to content

PasteFerry (隔空贴): clipboard and file sync across macOS, Windows and Linux. Direct-first, end-to-end encrypted. Optional official access: no server to host. Independent self-hosting remains available.

4.3 KB
Raw Blame
import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:grpc/grpc.dart';

import 'gen/pasteferry/v1/daemon.pbgrpc.dart';

/// daemon 写在数据目录下的握手信息。
///
/// daemon 监听 127.0.0.1 的随机端口,把端口与一次性 token 写进 daemon.json。
/// 用 token 是因为本机任意进程都能连上回环端口,仅"只监听 127.0.0.1"不够。
class DaemonEndpoint {
  const DaemonEndpoint({
    required this.port,
    required this.token,
    required this.pid,
    required this.version,
  });

  final int port;
  final String token;
  final int pid;
  final String version;

  factory DaemonEndpoint.fromJson(Map<String, dynamic> json) => DaemonEndpoint(
        port: json['port'] as int,
        token: json['token'] as String,
        pid: json['pid'] as int? ?? 0,
        version: json['version'] as String? ?? '',
      );

  /// 数据目录。必须与 Go 侧 config.DefaultPaths() 完全一致,
  /// 否则 UI 找不到 daemon。
  ///
  /// 刻意不用 path_provider:它在 macOS 上返回的是
  /// `~/Library/Application Support/<bundle_id>`,与 daemon 用的
  /// `~/Library/Application Support/PasteFerry` 并不是同一个位置。
  static String defaultDataDir() {
    // Android:Go 核心跑在 App 进程里,数据目录由 Kotlin 宿主给出(mobile/host.dart)
    final android = androidDataDir;
    if (android != null) return android;
    if (Platform.isMacOS) {
      final home = Platform.environment['HOME'] ?? '';
      return '$home/Library/Application Support/PasteFerry';
    }
    if (Platform.isWindows) {
      final base = Platform.environment['LOCALAPPDATA'] ??
          Platform.environment['APPDATA'] ??
          '';
      return '$base\\PasteFerry';
    }
    // Linux:按 XDG 放在 ~/.local/share 下,XDG_DATA_HOME 是绝对路径时以它为准
    final env = Platform.environment;
    final data = env['XDG_DATA_HOME'] ?? '';
    final base = data.startsWith('/') ? data : '${env['HOME'] ?? ''}/.local/share';
    return '$base/pasteferry';
  }

  /// Android 上 App 私有目录里的数据目录,启动时由宿主设置。
  static String? androidDataDir;

  static File endpointFile([String? dataDir]) =>
      File('${dataDir ?? defaultDataDir()}${Platform.pathSeparator}daemon.json');

  static Future<DaemonEndpoint> read([String? dataDir]) async {
    final file = endpointFile(dataDir);
    if (!await file.exists()) {
      throw DaemonNotRunning('未找到 ${file.path}');
    }
    final raw = jsonDecode(await file.readAsString()) as Map<String, dynamic>;
    return DaemonEndpoint.fromJson(raw);
  }
}

class DaemonNotRunning implements Exception {
  DaemonNotRunning(this.detail);
  final String detail;
  @override
  String toString() => 'daemon 未运行($detail)';
}

/// 与 daemon 的一条 gRPC 连接。
class DaemonConnection {
  DaemonConnection._(this._channel, this.client, this.endpoint);

  final ClientChannel _channel;
  final DaemonServiceClient client;
  final DaemonEndpoint endpoint;

  static Future<DaemonConnection> connect({
    String? dataDir,
    Duration requestTimeout = const Duration(seconds: 15),
  }) async {
    final ep = await DaemonEndpoint.read(dataDir);
    final channel = ClientChannel(
      '127.0.0.1',
      port: ep.port,
      options: const ChannelOptions(
        credentials: ChannelCredentials.insecure(),
        // daemon 在本机,握手应当很快;连不上就尽快报错而不是干等
        connectionTimeout: Duration(seconds: 5),
      ),
    );
    final client = DaemonServiceClient(
      channel,
      options: CallOptions(metadata: {'x-pasteferry-token': ep.token}),
      interceptors: [_RequestDeadline(requestTimeout)],
    );
    return DaemonConnection._(channel, client, ep);
  }

  Future<void> close() => _channel.shutdown();
}

/// 本机连接建立后,单次请求也必须有期限。事件订阅和下载等流式请求保持长连接。
class _RequestDeadline extends ClientInterceptor {
  _RequestDeadline(this.timeout);

  final Duration timeout;

  @override
  ResponseFuture<R> interceptUnary<Q, R>(
    ClientMethod<Q, R> method,
    Q request,
    CallOptions options,
    ClientUnaryInvoker<Q, R> invoker,
  ) {
    return invoker(
      method,
      request,
      options.timeout == null
          ? options.mergedWith(CallOptions(timeout: timeout))
          : options,
    );
  }
}