Compare commits

..

1 Commits

Author SHA1 Message Date
Koala 4d294cee33 fix(ui): tooltips, full emoji map, and onboarding layout 2026-05-25 23:37:05 +02:00
18 changed files with 225 additions and 843 deletions
+1 -1
View File
@@ -8,7 +8,7 @@
<a href="https://chromewebstore.google.com/detail/koalasync/obbnmkmlaaddodakcbdljknjpagklifc"><img src="https://img.shields.io/badge/Chrome-Download-blue?logo=googlechrome&logoColor=white" alt="Chrome Extension"></a>
</p>
<p align="center"><i>KoalaSync is a lightweight Browser Extension and Relay Server for synchronized video playback on almost any website with a video element—YouTube, Twitch, Netflix, Emby, Jellyfin, and beyond. Built with a focus on <b>Data Sovereignty</b> and <b>Performance</b>.</i></p>
<p align="center"><i>KoalaSync is a lightweight Browser Extension and Relay Server for synchronized video playback across any website—YouTube, Twitch, Netflix, and custom HTML5 players. Built with a focus on <b>Data Sovereignty</b> and <b>Performance</b>.</i></p>
### 🌟 Why KoalaSync?
+16 -180
View File
@@ -1,5 +1,4 @@
import { EVENTS, PROTOCOL_VERSION, OFFICIAL_SERVER_URL, OFFICIAL_SERVER_TOKEN, APP_VERSION, EPISODE_LOBBY_TIMEOUT, FORCE_SYNC_TIMEOUT } from './shared/constants.js';
import { generateUsername } from './shared/names.js';
// --- State Management ---
let socket = null;
@@ -16,23 +15,6 @@ let pendingHistory = [];
let eventQueue = [];
let isNamespaceJoined = false;
let lastActionState = { action: null, senderId: null, timestamp: 0, acks: [] };
let localSeq = 0; // Monotonically increasing command sequence for this peer
const lastSeqBySender = {}; // senderId → last received seq (stale command guard)
const activePorts = new Set(); // New: track active content ports for keep-alive
// --- Keep-Alive Port Listener ---
chrome.runtime.onConnect.addListener((port) => {
if (port.name === 'keepAlive') {
activePorts.add(port);
port.onDisconnect.addListener(() => {
activePorts.delete(port);
});
}
});
function _persistLastSeq() {
if (storageInitialized) chrome.storage.session.set({ lastSeqBySender });
}
// --- Boot Sequence Lock ---
let restorationTask = null;
@@ -53,7 +35,7 @@ function ensureState() {
'logs', 'history', 'currentRoom', 'lastActionState',
'eventQueue', 'isForceSyncInitiator', 'forceSyncAcks',
'forceSyncDeadline', 'reconnectFailed', 'reconnectStartTime', 'currentTabId', 'currentTabTitle',
'episodeLobby', 'localSeq', 'lastSeqBySender'
'episodeLobby'
], (data) => {
clearTimeout(storageTimeout);
if (data.currentTabId !== undefined) currentTabId = data.currentTabId;
@@ -102,9 +84,6 @@ function ensureState() {
}
}
if (data.localSeq !== undefined && !isNaN(data.localSeq)) localSeq = data.localSeq;
if (data.lastSeqBySender && typeof data.lastSeqBySender === 'object') Object.assign(lastSeqBySender, data.lastSeqBySender);
storageInitialized = true;
// Process any early logs/history that weren't captured in the spread
@@ -146,26 +125,6 @@ let forceSyncTimeout = null;
let episodeLobby = null; // { expectedTitle, initiatorPeerId, readyPeers: [], createdAt }
let episodeLobbyTimeout = null;
// --- Episode Title Extraction (synced with content.js) ---
function extractEpisodeId(title) {
if (!title || typeof title !== 'string') return null;
const se = title.match(/S(?:eason\s*)?(\d+)[\s\-\.]*E(?:pisode\s*)?(\d+)/i);
if (se) return `S${String(se[1]).padStart(2, '0')}E${String(se[2]).padStart(2, '0')}`;
const ep = title.match(/(?:Episode|Folge|Ep\.?|#)\s*(\d+)/i);
if (ep) return `EP${String(ep[1]).padStart(3, '0')}`;
return null;
}
function sameEpisode(titleA, titleB) {
if (!titleA && !titleB) return true; // Both unknown → assume same (backward compat)
if (!titleA || !titleB) return false; // One unknown, one known → different
const idA = extractEpisodeId(titleA);
const idB = extractEpisodeId(titleB);
if (idA && idB) return idA === idB; // Both have parseable IDs → compare IDs
if (idA || idB) return false; // One has ID, other doesn't → different
return titleA === titleB; // Neither has ID → exact string match
}
// --- Storage Utils ---
/**
@@ -227,7 +186,9 @@ async function getSettings() {
}
let username = data.username;
if (!username) {
username = generateUsername();
const adjs = ['Happy', 'Cool', 'Fast', 'Smart', 'Brave', 'Calm', 'Sneaky', 'Lazy', 'Wild', 'Chill', 'Lucky', 'Epic', 'Swift', 'Bold', 'Mighty', 'Cosmic', 'Neon', 'Shadow', 'Crystal', 'Thunder', 'Silent', 'Golden', 'Fierce', 'Noble', 'Mystic', 'Frozen', 'Blazing', 'Sapphire', 'Iron', 'Crimson'];
const nouns = ['Koala', 'Panda', 'Tiger', 'Eagle', 'Fox', 'Bear', 'Wolf', 'Lion', 'Hawk', 'Seal', 'Owl', 'Shark', 'Dragon', 'Phoenix', 'Falcon', 'Panther', 'Raven', 'Cobra', 'Lynx', 'Jaguar', 'Orca', 'Mantis', 'Viper', 'Condor', 'Badger', 'Otter', 'Rhino', 'Crane', 'Mongoose', 'Specter'];
username = `${adjs[Math.floor(Math.random() * adjs.length)]}${nouns[Math.floor(Math.random() * nouns.length)]}`;
chrome.storage.sync.set({ username }, () => {
resolve({
serverUrl: data.serverUrl || '',
@@ -573,47 +534,9 @@ function handleServerEvent(event, data) {
currentRoom = data;
if (currentRoom && Array.isArray(currentRoom.peers)) {
currentRoom.peers = currentRoom.peers.map(p => typeof p === 'object' ? createPeerData(p) : { peerId: p, username: null, tabTitle: null, mediaTitle: null, playbackState: null, currentTime: null, volume: null, muted: null, lastHeartbeat: Date.now() });
// Clear sequence tracking for peers that are no longer in the room
const activePeerIds = new Set(currentRoom.peers.map(p => typeof p === 'object' ? p.peerId : p));
Object.keys(lastSeqBySender).forEach(pId => {
if (!activePeerIds.has(pId)) {
delete lastSeqBySender[pId];
}
});
_persistLastSeq();
} else if (currentRoom) {
currentRoom.peers = [];
}
// Recover server-tracked active Episode Lobby if present
if (data && data.activeLobby && !episodeLobby) {
episodeLobby = {
expectedTitle: data.activeLobby.expectedTitle,
initiatorPeerId: data.activeLobby.initiatorPeerId,
readyPeers: data.activeLobby.readyPeers,
createdAt: Date.now()
};
persistEpisodeLobby();
broadcastLobbyUpdate();
addLog(`Recovered active episode lobby from server: "${episodeLobby.expectedTitle}"`, 'info');
// Notify content script to start polling
if (currentTabId) {
const tabId = parseInt(currentTabId);
if (!isNaN(tabId)) {
chrome.tabs.sendMessage(tabId, {
type: 'EPISODE_LOBBY',
expectedTitle: episodeLobby.expectedTitle
}).catch(() => {});
}
}
// Schedule timeout if we don't already have one
if (!episodeLobbyTimeout) {
episodeLobbyTimeout = setTimeout(() => cancelEpisodeLobby('Timeout'), EPISODE_LOBBY_TIMEOUT);
}
}
if (storageInitialized) chrome.storage.session.set({ currentRoom });
addLog(`Joined Room: ${data?.roomId || 'unknown'}`, 'success');
chrome.runtime.sendMessage({ type: 'PEER_UPDATE', peers: data.peers }).catch(() => {});
@@ -653,15 +576,6 @@ function handleServerEvent(event, data) {
case EVENTS.PAUSE:
case EVENTS.SEEK:
case EVENTS.FORCE_SYNC_PREPARE:
if (data.senderId && typeof data.seq === 'number') {
const lastSeq = lastSeqBySender[data.senderId];
if (lastSeq !== undefined && data.seq <= lastSeq) {
addLog(`Ignored stale ${event} from ${data.senderId} (seq ${data.seq} <= ${lastSeq})`, 'warn');
break;
}
lastSeqBySender[data.senderId] = data.seq;
_persistLastSeq();
}
if (data.senderId) {
addToHistory(event, data.senderId);
showNotification(data.senderId, event);
@@ -678,12 +592,6 @@ function handleServerEvent(event, data) {
routeToContent(event, data);
break;
case EVENTS.FORCE_SYNC_ACK:
if (data.senderId && typeof data.seq === 'number') {
const lastSeq = lastSeqBySender[data.senderId];
if (lastSeq !== undefined && data.seq <= lastSeq) break;
lastSeqBySender[data.senderId] = data.seq;
_persistLastSeq();
}
if (isForceSyncInitiator) {
forceSyncAcks.add(data.senderId);
chrome.storage.session.set({ forceSyncAcks: Array.from(forceSyncAcks) });
@@ -713,12 +621,6 @@ function handleServerEvent(event, data) {
}
break;
case EVENTS.FORCE_SYNC_EXECUTE:
if (data?.senderId && typeof data.seq === 'number') {
const lastSeq = lastSeqBySender[data.senderId];
if (lastSeq !== undefined && data.seq <= lastSeq) break;
lastSeqBySender[data.senderId] = data.seq;
_persistLastSeq();
}
if (data?.senderId) {
addToHistory(event, data.senderId);
showNotification(data.senderId, event);
@@ -765,9 +667,6 @@ function handleServerEvent(event, data) {
if (!Array.isArray(currentRoom.peers)) currentRoom.peers = [];
if (data.status === 'joined') {
if (!currentRoom.peers.find(p => (p.peerId || p) === data.peerId)) {
delete lastSeqBySender[data.peerId];
_persistLastSeq();
currentRoom.peers.push(createPeerData(data));
if (storageInitialized) chrome.storage.session.set({ currentRoom });
chrome.runtime.sendMessage({ type: 'PEER_UPDATE', peers: currentRoom.peers }).catch(() => {});
@@ -802,14 +701,12 @@ function handleServerEvent(event, data) {
peer.muted = data.muted !== undefined ? data.muted : peer.muted;
const timeSinceReactive = peer.lastReactiveUpdate ? (Date.now() - peer.lastReactiveUpdate) : Infinity;
const ignoreStatus = timeSinceReactive < 300;
const ignoreStatus = timeSinceReactive < 1000;
if (!ignoreStatus) {
peer.playbackState = data.playbackState !== undefined ? data.playbackState : peer.playbackState;
peer.currentTime = data.currentTime !== undefined ? data.currentTime : peer.currentTime;
if (data.playbackState !== undefined || data.currentTime !== undefined) {
peer.lastHeartbeat = Date.now();
}
peer.lastHeartbeat = Date.now();
}
} else {
// Migration: replace string peer with normalized object
@@ -826,7 +723,7 @@ function handleServerEvent(event, data) {
if (data.senderId && data.expectedTitle) {
addLog(`Episode lobby from ${data.senderId}: "${data.expectedTitle}"`, 'info');
// If we already have a lobby for this same title, treat as dedup
if (episodeLobby && sameEpisode(episodeLobby.expectedTitle, data.expectedTitle)) {
if (episodeLobby && episodeLobby.expectedTitle === data.expectedTitle) {
break; // Already tracking this lobby
}
// Cancel any existing lobby before starting a new one
@@ -835,7 +732,7 @@ function handleServerEvent(event, data) {
episodeLobby = {
expectedTitle: data.expectedTitle,
initiatorPeerId: data.senderId,
readyPeers: [data.senderId], // Initiator is already ready
readyPeers: [],
createdAt: Date.now()
};
persistEpisodeLobby();
@@ -898,11 +795,8 @@ function executeForceSync() {
const executionTimestamp = Date.now();
updateLastAction(EVENTS.FORCE_SYNC_EXECUTE, 'You', executionTimestamp);
localSeq++;
chrome.storage.session.set({ localSeq });
emit(EVENTS.FORCE_SYNC_EXECUTE, { actionTimestamp: executionTimestamp, seq: localSeq });
routeToContent(EVENTS.FORCE_SYNC_EXECUTE, { actionTimestamp: executionTimestamp, seq: localSeq });
emit(EVENTS.FORCE_SYNC_EXECUTE, { actionTimestamp: executionTimestamp });
routeToContent(EVENTS.FORCE_SYNC_EXECUTE, { actionTimestamp: executionTimestamp });
addLog('Force Sync Executed', 'success');
}
@@ -967,10 +861,8 @@ function executeEpisodeLobby() {
});
const syncPayload = { targetTime: 0.0 };
localSeq++;
chrome.storage.session.set({ localSeq });
emit(EVENTS.FORCE_SYNC_PREPARE, { ...syncPayload, peerId, actionTimestamp: timestamp, seq: localSeq });
routeToContent(EVENTS.FORCE_SYNC_PREPARE, { ...syncPayload, actionTimestamp: timestamp, seq: localSeq });
emit(EVENTS.FORCE_SYNC_PREPARE, { ...syncPayload, peerId, actionTimestamp: timestamp });
routeToContent(EVENTS.FORCE_SYNC_PREPARE, { ...syncPayload, actionTimestamp: timestamp });
forceSyncTimeout = setTimeout(() => {
if (isForceSyncInitiator) {
@@ -1028,10 +920,6 @@ async function routeToContent(action, payload) {
const actionTimestamp = payload?.actionTimestamp || Date.now();
const commandSenderId = payload?.senderId || null;
_routeToContentInternal(tabId, action, payload, actionTimestamp, commandSenderId, 0);
}
function _routeToContentInternal(tabId, action, payload, actionTimestamp, commandSenderId, retries) {
chrome.tabs.sendMessage(tabId, {
type: 'SERVER_COMMAND',
action,
@@ -1039,18 +927,12 @@ function _routeToContentInternal(tabId, action, payload, actionTimestamp, comman
actionTimestamp,
commandSenderId
}).catch(err => {
if (retries >= 3) {
addLog(`Content Script not responding in tab ${tabId} after ${retries} retries`, 'warn');
currentTabId = null;
updateBadgeStatus();
return;
}
if (err.message.includes('Receiving end does not exist') || err.message.includes('Extension context invalidated')) {
chrome.scripting.executeScript({
target: { tabId },
files: ['content.js']
}).then(() => {
setTimeout(() => _routeToContentInternal(tabId, action, payload, actionTimestamp, commandSenderId, retries + 1), 500);
setTimeout(() => routeToContent(action, payload), 500);
}).catch(_err => {
addLog(`Auto-reinject failed for tab ${tabId}`, 'warn');
});
@@ -1253,13 +1135,10 @@ async function handleAsyncMessage(message, sender, sendResponse) {
} else if (message.type === 'CONTENT_EVENT') {
const processEvent = () => {
const timestamp = Date.now();
localSeq++;
chrome.storage.session.set({ localSeq });
updateLastAction(message.action, 'You', timestamp);
lastActionState.targetTime = message.payload?.targetTime !== undefined ? message.payload.targetTime : message.payload?.currentTime;
if (storageInitialized) chrome.storage.session.set({ lastActionState });
message.payload.actionTimestamp = timestamp;
message.payload.seq = localSeq;
// Local Reactive Update
updateLocalPeerState(peerId, {
@@ -1280,7 +1159,6 @@ async function handleAsyncMessage(message, sender, sendResponse) {
routeToContent(EVENTS.FORCE_SYNC_PREPARE, message.payload);
if (forceSyncTimeout) clearTimeout(forceSyncTimeout);
forceSyncTimeout = setTimeout(() => {
if (isForceSyncInitiator) {
addLog('Force Sync: Timeout waiting for ACKs, executing anyway...', 'warn');
@@ -1289,16 +1167,6 @@ async function handleAsyncMessage(message, sender, sendResponse) {
}, FORCE_SYNC_TIMEOUT);
}
addToHistory(message.action, 'You');
const isNonEssentialEvent = message.action === EVENTS.PLAY || message.action === EVENTS.PAUSE || message.action === EVENTS.SEEK;
const otherCount = currentRoom && Array.isArray(currentRoom.peers) ? currentRoom.peers.filter(p => (typeof p === 'object' ? p.peerId : p) !== peerId).length : 0;
const hasOtherPeers = otherCount > 0;
if (isNonEssentialEvent && !hasOtherPeers) {
sendResponse({ status: 'ok_solo' });
return;
}
emit(message.action, { ...message.payload, peerId });
sendResponse({ status: 'ok' });
};
@@ -1338,9 +1206,7 @@ async function handleAsyncMessage(message, sender, sendResponse) {
executeForceSync();
}
} else {
localSeq++;
chrome.storage.session.set({ localSeq });
emit(EVENTS.FORCE_SYNC_ACK, { peerId, seq: localSeq });
emit(EVENTS.FORCE_SYNC_ACK, { peerId });
}
sendResponse({ status: 'ok' });
} else if (message.type === 'CMD_ACK') {
@@ -1435,7 +1301,7 @@ async function handleAsyncMessage(message, sender, sendResponse) {
}
// If lobby already exists for this title, just mark self ready
if (episodeLobby && sameEpisode(episodeLobby.expectedTitle, newTitle)) {
if (episodeLobby && episodeLobby.expectedTitle === newTitle) {
if (!episodeLobby.readyPeers.includes(peerId)) {
episodeLobby.readyPeers.push(peerId);
persistEpisodeLobby();
@@ -1482,7 +1348,7 @@ async function handleAsyncMessage(message, sender, sendResponse) {
sendResponse({ status: 'lobby_created' });
} else if (message.type === 'EPISODE_READY_LOCAL') {
// Content script confirmed it loaded the lobby episode
if (episodeLobby && message.payload && sameEpisode(message.payload.title, episodeLobby.expectedTitle)) {
if (episodeLobby && message.payload && message.payload.title === episodeLobby.expectedTitle) {
if (!episodeLobby.readyPeers.includes(peerId)) {
episodeLobby.readyPeers.push(peerId);
persistEpisodeLobby();
@@ -1509,41 +1375,11 @@ async function handleAsyncMessage(message, sender, sendResponse) {
// Tab removal listener
chrome.tabs.onRemoved.addListener((tabId) => {
if (tabId === currentTabId) {
const wasInRoom = !!currentRoom;
currentTabId = null;
currentTabTitle = null;
chrome.storage.session.set({ currentTabId: null, currentTabTitle: null });
updateBadgeStatus();
addLog('Target tab closed.', 'warn');
if (wasInRoom) {
const roomAtClose = currentRoom;
getSettings().then(settings => {
if (currentRoom !== roomAtClose) return;
emit(EVENTS.PEER_STATUS, {
peerId,
playbackState: 'paused',
currentTime: null,
mediaTitle: null,
username: settings.username,
tabTitle: null
});
if (currentRoom && Array.isArray(currentRoom.peers)) {
const me = currentRoom.peers.find(p => (p.peerId || p) === peerId);
if (me && typeof me === 'object') {
me.playbackState = 'paused';
me.currentTime = null;
me.mediaTitle = null;
me.tabTitle = null;
me.lastHeartbeat = Date.now();
if (storageInitialized) chrome.storage.session.set({ currentRoom });
chrome.runtime.sendMessage({ type: 'PEER_UPDATE', peers: currentRoom.peers }).catch(() => {});
}
}
}).catch(() => {});
}
}
});
+7 -11
View File
@@ -1,4 +1,3 @@
/* global cloneInto */
/**
* KoalaSync Bridge Script
* Injected into sync.koalastuff.net to facilitate communication between
@@ -23,15 +22,12 @@ window.addEventListener('KOALASYNC_JOIN_REQUEST', (e) => {
// 3. Listen for Status Updates from the Extension and relay to Website
chrome.runtime.onMessage.addListener((msg) => {
if (msg.type === 'JOIN_STATUS') {
const detail = { success: msg.success, message: msg.message };
// Firefox MV3 content scripts run in an isolated world. When dispatching
// a CustomEvent with a detail object, Firefox wraps it in an XrayWrapper
// that the page's JavaScript cannot destructure (Permission denied).
// cloneInto() exposes the object to the page's context correctly.
// Chrome doesn't have this issue — cloneInto() is undefined there.
const safeDetail = typeof cloneInto === 'function'
? cloneInto(detail, document.defaultView)
: detail;
window.dispatchEvent(new CustomEvent('KOALASYNC_STATUS', { detail: safeDetail }));
const event = new CustomEvent('KOALASYNC_STATUS', {
detail: {
success: msg.success,
message: msg.message
}
});
window.dispatchEvent(event);
}
});
+43 -172
View File
@@ -29,25 +29,8 @@
};
// --- SHARED_EVENTS_INJECT_END ---
// Suppresses native event reporting after a programmatic action.
// Each entry is a per-type timer (key = 'playing'|'paused'|'seek').
// While a timer exists, matching native events are consumed and not relayed.
// Timers self-clean after 300ms if the native event never fires.
let _suppressTimers = {};
function _setSuppress(state) {
if (_suppressTimers[state]) clearTimeout(_suppressTimers[state]);
_suppressTimers[state] = setTimeout(() => {
delete _suppressTimers[state];
}, 300);
}
function _clearSuppress(state) {
if (_suppressTimers[state]) {
clearTimeout(_suppressTimers[state]);
delete _suppressTimers[state];
}
}
let expectedEvents = new Set();
let expectedTimeouts = {};
// --- Seek Relay Filtering ---
// Minimum seek delta (seconds) to report. Prevents HLS/DASH buffering micro-seeks
@@ -61,17 +44,19 @@
let episodeTransitionDebounce = null;
let _pendingLobbyTitle = null; // Title we're waiting to match (from remote lobby)
let lobbyPollTimer = null;
let _autoSyncEnabled = true; // Cached setting, updated via storage.onChanged
// Cache the autoSyncNextEpisode setting
chrome.storage.sync.get(['autoSyncNextEpisode'], (data) => {
_autoSyncEnabled = data.autoSyncNextEpisode !== false; // default: enabled
});
chrome.storage.onChanged.addListener((changes, area) => {
if (area === 'sync' && changes.autoSyncNextEpisode) {
_autoSyncEnabled = changes.autoSyncNextEpisode.newValue !== false;
function expectEvent(state) {
expectedEvents.add(state);
if (expectedTimeouts[state]) {
clearTimeout(expectedTimeouts[state]);
delete expectedTimeouts[state];
}
});
const timeout = state === 'seek' ? 10000 : 1500;
expectedTimeouts[state] = setTimeout(() => {
expectedEvents.delete(state);
delete expectedTimeouts[state];
}, timeout);
}
function reportLog(message, level = 'info') {
chrome.runtime.sendMessage({ type: 'LOG', message, level }).catch(() => {});
@@ -97,43 +82,6 @@
: null;
}
// Extract a canonical episode identifier from a title string.
// Handles: S01E01, S1E1, S01 - E01, Season 1 Episode 1, "Folge 5", "Episode 5", "Ep. 5", "#5"
// Returns null if no episode pattern found.
function extractEpisodeId(title) {
if (!title || typeof title !== 'string') return null;
// S01E01 patterns (with optional spaces, dashes, dots between S and E)
const se = title.match(/S(?:eason\s*)?(\d+)[\s\-\.]*E(?:pisode\s*)?(\d+)/i);
if (se) return `S${String(se[1]).padStart(2, '0')}E${String(se[2]).padStart(2, '0')}`;
// "Episode X", "Folge X", "Ep. X", "#X"
const ep = title.match(/(?:Episode|Folge|Ep\.?|#)\s*(\d+)/i);
if (ep) return `EP${String(ep[1]).padStart(3, '0')}`;
return null;
}
// Returns true if two titles likely refer to the same episode.
// Strict: both must have IDs and match, OR neither has IDs and exact match.
function sameEpisode(titleA, titleB) {
if (!titleA && !titleB) return true; // Both unknown → assume same (backward compat)
if (!titleA || !titleB) return false; // One unknown, one known → different
const idA = extractEpisodeId(titleA);
const idB = extractEpisodeId(titleB);
if (idA && idB) return idA === idB; // Both have parseable IDs → compare IDs
if (idA || idB) return false; // One has ID, other doesn't → different
return titleA === titleB; // Neither has ID → exact string match
}
// Returns true only when we are CERTAIN the episodes differ.
// Permissive: only blocks if BOTH titles have parseable IDs AND they differ.
// Films, music, unparseable titles always pass through.
function isDifferentEpisode(titleA, titleB) {
if (!titleA || !titleB) return false; // Unknown → allow
const idA = extractEpisodeId(titleA);
const idB = extractEpisodeId(titleB);
if (!idA || !idB) return false; // At least one unparseable → allow
return idA !== idB; // Both parseable → only block if different
}
function checkEpisodeTransition() {
const currentTitle = getMediaTitle();
const video = findVideo();
@@ -141,7 +89,7 @@
// Only trigger if: we had a previous title, the title changed,
// a video exists, and we're near the start of new content.
if (lastKnownMediaTitle && currentTitle
&& !sameEpisode(currentTitle, lastKnownMediaTitle)
&& currentTitle !== lastKnownMediaTitle
&& video
&& video.currentTime < 5
&& video.readyState >= 1) {
@@ -174,11 +122,11 @@
const video = findVideo();
const currentTitle = getMediaTitle();
if (video && currentTitle && sameEpisode(currentTitle, expectedTitle)
if (video && currentTitle && currentTitle === expectedTitle
&& video.currentTime < 5 && video.readyState >= 1) {
// Match! Pause at start and report ready.
if (!video.paused) {
_setSuppress('paused');
expectEvent('paused');
video.pause();
}
stopLobbyPoll();
@@ -245,11 +193,11 @@
if (ytButton) {
const isCurrentlyPlaying = !video.paused;
if ((action === EVENTS.PLAY && !isCurrentlyPlaying) || (action === EVENTS.PAUSE && isCurrentlyPlaying)) {
_setSuppress(action === EVENTS.PLAY ? 'playing' : 'paused');
expectEvent(action === EVENTS.PLAY ? 'playing' : 'paused');
ytButton.click();
}
if (action === EVENTS.SEEK) {
_setSuppress('seek');
expectEvent('seek');
video.currentTime = data.targetTime;
}
return;
@@ -261,11 +209,11 @@
if (twitchButton) {
const isCurrentlyPlaying = !video.paused;
if ((action === EVENTS.PLAY && !isCurrentlyPlaying) || (action === EVENTS.PAUSE && isCurrentlyPlaying)) {
_setSuppress(action === EVENTS.PLAY ? 'playing' : 'paused');
expectEvent(action === EVENTS.PLAY ? 'playing' : 'paused');
twitchButton.click();
}
if (action === EVENTS.SEEK) {
_setSuppress('seek');
expectEvent('seek');
video.currentTime = data.targetTime;
}
return;
@@ -274,16 +222,16 @@
// Fallback for native HTML5
if (action === EVENTS.PLAY) {
_setSuppress('playing');
expectEvent('playing');
video.play().catch((e) => {
reportLog(`Playback prevented: ${e.message}`, 'warn');
_clearSuppress('playing');
expectedEvents.delete('playing');
});
} else if (action === EVENTS.PAUSE) {
_setSuppress('paused');
expectEvent('paused');
video.pause();
} else if (action === EVENTS.SEEK) {
_setSuppress('seek');
expectEvent('seek');
video.currentTime = data.targetTime;
}
} catch (e) {
@@ -329,24 +277,6 @@
if (message.type === 'SERVER_COMMAND') {
const { action, payload } = message;
let actionCompleted = false;
// Guard: Don't execute sync commands if peers are on different episodes.
// Only active when autoSyncNextEpisode setting is enabled (default: on).
// Only blocks when BOTH sides have parseable S01E01-style IDs that differ.
// Films and unparseable titles always pass through.
const syncActions = [EVENTS.PLAY, EVENTS.PAUSE, EVENTS.SEEK,
EVENTS.FORCE_SYNC_PREPARE, EVENTS.FORCE_SYNC_EXECUTE];
if (_autoSyncEnabled && syncActions.includes(action)) {
const senderTitle = payload?.mediaTitle;
const myTitle = getMediaTitle();
if (isDifferentEpisode(senderTitle, myTitle)) {
reportLog(`Episode mismatch: sender="${senderTitle || '?'}" vs mine="${myTitle || '?'}" — skipping ${action}. Disable "Auto-Sync next Episode" in settings if this causes issues.`, 'warn');
if (action !== EVENTS.FORCE_SYNC_PREPARE && action !== EVENTS.FORCE_SYNC_EXECUTE) {
chrome.runtime.sendMessage({ type: 'CMD_ACK', actionTimestamp: message.actionTimestamp, commandSenderId: message.commandSenderId });
}
return;
}
}
if (action === EVENTS.PLAY) {
tryMediaAction(EVENTS.PLAY);
@@ -368,8 +298,8 @@
reportLog(`Media Action Error: Invalid force sync payload - ${JSON.stringify(payload)}`, 'error');
return;
}
_setSuppress('paused');
_setSuppress('seek');
expectEvent('paused');
expectEvent('seek');
video.pause();
video.currentTime = payload.targetTime;
pollSeekReady(payload.targetTime).then((ready) => {
@@ -415,7 +345,7 @@
if (message.type === 'PAUSE_FOR_LOBBY') {
const video = findVideo();
if (video && !video.paused) {
_setSuppress('paused');
expectEvent('paused');
video.pause();
}
// Start lobby poll now that we know the feature is enabled
@@ -469,17 +399,6 @@
// Detect native events
function reportEvent(action) {
if (seekDebounceTimer && (action === EVENTS.PLAY || action === EVENTS.PAUSE)) {
clearTimeout(seekDebounceTimer);
seekDebounceTimer = null;
const v = findVideo();
if (v && Number.isFinite(v.currentTime)) {
lastReportedSeekTime = v.currentTime;
reportLog(`[Seek] Debounce flushed immediately due to ${action.toUpperCase()}`, 'info');
reportEvent(EVENTS.SEEK);
}
}
const video = findVideo();
if (!video) return;
@@ -490,14 +409,14 @@
const eventState = action === EVENTS.PLAY ? 'playing' : (action === EVENTS.PAUSE ? 'paused' : (action === EVENTS.SEEK ? 'seek' : null));
if (_suppressTimers[eventState]) {
_clearSuppress(eventState);
if (eventState && expectedEvents.has(eventState)) {
expectedEvents.delete(eventState);
if (expectedTimeouts[eventState]) {
clearTimeout(expectedTimeouts[eventState]);
delete expectedTimeouts[eventState];
}
return;
}
// Suppress only SEEK during visibility grace period (tab re-focus ghost jump).
// Play/Pause pass through — user may want to immediately pause after tabbing back.
if (Date.now() < visibilityGraceUntil && action === EVENTS.SEEK) return;
chrome.runtime.sendMessage({
type: 'CONTENT_EVENT',
@@ -514,38 +433,6 @@
scheduleProactiveHeartbeat();
}
// --- Tab Visibility Handling ---
// Browsers (especially Firefox) aggressively throttle background tabs.
// When the user returns to a video tab, the video element may have lost
// time-sync and fires spurious seek events as it recovers (jumping back).
// We suppress only SEEK for a short grace period after tab re-focus.
// Play/Pause are NOT suppressed — the user may legitimately want to
// pause immediately after switching back.
let pageVisible = !document.hidden;
let visibilityGraceUntil = 0;
const VISIBILITY_GRACE_MS = 300;
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
pageVisible = false;
} else if (!pageVisible) {
pageVisible = true;
visibilityGraceUntil = Date.now() + VISIBILITY_GRACE_MS;
reportLog(`Tab re-focused — suppressing seeks for ${VISIBILITY_GRACE_MS / 1000}s to prevent ghost relay`, 'warn');
}
});
// Reset on page hide/show (bfcache, tab discard)
window.addEventListener('pagehide', () => { pageVisible = false; });
window.addEventListener('pageshow', (event) => {
// event.persisted is true ONLY when restored from bfcache, not on initial load
if (event.persisted && !pageVisible) {
pageVisible = true;
visibilityGraceUntil = Date.now() + VISIBILITY_GRACE_MS;
reportLog(`Page restored from cache — suppressing seeks for ${VISIBILITY_GRACE_MS / 1000}s`, 'warn');
}
});
const handlePlay = () => reportEvent(EVENTS.PLAY);
const handlePause = () => reportEvent(EVENTS.PAUSE);
@@ -557,26 +444,28 @@
const current = video.currentTime;
if (!Number.isFinite(current)) return;
// Step 1: Check _suppressTimers (programmatic seek from remote peer)
if (_suppressTimers['seek']) {
_clearSuppress('seek');
// Step 1: Check expectedEvents (programmatic seek suppression)
if (expectedEvents.has('seek')) {
expectedEvents.delete('seek');
if (expectedTimeouts['seek']) {
clearTimeout(expectedTimeouts['seek']);
delete expectedTimeouts['seek'];
}
lastReportedSeekTime = current;
// No log — this is routine programmatic behavior (Force Sync, lobby, peer command)
return;
}
// Step 2: Suppress during visibility grace period (tab re-focus ghost events)
if (Date.now() < visibilityGraceUntil) return;
const delta = lastReportedSeekTime !== null ? Math.abs(current - lastReportedSeekTime) : null;
const deltaStr = delta !== null ? `Δ${delta.toFixed(2)}s` : 'Δ?';
// Step 3: Delta check — skip micro-seeks (buffering, chapter markers, etc.)
// Step 2: Delta check — skip micro-seeks (buffering, chapter markers, etc.)
if (lastReportedSeekTime !== null && delta < MIN_SEEK_DELTA) {
reportLog(`[Seek] Filtered (${deltaStr} < ${MIN_SEEK_DELTA}s threshold) @ ${current.toFixed(2)}s — not relayed`, 'warn');
return;
}
// Step 4: Debounce rapid consecutive seeks (e.g. scrubbing)
// Step 3: Debounce rapid consecutive seeks (e.g. scrubbing)
// — wait 800ms for the user to settle before relaying
if (seekDebounceTimer) clearTimeout(seekDebounceTimer);
seekDebounceTimer = setTimeout(() => {
@@ -716,24 +605,6 @@
// Initial Setup
setupListeners();
// Maintain a persistent keep-alive port connection to prevent background SW suspension
let keepAlivePort = null;
function connectKeepAlivePort() {
try {
if (chrome.runtime.id) {
keepAlivePort = chrome.runtime.connect({ name: 'keepAlive' });
keepAlivePort.onDisconnect.addListener(() => {
keepAlivePort = null;
setTimeout(connectKeepAlivePort, 1000);
});
}
} catch (_e) {
// Extension context invalidated or disabled
}
}
connectKeepAlivePort();
schedulePeriodicHeartbeat();
// Immediate heartbeat on injection — populate peer data without waiting 15s
+2 -2
View File
@@ -1,8 +1,8 @@
{
"manifest_version": 3,
"name": "KoalaSync",
"version": "1.9.0",
"description": "Synchronize video playback on YouTube, Netflix, Emby, Jellyfin, and any HTML5 site in real-time with friends.",
"version": "1.8.1",
"description": "Watch party extension to synchronize video playback on YouTube, Twitch, Netflix, and HTML5 sites in real-time with friends.",
"permissions": [
"storage",
"tabs",
+37 -71
View File
@@ -27,20 +27,15 @@
font-size: 14px;
}
.header-row {
display: flex;
align-items: center;
margin-bottom: 16px;
}
h1 {
font-size: 18px;
margin: 0;
margin: 0 0 16px 0;
color: var(--accent);
letter-spacing: 1px;
text-transform: uppercase;
display: inline-flex;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
}
@@ -51,27 +46,6 @@
border-radius: 4px;
}
.popup-version {
margin-left: auto;
display: flex;
align-items: center;
gap: 4px;
font-size: 10px;
color: var(--text-muted);
text-decoration: none;
opacity: 0.5;
transition: opacity 0.2s, color 0.2s;
}
.popup-version:hover {
opacity: 1;
color: var(--accent);
}
.popup-version svg {
width: 12px;
height: 12px;
display: block;
}
/* Tabs */
.tabs {
display: flex;
@@ -314,19 +288,11 @@
</head>
<body>
<div id="toast-container"></div>
<div class="header-row">
<h1><img src="icons/icon128.png" alt="KoalaSync Logo">KoalaSync</h1>
<a href="https://github.com/Shik3i/KoalaSync" target="_blank" class="popup-version">
<svg viewBox="0 0 16 16" fill="currentColor">
<path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"/>
</svg>
<span id="popupVersion">v0.0.0</span>
</a>
</div>
<h1><img src="icons/icon128.png" alt="KoalaSync Logo">KoalaSync</h1>
<div class="tabs">
<button class="tab-btn active" data-tab="tab-room" title="Room settings and connection">Room</button>
<button class="tab-btn" data-tab="tab-sync" title="Video sync controls and remote actions">Sync</button>
<button class="tab-btn" data-tab="tab-sync">Sync</button>
<button class="tab-btn" data-tab="tab-settings" title="Extension preferences">Settings</button>
<button class="tab-btn" data-tab="tab-dev" title="Advanced Diagnostics & Logs">Status</button>
</div>
@@ -341,27 +307,27 @@
<summary style="font-size: 11px; font-weight: 700; color: var(--text-muted); text-transform: uppercase; cursor: pointer; outline: none;">Manual Connect / Advanced</summary>
<div style="margin-top: 12px;">
<div class="form-group">
<label title="Select which KoalaSync server to use">Server</label>
<label>Server</label>
<div style="display:flex; gap:4px; margin-bottom:8px;">
<button id="serverOfficial" class="tab-btn active" style="flex:1; padding:6px; font-size:11px;" title="Use the official reliable server">Official</button>
<button id="serverCustom" class="tab-btn" style="flex:1; padding:6px; font-size:11px;" title="Connect to your own self-hosted server">Custom</button>
<button id="serverOfficial" class="tab-btn active" style="flex:1; padding:6px; font-size:11px;">Official</button>
<button id="serverCustom" class="tab-btn" style="flex:1; padding:6px; font-size:11px;">Custom</button>
</div>
<input type="text" id="serverUrl" placeholder="wss://your-server:3000" style="display:none;">
</div>
<div class="form-group">
<label title="The unique identifier for your sync room">Room ID</label>
<input type="text" id="roomId" placeholder="Enter Room ID" title="The unique ID of the room you want to join">
<label>Room ID</label>
<input type="text" id="roomId" placeholder="Leave empty to create">
</div>
<div class="form-group">
<label title="Optional password to restrict room access">Password (Optional)</label>
<input type="password" id="password" placeholder="Room Password (optional)" title="Password for the room (leave empty if none)">
<label>Password (Optional)</label>
<input type="password" id="password" placeholder="Room password">
</div>
<div id="roomError" style="display:none; color:var(--error); font-size:11px; margin-bottom:8px; text-align:center;"></div>
<button id="joinBtn" class="primary" title="Connect to the room">Join Room</button>
<div style="display: flex; justify-content: space-between; align-items: center; margin-top: 1.5rem; margin-bottom: 8px;">
<label style="margin:0;" title="List of publicly available rooms on this server">Public Rooms</label>
<button id="refreshRooms" class="secondary" style="background:transparent; border:none; color:var(--accent); font-size:10px; cursor:pointer;" title="Refresh the list of public rooms">REFRESH</button>
<label style="margin:0;">Public Rooms</label>
<button id="refreshRooms" style="background:transparent; border:none; color:var(--accent); font-size:10px; cursor:pointer;">REFRESH</button>
</div>
<div id="publicRooms" class="info-card" style="max-height: 120px; overflow-y: auto; padding: 4px;">
<div style="text-align:center; color: var(--text-muted); font-size: 11px; padding: 10px;">Refreshing...</div>
@@ -374,14 +340,14 @@
<div id="section-active" style="display:none;">
<div class="info-card" style="margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; border-left: 4px solid var(--accent);">
<div>
<label style="margin-bottom: 0;" title="The room you are currently connected to">Active Room</label>
<label style="margin-bottom: 0;">Active Room</label>
<div id="activeRoomId" style="font-weight: 700; color: var(--accent); font-size: 16px; letter-spacing: 1px;">NONE</div>
</div>
<div id="activeServer" style="font-size: 10px; color: var(--text-muted); text-align: right; max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">Official Server</div>
</div>
<div class="info-card" style="margin-bottom: 20px;">
<label title="Share this link with friends so they can join">Invite Link</label>
<label>Invite Link</label>
<div class="invite-box">
<input type="text" id="inviteLink" readonly>
<button id="copyInvite" class="secondary">📋</button>
@@ -389,7 +355,7 @@
</div>
<div style="margin-bottom: 20px;">
<label title="Other users currently connected to this room">Peers in Room</label>
<label>Peers in Room</label>
<div id="peerList" class="info-card">
<div style="text-align:center; color: var(--text-muted); font-size: 12px;">No peers connected</div>
</div>
@@ -404,7 +370,7 @@
<!-- SYNC ACTIVE: Visible when in a room -->
<div id="sync-active">
<div class="form-group">
<label title="Choose the browser tab containing the video to sync">Select Video</label>
<label>Select Video</label>
<select id="targetTab">
<option value="">-- Select a Tab --</option>
</select>
@@ -412,7 +378,7 @@
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">
<label style="margin: 0;">Remote Control</label>
<button id="syncTabCopyInvite" title="Copy Invite Link" style="background:transparent; border: 1px solid #334155; border-radius: 6px; padding: 4px 8px; font-size: 11px; cursor:pointer; opacity:0.8; transition: opacity 0.2s; color: var(--text-muted); display: flex; align-items: center; gap: 4px; white-space: nowrap;">📋 Invite Link</button>
<button id="syncTabCopyInvite" title="Copy Invite Link" style="background:transparent; border:none; padding:4px; font-size:14px; cursor:pointer; opacity:0.8; transition: opacity 0.2s;">🔗</button>
</div>
<div style="display: flex; gap: 8px; margin-bottom: 12px;">
<button id="playBtn" class="primary" style="flex:1; background: var(--success);" title="Send a Play command to everyone">▶ Play</button>
@@ -428,7 +394,7 @@
</div>
<!-- NEW: Last Action Status Card -->
<label title="Shows the most recent play, pause, or seek command">Last Activity Status</label>
<label>Last Activity Status</label>
<div id="lastActionCard" class="info-card" style="margin-bottom: 15px; max-height: 120px; overflow-y: auto;">
<div style="text-align:center; color: var(--text-muted); font-size: 10px;">No recent commands</div>
</div>
@@ -451,19 +417,19 @@
<div style="font-size: 32px; margin-bottom: 12px;">🔒</div>
<h3 style="margin: 0 0 8px 0; color: var(--accent); font-size: 15px;">Connect to a room first</h3>
<p style="color: var(--text-muted); font-size: 12px; margin-bottom: 20px;">You need to join a room via an invite link or create a new one to sync videos.</p>
<button id="syncTabCreateRoomBtn" class="primary" style="padding: 12px; font-size: 14px; background: linear-gradient(135deg, #6366f1, #a855f7); box-shadow: 0 4px 12px rgba(99, 102, 241, 0.4);" title="Create a new random room and join it">Create New Room</button>
<button id="syncTabCreateRoomBtn" class="primary" style="padding: 12px; font-size: 14px; background: linear-gradient(135deg, #6366f1, #a855f7); box-shadow: 0 4px 12px rgba(99, 102, 241, 0.4);">Create New Room</button>
</div>
</div>
<!-- Settings Tab -->
<div id="tab-settings" class="tab-content">
<div class="form-group" style="display: flex; align-items: center; justify-content: space-between; background: var(--card); padding: 10px; border-radius: 8px; margin-bottom: 12px; border: 1px solid #334155;">
<label style="margin-bottom: 0;" title="Username helps others identify you.">Your Username</label>
<label style="margin-bottom: 0;" title="Username helps others identify you.">Your Username </label>
<input type="text" id="username" placeholder="Anonymous Koala" maxlength="20" style="width: 150px;">
</div>
<div class="form-group" style="display: flex; align-items: center; justify-content: space-between; background: var(--card); padding: 10px; border-radius: 8px; margin-bottom: 12px; border: 1px solid #334155;">
<label style="margin-bottom: 0; cursor: help;" title="Filters out non-video tabs and unrelated domains to keep the list clean">Hide Clutter Tabs</label>
<label style="margin-bottom: 0; cursor: help;" title="Hides non-video sites like search engines or social media." title="Filters out non-video tabs and unrelated domains to keep the list clean">Hide Clutter Tabs</label>
<label class="toggle-switch">
<input type="checkbox" id="filterNoise" checked>
<span class="slider"></span>
@@ -471,7 +437,7 @@
</div>
<div class="form-group" style="display: flex; align-items: center; justify-content: space-between; background: var(--card); padding: 10px; border-radius: 8px; margin-bottom: 12px; border: 1px solid #334155;">
<label style="margin-bottom: 0; cursor: help;" title="Pauses automatically and waits for all peers when an episode changes, then sync-starts together.">Auto-Sync Next Episode</label>
<label style="margin-bottom: 0; cursor: help;" title="Pauses automatically and waits for all peers when an episode changes, then sync-starts together." title="Automatically clicks 'Next Episode' on supported sites like Netflix when others do">Auto-Sync Next Episode</label>
<label class="toggle-switch">
<input type="checkbox" id="autoSyncNextEpisode">
<span class="slider"></span>
@@ -479,7 +445,7 @@
</div>
<div class="form-group" style="display: flex; align-items: center; justify-content: space-between; background: var(--card); padding: 10px; border-radius: 8px; margin-bottom: 12px; border: 1px solid #334155;">
<label style="margin-bottom: 0; cursor: help;" title="Automatically copies the invite link to your clipboard when creating a new room.">Auto-Copy Invite Link</label>
<label style="margin-bottom: 0; cursor: help;" title="Automatically copies the invite link to your clipboard when creating a new room.">Auto-Copy Invite Link </label>
<label class="toggle-switch">
<input type="checkbox" id="autoCopyInvite" checked>
<span class="slider"></span>
@@ -487,7 +453,7 @@
</div>
<div class="form-group" style="display: flex; align-items: center; justify-content: space-between; background: var(--card); padding: 10px; border-radius: 8px; margin-bottom: 12px; border: 1px solid #334155;">
<label style="margin-bottom: 0; cursor: help;" title="Shows native system notifications when someone joins/leaves or plays/pauses.">Browser Notifications</label>
<label style="margin-bottom: 0; cursor: help;" title="Shows native system notifications when someone joins/leaves or plays/pauses." title="Shows native system notifications when someone joins/leaves or plays/pauses.">Browser Notifications</label>
<label class="toggle-switch">
<input type="checkbox" id="browserNotifications">
<span class="slider"></span>
@@ -497,37 +463,37 @@
<div style="margin-top: 15px; padding: 8px; border-top: 1px solid var(--card);">
<label title="Tools for fixing connection issues">Troubleshooting</label>
<button id="regenId" class="secondary" style="width: 100%; font-size: 11px;" title="Regenerate your internal ID and reconnect">Regenerate Peer ID</button>
<label>Troubleshooting</label>
<button id="regenId" class="secondary" style="width: 100%; font-size: 11px;">Regenerate Peer ID</button>
<p style="font-size: 9px; color: var(--text-muted); margin-top: 5px; text-align: center;">Use this if you see "Duplicate Identity" errors.</p>
</div>
</div>
<!-- Dev Tab -->
<div id="tab-dev" class="tab-content">
<label title="Current WebSocket connection state">Connection Status</label>
<label>Connection Status</label>
<div id="connStatus" class="info-card" style="display:flex; align-items:center; gap: 10px;">
<span id="connDot" class="status-dot status-offline"></span>
<span id="connText" style="flex:1;">Disconnected</span>
<button id="retryBtn" class="secondary" style="display:none; width: auto; padding: 4px 8px; font-size: 10px; margin: 0;" title="Attempt to reconnect to the server">RETRY</button>
<button id="copyLogs" class="btn secondary" style="width: auto; padding: 4px 10px; font-size: 11px;" title="Copy logs to clipboard for sharing">Copy Logs</button>
<button id="retryBtn" class="secondary" style="display:none; width: auto; padding: 4px 8px; font-size: 10px; margin: 0;">RETRY</button>
<button id="copyLogs" class="btn secondary" style="width: auto; padding: 4px 10px; font-size: 11px;">Copy Logs</button>
</div>
<label title="Technical details about the currently selected video element">Video Debug Info</label>
<label>Video Debug Info</label>
<div id="videoDebug" class="info-card" style="font-size: 10px; font-family: monospace; color: var(--text-muted); max-height: 250px; overflow-y: auto; line-height: 1.4;">
No tab selected or video detected.
</div>
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 8px;">
<label title="Chronological log of all sync commands in the room">Full Action History</label>
<label>Full Action History</label>
</div>
<div id="historyList" class="info-card" style="max-height: 120px; overflow-y: auto; font-size: 10px; margin-bottom: 15px;">
<div style="text-align:center; color: var(--text-muted); font-size: 11px;">No activity yet</div>
</div>
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 8px;">
<label title="Technical connection logs for debugging">Logs (Last 50)</label>
<button id="clearLogs" style="background:transparent; border:none; color:var(--accent); font-size:10px; cursor:pointer;" title="Clear log output">CLEAR</button>
<label>Logs (Last 50)</label>
<button id="clearLogs" style="background:transparent; border:none; color:var(--accent); font-size:10px; cursor:pointer;">CLEAR</button>
</div>
<div id="logList"></div>
@@ -546,8 +512,8 @@
<h2 id="onboarding-title" style="color:var(--accent); margin:0 0 8px; font-size:16px;">Welcome to KoalaSync!</h2>
<p id="onboarding-text" style="color:var(--text-muted); font-size:13px; margin:0 0 16px; line-height:1.4;">Let's get you started.</p>
<div style="display:flex; gap:8px; justify-content:center;">
<button id="onboarding-skip" class="secondary" style="width:auto; padding:8px 16px;" title="Skip the tutorial">Skip</button>
<button id="onboarding-next" class="primary" style="width:auto; padding:8px 16px;" title="Go to next step">Next</button>
<button id="onboarding-skip" class="secondary" style="width:auto; padding:8px 16px;">Skip</button>
<button id="onboarding-next" class="primary" style="width:auto; padding:8px 16px;">Next</button>
</div>
<div id="onboarding-dots" style="margin-top:12px; display:flex; gap:6px; justify-content:center;"></div>
</div>
+41 -65
View File
@@ -1,6 +1,5 @@
import { EVENTS, OFFICIAL_LANDING_PAGE_URL } from './shared/constants.js';
import { BLACKLIST_DOMAINS } from './shared/blacklist.js';
import { getAvatarForName, generateUsername } from './shared/names.js';
const elements = {
@@ -48,8 +47,7 @@ const elements = {
lobbyTitle: document.getElementById('lobbyTitle'),
lobbyPeerStatus: document.getElementById('lobbyPeerStatus'),
browserNotifications: document.getElementById('browserNotifications'),
autoCopyInvite: document.getElementById('autoCopyInvite'),
syncTabCopyInvite: document.getElementById('syncTabCopyInvite')
autoCopyInvite: document.getElementById('autoCopyInvite')
};
let localPeerId = null;
@@ -64,6 +62,24 @@ let errorToken = 0;
let forceSyncDone = false;
// --- Helpers ---
function getAvatarForName(username) {
if (!username) return '👤';
const lower = username.toLowerCase();
const map = {
'koala': '🐨', 'panda': '🐼', 'tiger': '🐯', 'eagle': '🦅',
'fox': '🦊', 'bear': '🐻', 'wolf': '🐺', 'lion': '🦁',
'hawk': '🦅', 'seal': '🦭', 'owl': '🦉', 'shark': '🦈',
'dragon': '🐉', 'phoenix': '🐦', 'falcon': '🦅', 'panther': '🐆',
'raven': '🐦‍⬛', 'cobra': '🐍', 'lynx': '🐈', 'jaguar': '🐆',
'orca': '🐋', 'mantis': '🦗', 'viper': '🐍', 'condor': '🦅',
'badger': '🦡', 'otter': '🦦', 'rhino': '🦏', 'crane': '🦩',
'mongoose': '🦦', 'specter': '👻'
};
for (const [key, emoji] of Object.entries(map)) {
if (lower.includes(key)) return emoji;
}
return '👤';
}
// --- Initialization ---
async function init() {
@@ -71,7 +87,9 @@ async function init() {
const data = await chrome.storage.sync.get(['serverUrl', 'useCustomServer', 'roomId', 'password', 'filterNoise', 'username', 'autoSyncNextEpisode', 'forceSyncMode', 'browserNotifications', 'autoCopyInvite']);
let username = data.username;
if (!username) {
username = generateUsername();
const adjs = ['Happy', 'Cool', 'Fast', 'Smart', 'Brave', 'Calm', 'Sneaky', 'Lazy', 'Wild', 'Chill', 'Lucky', 'Epic', 'Swift', 'Bold', 'Mighty', 'Cosmic', 'Neon', 'Shadow', 'Crystal', 'Thunder', 'Silent', 'Golden', 'Fierce', 'Noble', 'Mystic', 'Frozen', 'Blazing', 'Sapphire', 'Iron', 'Crimson'];
const nouns = ['Koala', 'Panda', 'Tiger', 'Eagle', 'Fox', 'Bear', 'Wolf', 'Lion', 'Hawk', 'Seal', 'Owl', 'Shark', 'Dragon', 'Phoenix', 'Falcon', 'Panther', 'Raven', 'Cobra', 'Lynx', 'Jaguar', 'Orca', 'Mantis', 'Viper', 'Condor', 'Badger', 'Otter', 'Rhino', 'Crane', 'Mongoose', 'Specter'];
username = `${adjs[Math.floor(Math.random() * adjs.length)]}${nouns[Math.floor(Math.random() * nouns.length)]}`;
chrome.storage.sync.set({ username });
}
@@ -86,11 +104,10 @@ async function init() {
if (elements.autoCopyInvite) elements.autoCopyInvite.checked = data.autoCopyInvite !== false;
// Set Version Info
const versionTxt = `v${chrome.runtime.getManifest().version}`;
const versionEl = document.getElementById('appVersion');
if (versionEl) versionEl.textContent = versionTxt;
const popupVerEl = document.getElementById('popupVersion');
if (popupVerEl) popupVerEl.textContent = versionTxt;
if (versionEl) {
versionEl.textContent = `v${chrome.runtime.getManifest().version}`;
}
if (data.useCustomServer) {
setServerMode(true);
@@ -315,9 +332,7 @@ function startInterpolation() {
const peer = activePeers.find(p => p.peerId === peerId);
if (peer && peer.playbackState === 'playing' && peer.currentTime != null && peer.lastHeartbeat) {
const elapsed = (Date.now() - peer.lastHeartbeat) / 1000;
if (elapsed < 45) {
el.textContent = formatTime(peer.currentTime + elapsed);
}
el.textContent = formatTime(peer.currentTime + elapsed);
}
});
}, 1000);
@@ -460,9 +475,7 @@ function updatePeerList(peers) {
let displayTime = p.currentTime;
if (p.playbackState === 'playing' && p.lastHeartbeat && p.currentTime != null) {
const elapsed = (Date.now() - p.lastHeartbeat) / 1000;
if (elapsed < 45) {
displayTime += elapsed;
}
displayTime += elapsed;
}
timeSpan.textContent = formatTime(displayTime);
statusLine.appendChild(timeSpan);
@@ -563,9 +576,7 @@ async function populateTabs(providedPeers = null, providedTargetTabId = null) {
const hostname = new URL(tab.url).hostname.toLowerCase();
if (domain.endsWith('.')) return hostname.startsWith(domain) || hostname.includes('.' + domain);
if (domain.includes('.')) return hostname === domain || hostname.endsWith('.' + domain);
} catch {
/* ignore invalid URLs */
}
} catch {}
return urlStr.includes(domain);
})) return false;
}
@@ -573,32 +584,23 @@ async function populateTabs(providedPeers = null, providedTargetTabId = null) {
});
// Smart Matching Logic — exclude own tabTitle to prevent self-match (computed once)
const cleanTitle = (rawTitle) => {
if (!rawTitle) return '';
return rawTitle
.replace(/(?:\s*[-\|•]\s*(?:YouTube|Twitch|Jellyfin|Emby|Netflix|Vimeo|Dailymotion).*)$/i, '')
.replace(/^(?:Netflix|Twitch|YouTube|Emby|Jellyfin)\s*[-\|•]\s*/i, '')
.trim();
};
const peerTitles = peerIds
.filter(p => (typeof p === 'object' ? p.peerId : p) !== localPeerId)
.map(p => (typeof p === 'object' ? p.tabTitle : null))
.filter(t => t && t.length > 3)
.map(t => cleanTitle(t).toLowerCase())
.filter(t => t.length > 3);
.filter(t => t && t.length > 3);
filteredTabs.forEach(tab => {
const option = document.createElement('option');
option.value = tab.id;
const rawTitle = (tab.title || 'Loading...');
const title = cleanTitle(rawTitle).toLowerCase();
const title = (tab.title || 'Loading...');
const isMatch = title.length > 3 && peerTitles.some(pt => {
return title.includes(pt) || pt.includes(title);
const isMatch = peerTitles.some(pt => {
const t1 = title.toLowerCase();
const t2 = pt.toLowerCase();
return t1.includes(t2) || t2.includes(t1);
});
let label = rawTitle.substring(0, 45) + (rawTitle.length > 45 ? '...' : '');
let label = title.substring(0, 45) + (title.length > 45 ? '...' : '');
if (isMatch) {
label = `⭐ MATCH: ${label}`;
option.style.fontWeight = 'bold';
@@ -606,7 +608,7 @@ async function populateTabs(providedPeers = null, providedTargetTabId = null) {
}
if (tab.audible) {
label = `[🎬] ${label}`;
label = `[🔊] ${label}`;
}
option.textContent = label;
@@ -643,7 +645,7 @@ async function populateTabs(providedPeers = null, providedTargetTabId = null) {
const matchOpt = options.find(o => o.textContent.includes('⭐ MATCH:'));
if (matchOpt && elements.targetTab.options.length > 1) {
elements.targetTab.value = matchOpt.value;
const tabTitle = matchOpt.dataset.originalTitle || null;
const tabTitle = matchOpt.text.replace('⭐ MATCH: ', '') || null;
chrome.runtime.sendMessage({ type: 'SET_TARGET_TAB', tabId: parseInt(matchOpt.value), tabTitle });
}
}
@@ -1003,7 +1005,7 @@ function handleCreateRoom() {
// Auto-connect
elements.joinBtn.click();
}
};
elements.createRoomBtn.addEventListener('click', handleCreateRoom);
const syncTabCreateRoomBtn = document.getElementById('syncTabCreateRoomBtn');
@@ -1065,15 +1067,13 @@ elements.forceSyncBtn.addEventListener('click', async () => {
elements.forceSyncBtn.disabled = true;
elements.forceSyncBtn.textContent = mode === 'jump-to-others' ? `Syncing to group (${formatTime(targetTime)})...` : 'Syncing...';
forceSyncDone = false;
const peerCount = (status.peers || []).filter(p => (typeof p === 'object' ? p.peerId : p) !== localPeerId).length;
const syncTimeoutMs = peerCount === 0 ? 3000 : 12000;
const forceSyncReset = () => {
if (!forceSyncDone) {
elements.forceSyncBtn.disabled = false;
elements.forceSyncBtn.textContent = originalText;
}
};
forceSyncResetTimer = setTimeout(forceSyncReset, syncTimeoutMs);
forceSyncResetTimer = setTimeout(forceSyncReset, 12000);
const tabId = parseInt(status.targetTabId);
const sendForceSync = (time) => {
@@ -1119,25 +1119,13 @@ elements.playBtn.addEventListener('click', () => {
showToast('Please select a video first!', 'warning');
return;
}
elements.playBtn.textContent = 'Playing...';
elements.playBtn.textContent = 'Playing...';
elements.playBtn.disabled = true;
chrome.runtime.sendMessage({
type: 'CONTENT_EVENT',
action: EVENTS.PLAY,
payload: {}
}, (response) => {
if (response && response.status === 'ok_solo') {
elements.playBtn.textContent = '▶ Play';
elements.playBtn.disabled = false;
}
});
// Safety reset: restore button after 2.5s in case no peers respond
setTimeout(() => {
if (elements.playBtn.disabled) {
elements.playBtn.textContent = '▶ Play';
elements.playBtn.disabled = false;
}
}, 2500);
});
elements.pauseBtn.addEventListener('click', () => {
@@ -1145,25 +1133,13 @@ elements.pauseBtn.addEventListener('click', () => {
showToast('Please select a video first!', 'warning');
return;
}
elements.pauseBtn.textContent = 'Pausing...';
elements.pauseBtn.textContent = 'Pausing...';
elements.pauseBtn.disabled = true;
chrome.runtime.sendMessage({
type: 'CONTENT_EVENT',
action: EVENTS.PAUSE,
payload: {}
}, (response) => {
if (response && response.status === 'ok_solo') {
elements.pauseBtn.textContent = '⏸ Pause';
elements.pauseBtn.disabled = false;
}
});
// Safety reset: restore button after 2.5s in case no peers respond
setTimeout(() => {
if (elements.pauseBtn.disabled) {
elements.pauseBtn.textContent = '⏸ Pause';
elements.pauseBtn.disabled = false;
}
}, 2500);
});
elements.clearLogs.addEventListener('click', () => {
+61
View File
@@ -0,0 +1,61 @@
const fs = require('fs');
let html = fs.readFileSync('extension/popup.html', 'utf8');
// Tooltips for inputs
html = html.replace('<input type="text" id="username" placeholder="Leave empty for random name">', '<input type="text" id="username" placeholder="Leave empty for random name" title="Your display name in the room">');
html = html.replace('<input type="text" id="roomId" placeholder="Enter Room ID">', '<input type="text" id="roomId" placeholder="Enter Room ID" title="The unique ID of the room you want to join">');
html = html.replace('<input type="password" id="password" placeholder="Room Password (optional)">', '<input type="password" id="password" placeholder="Room Password (optional)" title="Password for the room (leave empty if none)">');
// Tooltips for buttons
html = html.replace('<button id="joinBtn" class="primary">Join Room</button>', '<button id="joinBtn" class="primary" title="Connect to the room">Join Room</button>');
html = html.replace('<button id="leaveBtn" class="primary" style="display:none; background: var(--error);">Leave Room</button>', '<button id="leaveBtn" class="primary" style="display:none; background: var(--error);" title="Disconnect from the room">Leave Room</button>');
html = html.replace('<button id="createRoomBtn" class="primary">Create New Room</button>', '<button id="createRoomBtn" class="primary" title="Create a new random room and join it">Create New Room</button>');
html = html.replace('<button id="refreshRooms" class="secondary">↻ Refresh List</button>', '<button id="refreshRooms" class="secondary" title="Refresh the list of public rooms">↻ Refresh List</button>');
html = html.replace('<button id="playBtn" class="primary" style="flex:1; background: var(--success);">▶ Play</button>', '<button id="playBtn" class="primary" style="flex:1; background: var(--success);" title="Send a Play command to everyone">▶ Play</button>');
html = html.replace('<button id="pauseBtn" class="primary" style="flex:1; background: var(--error);">⏸ Pause</button>', '<button id="pauseBtn" class="primary" style="flex:1; background: var(--error);" title="Send a Pause command to everyone">⏸ Pause</button>');
html = html.replace('<button id="forceSyncBtn" class="primary" style="background: linear-gradient(135deg, #6366f1, #a855f7); flex: 1;">⚡ SYNC</button>', '<button id="forceSyncBtn" class="primary" style="background: linear-gradient(135deg, #6366f1, #a855f7); flex: 1;" title="Force all users to sync up">⚡ SYNC</button>');
html = html.replace('<button id="copyInvite" class="secondary" style="margin-top: 0; white-space: nowrap;">Copy Invite</button>', '<button id="copyInvite" class="secondary" style="margin-top: 0; white-space: nowrap;" title="Copy the room invite link to clipboard">Copy Invite</button>');
// Tooltips for tabs
html = html.replace('<button class="tab-btn active" data-tab="tab-room">Room</button>', '<button class="tab-btn active" data-tab="tab-room" title="Room settings and connection">Room</button>');
html = html.replace('<button class="tab-btn" data-tab="tab-sync" id="tabSyncBtn" style="display:none;">Sync</button>', '<button class="tab-btn" data-tab="tab-sync" id="tabSyncBtn" style="display:none;" title="Remote control and video selection">Sync</button>');
html = html.replace('<button class="tab-btn" data-tab="tab-settings">Settings</button>', '<button class="tab-btn" data-tab="tab-settings" title="Extension preferences">Settings</button>');
html = html.replace('<button class="tab-btn" data-tab="tab-dev">Status</button>', '<button class="tab-btn" data-tab="tab-dev" title="Connection status and debug logs">Status</button>');
// Remove explicit ️ where not needed since it's hidden now
html = html.replace('>Hide Clutter Tabs ️<', ' title="Filters out non-video tabs and unrelated domains to keep the list clean">Hide Clutter Tabs<');
html = html.replace('>Auto-Sync Next Episode ️<', ' title="Automatically clicks \'Next Episode\' on supported sites like Netflix when others do">Auto-Sync Next Episode<');
html = html.replace('>Auto-copy invite on Create ️<', ' title="Automatically copies the invite link to your clipboard when you create a new room">Auto-copy invite on Create<');
html = html.replace('>Browser Notifications ️<', ' title="Shows native system notifications when someone joins/leaves or plays/pauses.">Browser Notifications<');
// Fix onboarding layout
html = html.replace('align-items:center; justify-content:center;">', 'align-items:flex-end; justify-content:center; padding-bottom: 20px;">');
html = html.replace('margin-top: 50px;', '');
fs.writeFileSync('extension/popup.html', html, 'utf8');
let js = fs.readFileSync('extension/popup.js', 'utf8');
const newAvatarFn = `function getAvatarForName(username) {
if (!username) return '👤';
const lower = username.toLowerCase();
const map = {
'koala': '🐨', 'panda': '🐼', 'tiger': '🐯', 'eagle': '🦅',
'fox': '🦊', 'bear': '🐻', 'wolf': '🐺', 'lion': '🦁',
'hawk': '🦅', 'seal': '🦭', 'owl': '🦉', 'shark': '🦈',
'dragon': '🐉', 'phoenix': '🐦', 'falcon': '🦅', 'panther': '🐆',
'raven': '🐦‍⬛', 'cobra': '🐍', 'lynx': '🐈', 'jaguar': '🐆',
'orca': '🐋', 'mantis': '🦗', 'viper': '🐍', 'condor': '🦅',
'badger': '🦡', 'otter': '🦦', 'rhino': '🦏', 'crane': '🦩',
'mongoose': '🦦', 'specter': '👻'
};
for (const [key, emoji] of Object.entries(map)) {
if (lower.includes(key)) return emoji;
}
return '👤';
}`;
js = js.replace(/function getAvatarForName\(username\) \{[\s\S]*?return '👤';\n\}/, newAvatarFn);
fs.writeFileSync('extension/popup.js', js, 'utf8');
console.log("Fixed UI");
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "koalasync",
"version": "1.8.5",
"version": "1.8.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "koalasync",
"version": "1.8.5",
"version": "1.8.2",
"devDependencies": {
"archiver": "^7.0.1",
"eslint": "^10.4.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "koalasync",
"version": "1.9.0",
"version": "1.8.2",
"description": "KoalaSync Build Scripts",
"private": true,
"scripts": {
+2 -2
View File
@@ -22,7 +22,7 @@ if (!fs.existsSync(extSharedDir)) {
fs.mkdirSync(extSharedDir, { recursive: true });
}
const sharedFiles = ['constants.js', 'blacklist.js', 'names.js', 'README.md'];
const sharedFiles = ['constants.js', 'blacklist.js', 'README.md'];
for (const file of sharedFiles) {
const src = path.join(masterSharedDir, file);
const dest = path.join(extSharedDir, file);
@@ -31,7 +31,7 @@ for (const file of sharedFiles) {
}
fs.copyFileSync(src, dest);
}
console.log('✓ constants.js, blacklist.js, names.js, and README.md synced to extension/shared/');
console.log('✓ constants.js, blacklist.js, and README.md synced to extension/shared/');
// Read the base manifest
const baseManifest = JSON.parse(fs.readFileSync(baseManifestPath, 'utf8'));
+3 -41
View File
@@ -44,10 +44,9 @@ const httpServer = createServer(app);
const io = new Server(httpServer, {
cors: {
origin: (origin, callback) => {
if (!origin || origin === 'https://sync.koalastuff.net' || origin.startsWith('chrome-extension://') || origin.startsWith('moz-extension://')) {
if (!origin || origin === 'https://sync.koalastuff.net' || origin.startsWith('chrome-extension://')) {
callback(null, true);
} else {
log('CORS', `Rejected origin: ${origin}`);
callback(new Error('Not allowed by CORS'));
}
},
@@ -196,18 +195,7 @@ function removePeerFromRoom(socketId, roomId, reason) {
// 3. Notify remaining peers (use io.to so the removed socket itself
// doesn't receive it — it has already left or is disconnecting)
const isPeerStillConnected = Array.from(room.peerData.values()).some(data => data.peerId === peerId);
if (!isPeerStillConnected) {
io.to(roomId).emit(EVENTS.PEER_STATUS, { peerId, status: 'left' });
}
// 3.5. Clean up active lobby if a peer leaves
if (room.activeLobby) {
room.activeLobby.readyPeers = room.activeLobby.readyPeers.filter(id => id !== peerId);
if (room.activeLobby.readyPeers.length <= 1 || room.activeLobby.initiatorPeerId === peerId) {
room.activeLobby = null; // Dissolve lobby
}
}
io.to(roomId).emit(EVENTS.PEER_STATUS, { peerId, status: 'left' });
// 4. Delete empty room
if (room.peers.size === 0) {
@@ -308,7 +296,6 @@ io.on('connection', (socket) => {
const ip = socket._clientIp || socket.handshake.address;
if (!checkAuthRate(ip, roomId)) {
log('AUTH', `Auth rate limit blocked ${ip} from room ${roomId.substring(0, 3)}***`);
socket.emit(EVENTS.ERROR, { message: "Too many failed attempts. Try again later." });
return;
}
@@ -330,7 +317,6 @@ io.on('connection', (socket) => {
roomCreationLocks.set(roomId, lockPromise);
try {
if (rooms.size >= MAX_ROOMS) {
log('ROOM', `Server at capacity: ${rooms.size}/${MAX_ROOMS} rooms — rejecting join`);
socket.emit(EVENTS.ERROR, { message: "Server capacity reached" });
return;
}
@@ -353,22 +339,15 @@ io.on('connection', (socket) => {
}
}
if (!room) {
socket.emit(EVENTS.ERROR, { message: "Join error" });
return;
}
if (!createdByMe) {
if (room.passwordHash) {
if (!password || !(await bcrypt.compare(password, room.passwordHash))) {
recordAuthFailure(ip, roomId);
log('AUTH', `Invalid password from ${ip} for room ${roomId.substring(0, 3)}***`);
socket.emit(EVENTS.ERROR, { message: "Invalid password" });
return;
}
}
if (room.peers.size >= MAX_PEERS_PER_ROOM) {
log('ROOM', `Room full (${room.peers.size}/${MAX_PEERS_PER_ROOM}): ${roomId.substring(0, 3)}***`);
socket.emit(EVENTS.ERROR, { message: "Room full" });
return;
}
@@ -412,8 +391,7 @@ io.on('connection', (socket) => {
socket.to(roomId).emit(EVENTS.PEER_STATUS, { peerId, username: username || null, tabTitle: tabTitle || null, mediaTitle: mediaTitle || null, status: 'joined' });
socket.emit(EVENTS.ROOM_DATA, {
roomId,
peers: Array.from(room.peers).map(sid => room.peerData.get(sid)),
activeLobby: room.activeLobby || null
peers: Array.from(room.peers).map(sid => room.peerData.get(sid))
});
log('ROOM', `Peer ${peerId} joined: ${roomId.substring(0, 3)}***`);
} catch (err) {
@@ -471,7 +449,6 @@ io.on('connection', (socket) => {
// --- S-3: Construct clean relay payload — never forward raw client data ---
const relayPayload = {
senderId: mapping.peerId,
seq: clampNum(data.seq, 0, Number.MAX_SAFE_INTEGER),
currentTime: clampNum(data.currentTime, 0, 86400),
targetTime: clampNum(data.targetTime, 0, 86400),
playbackState: validState(data.playbackState),
@@ -489,21 +466,6 @@ io.on('connection', (socket) => {
// Strip undefined keys for clean wire format
Object.keys(relayPayload).forEach(k => relayPayload[k] === undefined && delete relayPayload[k]);
socket.to(mapping.roomId).emit(eventName, relayPayload);
// --- Side-effects: Server-side Episode Lobby Tracking ---
if (eventName === EVENTS.EPISODE_LOBBY && relayPayload.expectedTitle) {
room.activeLobby = {
expectedTitle: relayPayload.expectedTitle,
initiatorPeerId: mapping.peerId,
readyPeers: [mapping.peerId]
};
} else if (eventName === EVENTS.EPISODE_READY && room.activeLobby) {
if (!room.activeLobby.readyPeers.includes(mapping.peerId)) {
room.activeLobby.readyPeers.push(mapping.peerId);
}
} else if ((eventName === EVENTS.FORCE_SYNC_PREPARE || eventName === EVENTS.FORCE_SYNC_EXECUTE) && room.activeLobby) {
room.activeLobby = null;
}
}
}
} catch (err) {
+1 -1
View File
@@ -7,7 +7,7 @@
*/
export const PROTOCOL_VERSION = "1.0.0";
export const APP_VERSION = "1.9.0";
export const APP_VERSION = "1.3.1";
export const OFFICIAL_SERVER_URL = 'wss://syncserver.koalastuff.net';
export const OFFICIAL_LANDING_PAGE_URL = 'https://sync.koalastuff.net';
-281
View File
@@ -1,281 +0,0 @@
/**
* KoalaSync Shared Name Generation & Emoji Mapping
*
* ⚠️ WARNING: This is the SINGLE SOURCE OF TRUTH.
* If you edit this file, you MUST run: node scripts/build-extension.js
* to propagate changes to the extension.
*
* The emoji map covers every animal/creature that has a Unicode emoji.
* Entries are sorted by key length (longest first) at lookup time to
* prevent substring false-matches (e.g. "caterpillar" must be checked
* before "cat").
*
* If you add a new animal noun to USERNAME_NOUNS, ensure it has a
* corresponding entry in ANIMAL_EMOJI_MAP (or a substring that already
* maps to a suitable emoji).
*/
export const USERNAME_ADJECTIVES = [
'Happy', 'Cool', 'Fast', 'Smart', 'Brave', 'Calm', 'Sneaky', 'Lazy',
'Wild', 'Chill', 'Lucky', 'Epic', 'Swift', 'Bold', 'Mighty',
'Cosmic', 'Neon', 'Shadow', 'Crystal', 'Thunder', 'Silent', 'Golden',
'Fierce', 'Noble', 'Mystic', 'Frozen', 'Blazing', 'Sapphire', 'Iron', 'Crimson'
];
export const USERNAME_NOUNS = [
'Koala', 'Panda', 'Tiger', 'Eagle', 'Fox', 'Bear', 'Wolf', 'Lion',
'Hawk', 'Seal', 'Owl', 'Shark', 'Dragon', 'Phoenix', 'Falcon',
'Panther', 'Raven', 'Cobra', 'Lynx', 'Jaguar', 'Orca', 'Mantis',
'Viper', 'Condor', 'Badger', 'Otter', 'Rhino', 'Crane', 'Mongoose',
'Specter',
'Cat', 'Dog', 'Deer', 'Bat', 'Gorilla', 'Monkey', 'Rabbit',
'Horse', 'Unicorn', 'Zebra', 'Leopard', 'Cheetah', 'Puma',
'Ram', 'Goat', 'Bull', 'Donkey', 'Moose',
'Elephant', 'Giraffe', 'Hippo', 'Sloth', 'Kangaroo',
'Raccoon', 'Hamster', 'Hedgehog', 'Skunk', 'Beaver', 'Bison',
'Camel', 'Llama', 'Hyena', 'Coyote',
'Mouse', 'Pig', 'Boar', 'Polar', 'Orangutan', 'Mammoth',
'Crow', 'Duck', 'Swan', 'Penguin', 'Parrot', 'Peacock',
'Dove', 'Dodo', 'Turkey', 'Flamingo', 'Chicken', 'Rooster', 'Goose',
'Dolphin', 'Whale', 'Crab', 'Lobster', 'Octopus', 'Squid',
'Jellyfish', 'Turtle',
'Crocodile', 'Lizard', 'Snake', 'Frog', 'Toad', 'Gecko',
'Bee', 'Ant', 'Spider', 'Scorpion', 'Butterfly', 'Ladybug',
'Beetle', 'Snail', 'Dragonfly', 'Caterpillar',
'Alien', 'Robot', 'Mermaid', 'Ghoul', 'Sprite', 'Cyborg',
'Dinosaur', 'Reaper', 'Wraith', 'Sphinx',
];
export const ANIMAL_EMOJI_MAP = {
'hippopotamus': '🦛',
'rhinoceros': '🦏',
'caterpillar': '🐛',
'chimpanzee': '🐵',
'orangutan': '🦧',
'blackbird': '🐦‍⬛',
'bumblebee': '🐝',
'cockatoo': '🦜',
'cockroach': '🪳',
'dragonfly': '🐉',
'grasshopper': '🦗',
'hedgehog': '🦔',
'jellyfish': '🪼',
'kangaroo': '🦘',
'ladybird': '🐞',
'ladybug': '🐞',
'porcupine': '🦔',
'scorpion': '🦂',
'tarantula': '🕷️',
'alligator': '🐊',
'anaconda': '🐍',
'antelope': '🦌',
'blowfish': '🐡',
'butterfly': '🦋',
'chameleon': '🦎',
'chipmunk': '🐿️',
'crocodile': '🐊',
'dinosaur': '🦖',
'elephant': '🐘',
'flamingo': '🦩',
'giraffe': '🦒',
'hamster': '🐹',
'leopard': '🐆',
'lobster': '🦞',
'mermaid': '🧜‍♀️',
'mongoose': '🦦',
'mosquito': '🦟',
'pangolin': '🦔',
'peacock': '🦚',
'penguin': '🐧',
'phoenix': '🐦‍🔥',
'raccoon': '🦝',
'seahorse': '🐴',
'sealion': '🦭',
'unicorn': '🦄',
'vampire': '🦇',
'warthog': '🐗',
'wolverine': '🦡',
'mammoth': '🦣',
'meerkat': '🦦',
'octopus': '🐙',
'opposum': '🐭',
'ostrich': '🐦',
'panther': '🐆',
'pelican': '🦩',
'rooster': '🐓',
'serpent': '🐍',
'specter': '👻',
'spectre': '👻',
'sparrow': '🐦',
'spider': '🕷️',
'sphinx': '🦁',
'squirrel': '🐿️',
'stingray': '🦈',
'termite': '🐜',
'tortoise': '🐢',
'turkey': '🦃',
'walrus': '🦭',
'wombat': '🦡',
'woodpecker': '🐦',
'alien': '👾',
'badger': '🦡',
'beaver': '🦫',
'beetle': '🪲',
'beluga': '🐋',
'bison': '🦬',
'bobcat': '🐱',
'buffalo': '🦬',
'bunny': '🐰',
'camel': '🐪',
'cheetah': '🐆',
'chicken': '🐔',
'cobra': '🐍',
'condor': '🦅',
'cougar': '🐆',
'coyote': '🐺',
'crane': '🦩',
'cricket': '🦗',
'crow': '🐦‍⬛',
'cyborg': '🤖',
'dolphin': '🐬',
'donkey': '🫏',
'dragon': '🐉',
'drake': '🐉',
'eagle': '🦅',
'falcon': '🦅',
'ferret': '🦦',
'gazelle': '🦌',
'gecko': '🦎',
'gerbil': '🐹',
'ghost': '👻',
'ghoul': '👻',
'goose': '🪿',
'gopher': '🐹',
'gorilla': '🦍',
'grizzly': '🐻',
'heron': '🦩',
'hippo': '🦛',
'hornet': '🐝',
'hyena': '🐺',
'iguana': '🦎',
'jackal': '🐺',
'jaguar': '🐆',
'kitten': '🐱',
'koala': '🐨',
'lemur': '🐒',
'lizard': '🦎',
'llama': '🦙',
'locust': '🦗',
'lynx': '🐱',
'macaw': '🦜',
'mantis': '🦗',
'mink': '🦦',
'monkey': '🐵',
'moose': '🦌',
'mouse': '🐭',
'orca': '🐋',
'otter': '🦦',
'oyster': '🦪',
'panda': '🐼',
'parrot': '🦜',
'pigeon': '🕊️',
'polar': '🐻‍❄️',
'poodle': '🐩',
'puffin': '🐧',
'puma': '🐆',
'rabbit': '🐰',
'raptor': '🦖',
'raven': '🐦‍⬛',
'reaper': '👻',
'rhino': '🦏',
'robin': '🐦',
'robot': '🤖',
'salmon': '🐟',
'shrimp': '🦐',
'skunk': '🦨',
'sloth': '🦥',
'snail': '🐌',
'snake': '🐍',
'sprite': '🧚',
'squid': '🦑',
'swan': '🦢',
'tapir': '🐗',
'tiger': '🐯',
'toad': '🐸',
'trout': '🐟',
'tuna': '🐟',
'turtle': '🐢',
'viper': '🐍',
'vulture': '🦅',
'weasel': '🦦',
'whale': '🐋',
'wolf': '🐺',
'wraith': '👻',
'zebra': '🦓',
'ape': '🦍',
'ant': '🐜',
'bat': '🦇',
'bee': '🐝',
'bug': '🐛',
'cat': '🐱',
'cow': '🐮',
'crab': '🦀',
'dog': '🐶',
'duck': '🦆',
'elk': '🦌',
'fly': '🪰',
'fox': '🦊',
'frog': '🐸',
'goat': '🐐',
'hawk': '🦅',
'hen': '🐔',
'hog': '🐷',
'lion': '🦁',
'mole': '🐭',
'moth': '🦋',
'mule': '🫏',
'owl': '🦉',
'pig': '🐷',
'ram': '🐏',
'rat': '🐀',
'seal': '🦭',
'shark': '🦈',
'wasp': '🐝',
'yak': '🐂',
'doe': '🦌',
'ewe': '🐑',
'buck': '🦌',
'ox': '🐂',
'bull': '🐂',
'dodo': '🦤',
'boar': '🐗',
'bear': '🐻',
'deer': '🦌',
'dove': '🕊️',
'fish': '🐟',
'hare': '🐰',
'horse': '🐴',
'lamb': '🐑',
'mare': '🐴',
'pony': '🐴',
'pup': '🐶',
'croc': '🐊',
'gnat': '🦟',
'gnu': '🦬',
};
export function getAvatarForName(username) {
if (!username) return '\u{1F464}';
const lower = username.toLowerCase();
const sorted = Object.entries(ANIMAL_EMOJI_MAP).sort((a, b) => b[0].length - a[0].length);
for (const [key, emoji] of sorted) {
if (lower.includes(key)) return emoji;
}
return '\u{1F464}';
}
export function generateUsername() {
const adj = USERNAME_ADJECTIVES[Math.floor(Math.random() * USERNAME_ADJECTIVES.length)];
const noun = USERNAME_NOUNS[Math.floor(Math.random() * USERNAME_NOUNS.length)];
return `${adj}${noun}`;
}
+6 -9
View File
@@ -3,18 +3,15 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>KoalaSync | Sync Netflix, Emby, Jellyfin & Any Video with Friends Browser Extension</title>
<meta name="description" content="Watch Netflix, Emby, Jellyfin, YouTube, Twitch and any HTML5 video in perfect sync with friends. KoalaSync is a privacy-first, open-source browser extension for Chrome and Firefox. Works on almost any site with a video element.">
<title>KoalaSync | Real-time Video Synchronization for Friends</title>
<meta name="description" content="Watch YouTube, Twitch, and HTML5 videos in sync with friends. KoalaSync is a privacy-first, open-source browser extension for Chrome and Firefox.">
<link rel="stylesheet" href="style.css">
<link rel="icon" type="image/png" href="assets/logo.png">
<link rel="canonical" href="https://sync.koalastuff.net/">
<meta name="robots" content="index, follow">
<meta property="og:title" content="KoalaSync | Sync Netflix, Emby, Jellyfin & Any Video with Friends">
<meta property="og:description" content="Watch Netflix, Emby, Jellyfin, YouTube, Twitch and any HTML5 video in perfect sync. Privacy-first, open-source browser extension for Chrome & Firefox.">
<meta property="og:title" content="KoalaSync | Sync your videos">
<meta property="og:description" content="Watch together, stay in sync. Privacy-first video synchronization.">
<meta property="og:image" content="https://sync.koalastuff.net/assets/logo.png">
<meta property="og:type" content="website">
<meta property="og:url" content="https://sync.koalastuff.net/">
<script src="lang-init.js"></script>
</head>
@@ -103,7 +100,7 @@
<div class="mock-label"><span lang="en">Invite Link</span><span lang="de">Einladungs-Link</span></div>
<div class="mock-invite-box">
<input type="text" class="mock-input" value="https://sync.koalastuff.net/join.html#join:brave-eagle-80:pass" readonly>
<button class="mock-btn" style="padding: 0.35rem 0.5rem;"><span lang="en">Copy</span><span lang="de">Kopieren</span></button>
<button class="mock-btn" style="padding: 0.35rem 0.5rem;" onclick="navigator.clipboard.writeText('https://sync.koalastuff.net/join.html#join:brave-eagle-80:pass')"><span lang="en">Copy</span><span lang="de">Kopieren</span></button>
</div>
</div>
<div class="mock-card" style="margin-bottom: 12px;">
@@ -457,7 +454,7 @@
<span class="t-key">-</span> <span class="t-str">MAX_PEERS_PER_ROOM=50</span>
<span class="t-key">pids_limit:</span> <span class="t-val">2048</span></code></pre>
<div style="margin-top: 1rem; font-size: 0.75rem; text-align: right; padding-right: 0.5rem;">
<a href="https://github.com/Shik3i/KoalaSync/pkgs/container/koalasync" target="_blank" style="color: var(--accent); text-decoration: none; display: inline-flex; align-items: center; gap: 6px; font-weight: 600; transition: opacity 0.2s; opacity: 0.85;">
<a href="https://github.com/Shik3i/KoalaSync/pkgs/container/koalasync" target="_blank" style="color: var(--accent); text-decoration: none; display: inline-flex; align-items: center; gap: 6px; font-weight: 600; transition: opacity 0.2s; opacity: 0.85;" onmouseover="this.style.opacity='1'" onmouseout="this.style.opacity='0.85'">
📦 <span lang="en">View all image tags on GitHub Packages</span><span lang="de">Alle Image-Tags auf GitHub Packages ansehen</span>
</a>
</div>
-2
View File
@@ -1,6 +1,4 @@
# KoalaSync Website — Allow all crawlers, full indexing
User-agent: *
Allow: /
# Sitemap for search engines
Sitemap: https://sync.koalastuff.net/sitemap.xml
+2 -2
View File
@@ -1,4 +1,4 @@
{
"version": "1.9.0",
"date": "2026-05-28T02:55:04Z"
"version": "1.8.0",
"date": "2026-05-25T21:09:07Z"
}