Compare commits

...

10 Commits

13 changed files with 185 additions and 55 deletions
+5
View File
@@ -51,6 +51,11 @@ jobs:
- name: Checkout code
uses: actions/checkout@v4
- name: Sync Protocol Constants
run: |
chmod +x ./scripts/sync-constants.sh
./scripts/sync-constants.sh
- name: Create Extension Zip
run: |
zip -r koala-sync-extension.zip extension/ -x "*.DS_Store*"
+3
View File
@@ -39,3 +39,6 @@ coverage/
# We ignore the synced files in the extension folder to ensure
# the root 'shared/' remains the Single Source of Truth.
extension/shared/
# Temporary scratch files
scratch/
+16 -6
View File
@@ -8,11 +8,17 @@ KoalaSync is a premium, lightweight Chrome Extension and Relay Server for synchr
## Repository Structure
- `extension/`: Chrome Extension (Manifest V3, Vanilla JS).
- `server/`: Node.js + Socket.IO Relay Server (Containerized).
- `website/`: Static marketing landing page & tutorials.
- `shared/`: Shared protocol constants.
- `website/`: Marketing landing page & **Invitation Bridge**.
- `shared/`: Protocol constants and domain blacklist.
- `scripts/`: Development utilities for protocol synchronization.
> [!NOTE]
> For deep technical dives, see [ARCHITECTURE.md](ARCHITECTURE.md) and [SYNC_GUIDE.md](SYNC_GUIDE.md).
## Key Features
- **Global Synchronization**: Synchronize Play, Pause, and Seeking on any website with a `<video>` tag.
- **Smart Matching**: Automatically highlights and sorts tabs containing matching video titles.
- **Noise Filtering**: Built-in domain blacklist to hide non-video sites from selection.
- **Smart Identity**: Customizable usernames combined with unique hexadecimal peer IDs.
- **Dual Heartbeat Architecture**: Robust session tracking that prevents ghost rooms and stale connections.
- **Zero-Latency Relay**: Custom Socket.IO wire protocol implementation for maximum performance.
@@ -31,10 +37,14 @@ docker-compose up -d --build
The server will be available at `ws://localhost:3000`.
### 2. Chrome Extension
1. Open Chrome and go to `chrome://extensions/`.
2. Enable **Developer mode** (top right).
3. Click **Load unpacked**.
4. Select the `extension/` folder.
1. **Synchronize Protocol**: From the root directory, run the sync script to copy the master constants to the extension folder:
```bash
./scripts/sync-constants.sh
```
2. Open Chrome and go to `chrome://extensions/`.
3. Enable **Developer mode** (top right).
4. Click **Load unpacked**.
5. Select the `extension/` folder.
## Usage
1. Open the extension and go to the **Settings** tab to set your **Username**.
+5 -4
View File
@@ -7,10 +7,11 @@ To ensure that the extension and the relay server are always using the exact sam
## When should you run the sync script?
You MUST run the synchronization script in any of the following scenarios:
1. **After modifying** `shared/constants.js`.
2. **After modifying** `shared/blacklist.js`.
3. **Before committing** changes to the repository if any protocol-related files were touched.
4. **Before deploying** the server or releasing the extension.
1. **After a fresh `git clone` or `git pull`** (as the synced files are ignored by git).
2. **After modifying** `shared/constants.js`.
3. **After modifying** `shared/blacklist.js`.
4. **Before committing** changes to the repository if any protocol-related files were touched.
5. **Before deploying** the server or releasing the extension.
## How to sync
+4 -3
View File
@@ -22,9 +22,10 @@ KoalaSync requires `<all_urls>` permission to detect and interact with video ele
- **Zero Telemetry**: No analytics or external tracking scripts.
## Installation
1. Open Chrome and go to `chrome://extensions/`.
2. Enable **Developer mode** (top right).
3. Click **Load unpacked** and select the `extension` folder from this repository.
1. **Sync Protocol**: Run `./scripts/sync-constants.sh` (macOS/Linux) or `scripts\sync-constants.bat` (Windows) from the root.
2. Open Chrome and go to `chrome://extensions/`.
3. Enable **Developer mode** (top right).
4. Click **Load unpacked** and select the `extension` folder.
## Development
If you modify `shared/constants.js`, you must synchronize the changes across the extension and server:
+38 -7
View File
@@ -518,7 +518,12 @@ 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)) {
currentRoom.peers.push({ peerId: data.peerId, username: data.username, tabTitle: data.tabTitle });
currentRoom.peers.push({
peerId: data.peerId,
username: data.username,
tabTitle: data.tabTitle,
mediaTitle: data.mediaTitle || null
});
if (storageInitialized) chrome.storage.session.set({ currentRoom });
chrome.runtime.sendMessage({ type: 'PEER_UPDATE', peers: currentRoom.peers }).catch(() => {});
}
@@ -533,10 +538,16 @@ function handleServerEvent(event, data) {
if (typeof peer === 'object') {
peer.tabTitle = data.tabTitle;
peer.username = data.username;
peer.mediaTitle = data.mediaTitle !== undefined ? data.mediaTitle : peer.mediaTitle;
} else {
// Migration: replace string with object
const idx = currentRoom.peers.indexOf(peer);
currentRoom.peers[idx] = { peerId: data.peerId, username: data.username, tabTitle: data.tabTitle };
currentRoom.peers[idx] = {
peerId: data.peerId,
username: data.username,
tabTitle: data.tabTitle,
mediaTitle: data.mediaTitle || null
};
}
if (storageInitialized) chrome.storage.session.set({ currentRoom });
chrome.runtime.sendMessage({ type: 'PEER_UPDATE', peers: currentRoom.peers }).catch(() => {});
@@ -676,14 +687,15 @@ async function handleAsyncMessage(message, sender, sendResponse) {
protocolVersion: PROTOCOL_VERSION
});
}
} else {
connect();
}
sendResponse({ status: 'ok' });
} else if (message.type === 'RETRY_CONNECT') {
reconnectFailed = false;
reconnectStartTime = null;
reconnectDelay = 1000;
connect();
sendResponse({ status: 'ok' });
} else if (message.type === 'GET_STATUS') {
const isConnected = socket && socket.readyState === WebSocket.OPEN && isNamespaceJoined;
let status = isConnected ? 'connected' : (isConnecting || (socket && socket.readyState === WebSocket.CONNECTING) ? 'connecting' : 'disconnected');
@@ -714,6 +726,7 @@ async function handleAsyncMessage(message, sender, sendResponse) {
});
addLog('Left Room', 'info');
chrome.runtime.sendMessage({ type: 'PEER_UPDATE', peers: [] }).catch(() => {});
sendResponse({ status: 'ok' });
} else if (message.type === 'CLEAR_LOGS') {
logs = [];
sendResponse({ status: 'ok' });
@@ -725,6 +738,7 @@ async function handleAsyncMessage(message, sender, sendResponse) {
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(`42${JSON.stringify([EVENTS.GET_ROOMS])}`);
}
sendResponse({ status: 'ok' });
} else if (message.type === 'WEB_JOIN_REQUEST') {
const { roomId, password, useCustomServer, serverUrl } = message;
chrome.storage.sync.set({
@@ -751,7 +765,6 @@ async function handleAsyncMessage(message, sender, sendResponse) {
}
sendResponse({ status: 'ok' });
});
return true; // Keep channel open for async getSettings
} else if (message.type === 'REGENERATE_ID') {
const newId = self.crypto.randomUUID().substring(0, 8);
chrome.storage.local.set({ peerId: newId }, () => {
@@ -760,7 +773,6 @@ async function handleAsyncMessage(message, sender, sendResponse) {
if (socket) socket.close(); // Force reconnect with new ID
sendResponse({ peerId: newId });
});
return true;
} else if (message.type === 'GET_VIDEO_STATE') {
const { tabId } = message;
if (!tabId) {
@@ -774,7 +786,6 @@ async function handleAsyncMessage(message, sender, sendResponse) {
sendResponse(res);
}
});
return true; // Keep channel open
} else if (message.type === 'CONTENT_EVENT') {
if (sender.tab) {
currentTabId = sender.tab.id;
@@ -815,6 +826,7 @@ async function handleAsyncMessage(message, sender, sendResponse) {
}
addToHistory(message.action, 'You');
emit(message.action, { ...message.payload, peerId });
sendResponse({ status: 'ok' });
} else if (message.type === 'FORCE_SYNC_ACK') {
if (isForceSyncInitiator) {
forceSyncAcks.add(peerId);
@@ -827,6 +839,7 @@ async function handleAsyncMessage(message, sender, sendResponse) {
} else {
emit(EVENTS.FORCE_SYNC_ACK, { peerId });
}
sendResponse({ status: 'ok' });
} else if (message.type === 'CMD_ACK') {
// Content script successfully ran a command. Send ACK back to the initiator.
if (currentCommandSenderId && currentCommandSenderId !== peerId) {
@@ -836,6 +849,7 @@ async function handleAsyncMessage(message, sender, sendResponse) {
actionTimestamp: message.actionTimestamp
});
}
sendResponse({ status: 'ok' });
} else if (message.type === 'HEARTBEAT') {
if (sender.tab) {
currentTabId = sender.tab.id;
@@ -843,10 +857,27 @@ async function handleAsyncMessage(message, sender, sendResponse) {
}
// Peer status heartbeat from content script
getSettings().then(settings => {
emit(EVENTS.PEER_STATUS, { ...message.payload, peerId, username: settings.username, tabTitle: currentTabTitle });
const statusPayload = { ...message.payload, peerId, username: settings.username, tabTitle: currentTabTitle };
emit(EVENTS.PEER_STATUS, statusPayload);
// Locally update our own metadata so the popup sees it for "YOU"
if (currentRoom && currentRoom.peers) {
const me = currentRoom.peers.find(p => (p.peerId || p) === peerId);
if (me && typeof me === 'object') {
me.tabTitle = currentTabTitle;
me.username = settings.username;
me.mediaTitle = message.payload.mediaTitle;
chrome.runtime.sendMessage({ type: 'PEER_UPDATE', peers: currentRoom.peers }).catch(() => {});
}
}
});
sendResponse({ status: 'ok' });
} else if (message.type === 'LOG') {
addLog(`[Content] ${message.message}`, message.level || 'info');
sendResponse({ status: 'ok' });
} else {
// Final fallback to prevent channel hanging
sendResponse({ error: 'unhandled_message' });
}
}
+46 -3
View File
@@ -55,6 +55,15 @@
const video = findVideo();
if (!video) return;
if (action === EVENTS.SEEK) {
const target = data ? (data.targetTime !== undefined ? data.targetTime : data.currentTime) : undefined;
if (!Number.isFinite(target)) {
reportLog(`Media Action Error: Invalid seek payload - ${JSON.stringify(data)}`, 'error');
return;
}
data.targetTime = target;
}
try {
const host = window.location.hostname.toLowerCase();
const isYouTube = host.includes('youtube.com');
@@ -162,6 +171,10 @@
if (!payload || payload.targetTime === undefined) return;
const video = findVideo();
if (video) {
if (!Number.isFinite(payload.targetTime)) {
reportLog(`Media Action Error: Invalid force sync payload - ${JSON.stringify(payload)}`, 'error');
return;
}
setTargetState('paused');
video.pause();
video.currentTime = payload.targetTime;
@@ -178,6 +191,22 @@
if (message.type === 'GET_VIDEO_STATE') {
const video = findVideo();
if (video) {
const dataAttributes = {};
if (video.attributes) {
for (const attr of video.attributes) {
if (attr.name.startsWith('data-')) {
dataAttributes[attr.name] = attr.value;
}
}
}
const metadata = (navigator.mediaSession && navigator.mediaSession.metadata) ? {
title: navigator.mediaSession.metadata.title,
artist: navigator.mediaSession.metadata.artist,
album: navigator.mediaSession.metadata.album,
artwork: Array.from(navigator.mediaSession.metadata.artwork || []).map(a => a.src)
} : null;
sendResponse({
paused: video.paused,
currentTime: video.currentTime,
@@ -186,7 +215,12 @@
muted: video.muted,
playbackRate: video.playbackRate,
url: window.location.href,
id: video.id || 'none'
id: video.id || 'none',
className: video.className || 'none',
src: video.src || 'none',
currentSrc: video.currentSrc || 'none',
dataAttributes,
metadata
});
} else {
sendResponse({ error: 'No video found' });
@@ -199,6 +233,11 @@
const video = findVideo();
if (!video) return;
const current = video.currentTime;
if (!Number.isFinite(current)) return;
const mediaTitle = (navigator.mediaSession && navigator.mediaSession.metadata) ? navigator.mediaSession.metadata.title : null;
const eventState = action === EVENTS.PLAY ? 'playing' : (action === EVENTS.PAUSE ? 'paused' : (action === EVENTS.SEEK ? 'seek' : null));
if (eventState && lastTargetState === eventState) {
@@ -210,7 +249,9 @@
type: 'CONTENT_EVENT',
action,
payload: {
currentTime: video.currentTime,
currentTime: current,
targetTime: current,
mediaTitle: mediaTitle,
timestamp: Date.now()
}
});
@@ -269,11 +310,13 @@
const heartbeatInterval = setInterval(() => {
const video = findVideo();
if (video) {
const mediaTitle = (navigator.mediaSession && navigator.mediaSession.metadata) ? navigator.mediaSession.metadata.title : null;
chrome.runtime.sendMessage({
type: 'HEARTBEAT',
payload: {
playbackState: video.paused ? 'paused' : 'playing',
currentTime: video.currentTime
currentTime: video.currentTime,
mediaTitle: mediaTitle
}
}).catch(err => {
if (err.message.includes('Extension context invalidated')) {
+1 -1
View File
@@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "KoalaSync",
"version": "1.0.0",
"version": "1.1.1",
"description": "Synchronize video playback across different tabs and users.",
"permissions": [
"storage",
+1 -1
View File
@@ -328,7 +328,7 @@
</div>
<label>Video Debug Info</label>
<div id="videoDebug" class="info-card" style="font-size: 10px; font-family: monospace; color: var(--text-muted); min-height: 60px; line-height: 1.4;">
<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>
+59 -25
View File
@@ -94,6 +94,7 @@ async function init() {
function toggleUIState(inRoom) {
if (elements.sectionJoin) elements.sectionJoin.style.display = inRoom ? 'none' : 'block';
if (elements.sectionActive) elements.sectionActive.style.display = inRoom ? 'block' : 'none';
if (elements.peerListSync) elements.peerListSync.style.display = inRoom ? 'block' : 'none';
}
function updateUI(roomId, password, useCustomServer = false, serverUrl = '') {
@@ -241,10 +242,17 @@ function updatePeerList(peers) {
peerItem.appendChild(header);
if (p.mediaTitle) {
const mediaDiv = document.createElement('div');
mediaDiv.style.cssText = 'font-size:11px; color:var(--star); font-weight: 600; margin-top: 2px;';
mediaDiv.textContent = `🎬 ${p.mediaTitle}`;
peerItem.appendChild(mediaDiv);
}
if (pTabTitle) {
const titleDiv = document.createElement('div');
titleDiv.style.cssText = 'font-size:10px; color:var(--text-muted);';
titleDiv.textContent = pTabTitle;
titleDiv.style.cssText = 'font-size:10px; color:var(--text-muted); opacity: 0.8;';
titleDiv.textContent = p.mediaTitle ? `via ${pTabTitle}` : pTabTitle;
peerItem.appendChild(titleDiv);
}
@@ -806,31 +814,57 @@ function refreshDebugInfo() {
if (elements.videoDebug) {
elements.videoDebug.innerHTML = '';
const status = document.createElement('div');
status.style.cssText = 'color:var(--accent); margin-bottom:4px;';
status.textContent = `VIDEO STATE: ${state.paused ? 'PAUSED' : 'PLAYING'}`;
const addField = (label, value, color = null) => {
const row = document.createElement('div');
row.style.marginBottom = '4px';
if (color) row.style.color = color;
const b = document.createElement('b');
b.textContent = `${label}: `;
b.style.color = 'var(--text-muted)';
const span = document.createElement('span');
span.textContent = value;
span.style.wordBreak = 'break-all';
row.appendChild(b);
row.appendChild(span);
elements.videoDebug.appendChild(row);
};
const addSection = (title) => {
const div = document.createElement('div');
div.style.cssText = 'margin: 8px 0 4px 0; border-bottom: 1px solid #334155; padding-bottom: 2px; color: var(--accent); font-weight: bold; font-size: 9px;';
div.textContent = title.toUpperCase();
elements.videoDebug.appendChild(div);
};
addField('STATE', state.paused ? 'PAUSED' : 'PLAYING', 'var(--accent)');
addField('TIME', `${state.currentTime.toFixed(2)}s / ${state.duration.toFixed(2)}s`);
addField('READY', state.readyState);
const time = document.createElement('div');
time.style.fontSize = '11px';
time.textContent = `Time: ${state.currentTime.toFixed(2)}s / ${state.duration.toFixed(2)}s`;
addSection('Identification');
addField('URL', state.url);
addField('ID', state.id);
addField('CLASS', state.className);
const readyState = document.createElement('div');
readyState.style.fontSize = '11px';
readyState.textContent = `ReadyState: ${state.readyState}`;
const misc = document.createElement('div');
misc.style.fontSize = '11px';
misc.textContent = `Muted: ${state.muted} | PlaybackRate: ${state.playbackRate}`;
const url = document.createElement('div');
url.style.cssText = 'font-size:9px; margin-top:4px; opacity:0.7;';
url.textContent = `URL: ${state.url.substring(0, 40)}...`;
elements.videoDebug.appendChild(status);
elements.videoDebug.appendChild(time);
elements.videoDebug.appendChild(readyState);
elements.videoDebug.appendChild(misc);
elements.videoDebug.appendChild(url);
addSection('Media Source');
addField('CURRENT_SRC', state.currentSrc);
addField('SRC', state.src);
if (state.metadata) {
addSection('Media Session API');
addField('TITLE', state.metadata.title || 'n/a');
addField('ARTIST', state.metadata.artist || 'n/a');
addField('ALBUM', state.metadata.album || 'n/a');
}
if (state.dataAttributes && Object.keys(state.dataAttributes).length > 0) {
addSection('Data Attributes');
for (const [key, val] of Object.entries(state.dataAttributes)) {
addField(key.replace('data-', '').toUpperCase(), val);
}
}
}
});
});
BIN
View File
Binary file not shown.
+6 -4
View File
@@ -155,7 +155,7 @@ io.on('connection', (socket) => {
return;
}
if (!payload || typeof payload.roomId !== 'string') return;
const { roomId, password, peerId, username, tabTitle, protocolVersion } = payload;
const { roomId, password, peerId, username, tabTitle, mediaTitle, protocolVersion } = payload;
try {
// Protocol check
if (protocolVersion !== '1.0.0') {
@@ -244,12 +244,13 @@ io.on('connection', (socket) => {
peerId,
username: username || null,
tabTitle: tabTitle || null,
mediaTitle: mediaTitle || null,
lastSeen: Date.now()
});
socketToRoom.set(socket.id, { roomId, peerId });
peerToSocket.set(peerId, socket.id);
socket.to(roomId).emit(EVENTS.PEER_STATUS, { peerId, username: username || null, tabTitle: tabTitle || null, status: 'joined' });
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))
@@ -288,8 +289,9 @@ io.on('connection', (socket) => {
const existing = room.peerData.get(socket.id) || { peerId: mapping.peerId };
room.peerData.set(socket.id, {
...existing,
username: data.username || existing.username,
tabTitle: data.tabTitle || existing.tabTitle,
username: data.username !== undefined ? data.username : existing.username,
tabTitle: data.tabTitle !== undefined ? data.tabTitle : existing.tabTitle,
mediaTitle: data.mediaTitle !== undefined ? data.mediaTitle : existing.mediaTitle,
lastSeen: Date.now()
});
+1 -1
View File
@@ -3,7 +3,7 @@
*/
export const PROTOCOL_VERSION = "1.0.0";
export const APP_VERSION = "1.0.0";
export const APP_VERSION = "1.0.3";
export const OFFICIAL_SERVER_URL = 'wss://sync.shik3i.net';
export const OFFICIAL_LANDING_PAGE_URL = 'https://koalasync.shik3i.net';