fix: watch together bugs and server write serialization

This commit is contained in:
edde746
2026-04-16 14:00:24 +02:00
parent 3cf1ebc09b
commit 1d3ae3e1c5
8 changed files with 193 additions and 132 deletions
@@ -280,6 +280,25 @@ class SyncMessage {
/// Position as Duration (convenience getter)
Duration? get position => positionMs != null ? Duration(milliseconds: positionMs!) : null;
SyncMessage copyWith({String? peerId}) {
return SyncMessage(
type: type,
timestamp: timestamp,
positionMs: positionMs,
bufferingState: bufferingState,
rate: rate,
peerId: peerId ?? this.peerId,
displayName: displayName,
isHost: isHost,
controlMode: controlMode,
pingId: pingId,
ratingKey: ratingKey,
serverId: serverId,
mediaTitle: mediaTitle,
isPlaying: isPlaying,
);
}
/// Serialize to JSON string for sending over data channel
String toJson() {
final map = <String, dynamic>{'t': type.name, 'ts': timestamp};
@@ -79,9 +79,6 @@ class WatchSession {
/// Current connection state
final SessionState state;
/// List of participants in the session
final List<Participant> participants;
/// Error message if state is error
final String? errorMessage;
@@ -102,7 +99,6 @@ class WatchSession {
required this.role,
required this.controlMode,
required this.state,
this.participants = const [],
this.errorMessage,
this.mediaRatingKey,
this.mediaServerId,
@@ -116,15 +112,11 @@ class WatchSession {
/// Whether the session is currently connected
bool get isConnected => state == SessionState.connected;
/// Number of participants (including self)
int get participantCount => participants.length;
WatchSession copyWith({
String? sessionId,
SessionRole? role,
ControlMode? controlMode,
SessionState? state,
List<Participant>? participants,
String? errorMessage,
String? mediaRatingKey,
String? mediaServerId,
@@ -136,7 +128,6 @@ class WatchSession {
role: role ?? this.role,
controlMode: controlMode ?? this.controlMode,
state: state ?? this.state,
participants: participants ?? this.participants,
errorMessage: errorMessage ?? this.errorMessage,
mediaRatingKey: mediaRatingKey ?? this.mediaRatingKey,
mediaServerId: mediaServerId ?? this.mediaServerId,
@@ -163,7 +154,6 @@ class WatchSession {
mediaRatingKey: mediaRatingKey,
mediaServerId: mediaServerId,
mediaTitle: mediaTitle,
participants: [],
);
}
@@ -174,7 +164,6 @@ class WatchSession {
role: SessionRole.guest,
controlMode: ControlMode.hostOnly, // Will be updated when connected
state: SessionState.connecting,
participants: [],
);
}
}
@@ -36,20 +36,22 @@ class WatchTogetherProvider with ChangeNotifier {
// During Watch Together join, 4-5 notifications fire within milliseconds;
// this batches them into one rebuild to avoid overwhelming low-end devices.
bool _notifyScheduled = false;
bool _disposed = false;
@override
void notifyListeners() {
if (_notifyScheduled) return;
if (_disposed || _notifyScheduled) return;
_notifyScheduled = true;
scheduleMicrotask(() {
_notifyScheduled = false;
super.notifyListeners();
if (!_disposed) super.notifyListeners();
});
}
// Host reconnect grace period
Timer? _hostReconnectTimer;
bool _isWaitingForHostReconnect = false;
bool _hostIntentionallyLeft = false;
// Debounce map for action events (peerId+type → last emission timestamp)
final Map<String, int> _lastActionEventMs = {};
@@ -131,7 +133,6 @@ class WatchTogetherProvider with ChangeNotifier {
role: session.role,
controlMode: session.controlMode,
state: session.state,
participants: session.participants,
errorMessage: session.errorMessage,
hostPeerId: session.hostPeerId,
);
@@ -174,6 +175,13 @@ class WatchTogetherProvider with ChangeNotifier {
}
}
/// Wire up reconnection handler to re-announce join after reconnect
void _wireReconnectHandler() {
_peerService!.onReconnected = () {
_syncManager?.announceJoin(_displayName);
};
}
/// Wire up sync manager's state change callback to update provider state
void _wireSyncStateChanges() {
_syncManager!.onSyncStateChanged = (isSyncing) {
@@ -227,6 +235,7 @@ class WatchTogetherProvider with ChangeNotifier {
);
_wireSyncStateChanges();
_wireReconnectHandler();
notifyListeners();
appLogger.d('WatchTogether: Session created: $createdSessionId');
@@ -276,6 +285,7 @@ class WatchTogetherProvider with ChangeNotifier {
};
_wireSyncStateChanges();
_wireReconnectHandler();
// Add self to participants
_participants.add(Participant(peerId: _peerService!.myPeerId!, displayName: _displayName, isHost: false));
@@ -298,25 +308,15 @@ class WatchTogetherProvider with ChangeNotifier {
///
/// Returns `true` if the user became the host.
Future<bool> enterRoom(String sessionId, {ControlMode controlMode = ControlMode.anyone, String? displayName}) async {
// Probe the relay to determine if the room exists, then delegate to
// the existing createSession / joinSession which handle all setup.
final customRelayUrl = SettingsService.instanceOrNull?.getCustomRelayUrl();
final probe = WatchTogetherPeerService(customBaseUrl: customRelayUrl);
try {
final becameHost = await probe.joinOrCreateSession(sessionId);
final shouldBeHost = becameHost || probe.connectedPeers.isEmpty;
await probe.disconnect();
probe.dispose();
if (shouldBeHost) {
await joinSession(sessionId, displayName: displayName);
return false; // joined as guest
} on PeerError catch (e) {
// Room doesn't exist — create it as host
if (e.serverCode == 'room_not_found') {
await createSession(controlMode: controlMode, displayName: displayName, sessionId: sessionId);
} else {
await joinSession(sessionId, displayName: displayName);
return true;
}
return shouldBeHost;
} catch (e) {
await probe.disconnect();
probe.dispose();
rethrow;
}
}
@@ -358,6 +358,7 @@ class WatchTogetherProvider with ChangeNotifier {
_isDeferredPlay = false;
_lastHandledCurrentPlaybackKey = null;
_lastActionEventMs.clear();
_hostIntentionallyLeft = false;
notifyListeners();
appLogger.d('WatchTogether: Session left');
@@ -410,8 +411,9 @@ class WatchTogetherProvider with ChangeNotifier {
_participants.removeWhere((p) => p.peerId == peerId);
// If host disconnected, start grace period for reconnection
if (!isHost && peerId == _session?.hostPeerId) {
// If host disconnected unexpectedly, start grace period for reconnection.
// Skip if the host already sent a deliberate leave message.
if (!isHost && peerId == _session?.hostPeerId && !_hostIntentionallyLeft) {
_startHostReconnectGracePeriod();
} else if (disconnectedName != null) {
_participantEventController.add(
@@ -459,16 +461,16 @@ class WatchTogetherProvider with ChangeNotifier {
_participantEventController.add(
ParticipantEvent(displayName: message.displayName!, type: ParticipantEventType.joined),
);
}
// Send our join info back so the new peer adds us to their
// participant list. Every peer does this (not just the host)
// so that late joiners learn about all existing participants.
if (_peerService != null) {
_peerService!.sendTo(
message.peerId!,
SyncMessage.join(peerId: _peerService!.myPeerId!, displayName: _displayName, isHost: isHost),
);
// Send our join info back so the new peer adds us to their
// participant list. Only reply to NEW peers to avoid an
// infinite join ping-pong (A→join→B→join→A→...).
if (_peerService != null) {
_peerService!.sendTo(
message.peerId!,
SyncMessage.join(peerId: _peerService!.myPeerId!, displayName: _displayName, isHost: isHost),
);
}
}
notifyListeners();
@@ -487,6 +489,14 @@ class WatchTogetherProvider with ChangeNotifier {
ParticipantEvent(displayName: leavingName, type: ParticipantEventType.left),
);
}
// If the host deliberately left, end the session immediately
// instead of waiting for the 15s reconnect grace period.
if (!isHost && message.peerId == _session?.hostPeerId) {
_hostIntentionallyLeft = true;
_handleHostExitedPlayer(message);
}
notifyListeners();
}
break;
@@ -739,6 +749,7 @@ class WatchTogetherProvider with ChangeNotifier {
@override
void dispose() {
_disposed = true;
_cancelHostReconnectGracePeriod();
_participantEventController.close();
leaveSession();
@@ -59,6 +59,9 @@ class WatchTogetherPeerService with KeepaliveMixin {
static const int _maxReconnectAttempts = 3;
Timer? _reconnectTimer;
/// Called after a successful reconnection so the provider can re-announce join.
void Function()? onReconnected;
// Keepalive (via KeepaliveMixin)
@override
Duration get pingInterval => const Duration(seconds: 15);
@@ -192,10 +195,16 @@ class WatchTogetherPeerService with KeepaliveMixin {
case 'message':
final payload = msg['payload'];
final serverFrom = msg['from'] as String?;
if (payload != null) {
try {
final payloadStr = payload is String ? payload : jsonEncode(payload);
final syncMsg = SyncMessage.fromJson(payloadStr);
var syncMsg = SyncMessage.fromJson(payloadStr);
// Use the server-authenticated sender ID instead of the
// self-reported peerId in the payload to prevent spoofing.
if (serverFrom != null && syncMsg.peerId != serverFrom) {
syncMsg = syncMsg.copyWith(peerId: serverFrom);
}
_safeAdd(_messageReceivedController, syncMsg);
} catch (e) {
appLogger.e('WatchTogether: Failed to parse sync message payload', error: e);
@@ -206,7 +215,7 @@ class WatchTogetherPeerService with KeepaliveMixin {
final code = msg['code'] as String? ?? 'unknown';
final message = msg['message'] as String? ?? 'Unknown error';
appLogger.e('WatchTogether: Server error: $code - $message');
final error = PeerError(type: PeerErrorType.serverError, message: '$code: $message');
final error = PeerError(type: PeerErrorType.serverError, message: '$code: $message', serverCode: code);
_safeAdd(_errorController, error);
if (setupCompleter != null && !setupCompleter.isCompleted) {
setupCompleter.completeError(error);
@@ -292,15 +301,27 @@ class WatchTogetherPeerService with KeepaliveMixin {
_listenToChannel(channel, setupCompleter: completer);
startKeepalive();
// Re-send create or join
if (_isHost) {
_sendRaw({'type': 'create', 'sessionId': _sessionId, 'peerId': _myPeerId});
} else {
_sendRaw({'type': 'join', 'sessionId': _sessionId, 'peerId': _myPeerId});
// Always try join first — the room may still have peers (e.g. host
// reconnecting while guests remain). Fall back to create only if
// the room no longer exists and we were the host.
_sendRaw({'type': 'join', 'sessionId': _sessionId, 'peerId': _myPeerId});
try {
await completer.future.namedTimeout(const Duration(seconds: 10), operation: 'WatchTogether reconnect');
} on PeerError catch (e) {
if (_isHost && e.serverCode == 'room_not_found') {
appLogger.d('WatchTogether: Room gone, re-creating as host');
final createCompleter = Completer<void>();
_listenToChannel(channel, setupCompleter: createCompleter);
_sendRaw({'type': 'create', 'sessionId': _sessionId, 'peerId': _myPeerId});
await createCompleter.future.namedTimeout(const Duration(seconds: 10), operation: 'WatchTogether reconnect create');
} else {
rethrow;
}
}
await completer.future.namedTimeout(const Duration(seconds: 10), operation: 'WatchTogether reconnect');
appLogger.d('WatchTogether: Reconnected successfully');
onReconnected?.call();
} catch (e) {
appLogger.e('WatchTogether: Reconnect failed', error: e);
_handleWebSocketClosed();
@@ -384,20 +405,6 @@ class WatchTogetherPeerService with KeepaliveMixin {
}
}
/// Try to join a session; if it doesn't exist, create it as host.
///
/// Returns `true` if the user became the host (room was empty).
Future<bool> joinOrCreateSession(String sessionId) async {
try {
await joinSession(sessionId);
return false; // joined as guest
} on PeerError catch (e) {
if (e.type != PeerErrorType.serverError) rethrow;
await createSession(sessionId: sessionId);
return true; // created as host
}
}
/// Broadcast a message to all connected peers
void broadcast(SyncMessage message) {
final payload = message.toJson();
@@ -228,7 +228,7 @@ class WatchTogetherSyncManager {
} finally {
_isRemoteAction = false;
}
_broadcastPlayPause(true);
// Don't broadcast play — deferred play will broadcast when all peers are ready.
return;
}
@@ -539,20 +539,6 @@ class WatchTogetherSyncManager {
return;
}
// HOST RELAY: In "anyone" mode, host rebroadcasts control commands from guests
// This is needed because guests only connect to host (star topology), not to each other
if (_session.isHost && _session.controlMode == ControlMode.anyone) {
final isControlMessage =
message.type == SyncMessageType.play ||
message.type == SyncMessageType.pause ||
message.type == SyncMessageType.seek ||
message.type == SyncMessageType.rate;
if (isControlMessage) {
_peerService.broadcast(message);
}
}
// In hostOnly mode, only process messages from host (unless it's join/leave/sessionConfig)
if (_session.controlMode == ControlMode.hostOnly && !_session.isHost) {
final isHostMessage = message.peerId == _session.hostPeerId;
@@ -669,11 +655,14 @@ class WatchTogetherSyncManager {
if (_deferredPlay && isAllReady) {
_setDeferredPlay(false);
_firstPlayCompleted = true;
final pos = _deferredPlayPosition;
_deferredPlayPosition = null;
await _applyRemotePlay(
position: _deferredPlayPosition,
position: pos,
expectedAttachmentGeneration: queuedAttachmentGeneration,
);
_deferredPlayPosition = null;
// Broadcast play to all peers now that everyone is ready
_broadcastPlayPause(true);
}
}
break;