Files
openchamber-android-native/lib/api/relay_transport.dart
T
blumia 7b5bccf28f feat: English and Chinese, and selectable chat text
- settings → general → language picks system, Chinese or English; the
  choice is stored on the device and read before the first frame
- our Chinese strings are translated through tr()/trArgs() and AppText,
  with the English in lib/l10n/en_*.dart; a missing entry falls back to
  Chinese and a test checks that every literal in lib has one
- AppText rebuilds on a language change (it depends on the resolved
  locale), so const text and whole pages switch at once; the built-in
  date/time pickers and selection menu follow the same language
- server and user data (titles, messages, prompts, paths) is never
  translated
- the chat list sits in a SelectionArea: long-press selects message text
  and shows the copy/select-all menu
- bump to 0.5.2
2026-11-26 09:04:25 +08:00

114 lines
3.6 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// The server as reached through the private relay: every request and socket
// rides the E2EE tunnel started from the pairing link's relay candidate.
import 'dart:async';
import 'dart:convert';
import '../l10n.dart';
import '../version.dart';
import 'relay_tunnel.dart';
import 'transport.dart';
class RelayTransport implements Transport {
final RelayTunnel _tunnel;
String? _bearer;
String? _urlToken;
DateTime _urlTokenExpiresAt = DateTime.fromMillisecondsSinceEpoch(0);
Future<String>? _minting;
RelayTransport({
required String relayUrl,
required String serverId,
required Map<String, dynamic> hostKey,
String? grant,
String? version,
}) : _tunnel = RelayTunnel(
relayUrl: relayUrl,
serverId: serverId,
hostKey: hostKey,
grant: grant,
// Read at construction: the version is known once the app has
// started, which is after this default would have been fixed.
appVersion: version ?? appVersion,
);
@override
Future<TransportResponse> send(TransportRequest request) =>
_tunnel.send(request);
@override
Future<TransportSocket> webSocket(String path,
{String? rawQuery, Map<String, String> headers = const {}}) async {
final token = await _mintUrlToken();
final query = [
if (rawQuery != null && rawQuery.isNotEmpty) rawQuery,
if (token.isNotEmpty) 'oc_url_token=${Uri.encodeQueryComponent(token)}',
].join('&');
return _tunnel.openWebSocket(path, rawQuery: query, headers: headers);
}
@override
void setBearerToken(String? token) {
if (_bearer != token) {
_bearer = token;
_urlToken = null;
_urlTokenExpiresAt = DateTime.fromMillisecondsSinceEpoch(0);
}
}
/// WebSocket upgrades cannot carry headers, so the host expects a short-lived
/// URL-scoped token minted over the same tunnel with the bearer.
Future<String> _mintUrlToken() async {
final bearer = _bearer;
if (bearer == null || bearer.isEmpty) return '';
if (_urlToken != null && _urlToken!.isNotEmpty &&
DateTime.now().isBefore(_urlTokenExpiresAt)) {
return _urlToken!;
}
final inFlight = _minting;
if (inFlight != null) return inFlight;
final future = _mint(bearer);
_minting = future;
try {
return await future;
} finally {
_minting = null;
}
}
Future<String> _mint(String bearer) async {
final response = await _tunnel.send(TransportRequest(
method: 'POST',
path: '/auth/url-token',
headers: {'authorization': 'Bearer $bearer', 'accept': 'application/json'},
));
final bytes = await response.body
.fold<List<int>>(<int>[], (all, chunk) => all..addAll(chunk));
if (response.status < 200 || response.status >= 300) {
throw RelayTunnelException(trArgs('无法获取 WebSocket 令牌({0})', [response.status]));
}
try {
final decoded = jsonDecode(utf8.decode(bytes, allowMalformed: true));
if (decoded is! Map) return '';
final token = decoded['token'];
if (token is! String) return '';
final expiresIn = decoded['expiresIn'];
final expiresAt = decoded['expiresAt'];
final lifetime = expiresIn is num
? Duration(seconds: expiresIn.toInt())
: expiresAt is num && expiresAt > 0
? Duration(milliseconds: expiresAt.toInt())
: const Duration(minutes: 4);
_urlToken = token.trim();
_urlTokenExpiresAt = DateTime.now()
.add(lifetime)
.subtract(const Duration(seconds: 20));
return _urlToken!;
} catch (_) {
return '';
}
}
@override
void close() => _tunnel.close();
}