added queue system on rooms
This commit is contained in:
@@ -7,7 +7,14 @@ interface RoomUser {
|
||||
avatar?: string;
|
||||
isHost: boolean;
|
||||
isGuest: boolean;
|
||||
userId?: number; // ID real del usuario si está logueado
|
||||
userId?: number;
|
||||
}
|
||||
|
||||
export interface QueueItem {
|
||||
uid: string;
|
||||
metadata: RoomMetadata;
|
||||
videoData: any;
|
||||
addedBy: string;
|
||||
}
|
||||
|
||||
interface RoomMetadata {
|
||||
@@ -36,6 +43,7 @@ interface RoomData {
|
||||
metadata?: RoomMetadata | null;
|
||||
exposed: boolean;
|
||||
publicUrl?: string;
|
||||
queue: QueueItem[];
|
||||
}
|
||||
|
||||
const rooms = new Map<string, RoomData>();
|
||||
@@ -57,7 +65,8 @@ export function createRoom(name: string, host: RoomUser, password?: string, expo
|
||||
password: password || undefined,
|
||||
metadata: null,
|
||||
exposed,
|
||||
publicUrl
|
||||
publicUrl,
|
||||
queue: []
|
||||
};
|
||||
|
||||
rooms.set(roomId, room);
|
||||
@@ -75,6 +84,55 @@ export function getAllRooms(): RoomData[] {
|
||||
}));
|
||||
}
|
||||
|
||||
export function addQueueItem(roomId: string, item: QueueItem): boolean {
|
||||
const room = rooms.get(roomId);
|
||||
if (!room) return false;
|
||||
room.queue.push(item);
|
||||
return true;
|
||||
}
|
||||
|
||||
export function removeQueueItem(roomId: string, itemUid: string): boolean {
|
||||
const room = rooms.get(roomId);
|
||||
if (!room) return false;
|
||||
room.queue = room.queue.filter(i => i.uid !== itemUid);
|
||||
return true;
|
||||
}
|
||||
|
||||
export function getNextQueueItem(roomId: string): QueueItem | undefined {
|
||||
const room = rooms.get(roomId);
|
||||
if (!room || room.queue.length === 0) return undefined;
|
||||
return room.queue.shift(); // Saca el primero y lo retorna
|
||||
}
|
||||
|
||||
export function getAndRemoveQueueItem(roomId: string, itemUid: string): QueueItem | undefined {
|
||||
const room = rooms.get(roomId);
|
||||
if (!room) return undefined;
|
||||
|
||||
const index = room.queue.findIndex(i => i.uid === itemUid);
|
||||
if (index === -1) return undefined;
|
||||
|
||||
const [item] = room.queue.splice(index, 1);
|
||||
return item;
|
||||
}
|
||||
|
||||
export function moveQueueItem(roomId: string, itemUid: string, direction: 'up' | 'down'): boolean {
|
||||
const room = rooms.get(roomId);
|
||||
if (!room) return false;
|
||||
|
||||
const index = room.queue.findIndex(i => i.uid === itemUid);
|
||||
if (index === -1) return false;
|
||||
|
||||
const newIndex = direction === 'up' ? index - 1 : index + 1;
|
||||
|
||||
if (newIndex < 0 || newIndex >= room.queue.length) return false;
|
||||
|
||||
const temp = room.queue[newIndex];
|
||||
room.queue[newIndex] = room.queue[index];
|
||||
room.queue[index] = temp;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export function addUserToRoom(roomId: string, user: RoomUser): boolean {
|
||||
const room = rooms.get(roomId);
|
||||
if (!room) return false;
|
||||
|
||||
@@ -155,7 +155,6 @@ async function handleWebSocketConnection(connection: any, req: any) {
|
||||
isGuest
|
||||
});
|
||||
|
||||
// Enviar estado inicial
|
||||
socket.send(JSON.stringify({
|
||||
type: 'init',
|
||||
userId,
|
||||
@@ -171,7 +170,8 @@ async function handleWebSocketConnection(connection: any, req: any) {
|
||||
isHost: u.isHost,
|
||||
isGuest: u.isGuest
|
||||
})),
|
||||
currentVideo: room.currentVideo
|
||||
currentVideo: room.currentVideo,
|
||||
queue: room.queue || []
|
||||
}
|
||||
}));
|
||||
|
||||
@@ -226,6 +226,46 @@ function handleMessage(roomId: string, userId: string, data: any) {
|
||||
});
|
||||
break;
|
||||
|
||||
case 'queue_play_item':
|
||||
if (room.host.id !== userId) return;
|
||||
|
||||
const itemToPlay = roomService.getAndRemoveQueueItem(roomId, data.itemUid);
|
||||
if (itemToPlay) {
|
||||
const videoPayload = {
|
||||
videoData: itemToPlay.videoData.videoData,
|
||||
subtitles: itemToPlay.videoData.subtitles,
|
||||
currentTime: 0,
|
||||
isPlaying: true
|
||||
};
|
||||
|
||||
roomService.updateRoomVideo(roomId, videoPayload);
|
||||
roomService.updateRoomMetadata(roomId, itemToPlay.metadata);
|
||||
|
||||
broadcastToRoom(roomId, {
|
||||
type: 'video_update',
|
||||
video: videoPayload,
|
||||
metadata: itemToPlay.metadata
|
||||
});
|
||||
|
||||
broadcastToRoom(roomId, {
|
||||
type: 'queue_update',
|
||||
queue: room.queue
|
||||
});
|
||||
}
|
||||
break;
|
||||
|
||||
case 'queue_move':
|
||||
if (room.host.id !== userId) return;
|
||||
|
||||
const moved = roomService.moveQueueItem(roomId, data.itemUid, data.direction);
|
||||
if (moved) {
|
||||
broadcastToRoom(roomId, {
|
||||
type: 'queue_update',
|
||||
queue: room.queue
|
||||
});
|
||||
}
|
||||
break;
|
||||
|
||||
case 'request_sync':
|
||||
// Cualquier usuario puede pedir sync
|
||||
const host = clients.get(room.host.id);
|
||||
@@ -375,6 +415,63 @@ function handleMessage(roomId: string, userId: string, data: any) {
|
||||
}
|
||||
break;
|
||||
|
||||
case 'queue_add':
|
||||
// Solo el host (o todos si quisieras) pueden añadir
|
||||
if (room.host.id !== userId) return;
|
||||
|
||||
const newItem = {
|
||||
uid: `q_${Date.now()}_${Math.random().toString(36).substr(2, 5)}`,
|
||||
metadata: data.metadata,
|
||||
videoData: data.video, // El objeto que contiene url, type, subtitles
|
||||
addedBy: room.users.get(userId)?.username || 'Unknown'
|
||||
};
|
||||
|
||||
roomService.addQueueItem(roomId, newItem);
|
||||
|
||||
// Avisar a todos que la cola cambió
|
||||
broadcastToRoom(roomId, {
|
||||
type: 'queue_update',
|
||||
queue: room.queue
|
||||
});
|
||||
break;
|
||||
|
||||
case 'queue_remove':
|
||||
if (room.host.id !== userId) return;
|
||||
roomService.removeQueueItem(roomId, data.itemUid);
|
||||
broadcastToRoom(roomId, {
|
||||
type: 'queue_update',
|
||||
queue: room.queue
|
||||
});
|
||||
break;
|
||||
|
||||
case 'play_next':
|
||||
if (room.host.id !== userId) return;
|
||||
|
||||
const nextItem = roomService.getNextQueueItem(roomId);
|
||||
if (nextItem) {
|
||||
const videoPayload = {
|
||||
videoData: nextItem.videoData.videoData,
|
||||
subtitles: nextItem.videoData.subtitles,
|
||||
currentTime: 0,
|
||||
isPlaying: true
|
||||
};
|
||||
|
||||
roomService.updateRoomVideo(roomId, videoPayload);
|
||||
roomService.updateRoomMetadata(roomId, nextItem.metadata);
|
||||
|
||||
broadcastToRoom(roomId, {
|
||||
type: 'video_update',
|
||||
video: videoPayload,
|
||||
metadata: nextItem.metadata
|
||||
});
|
||||
|
||||
broadcastToRoom(roomId, {
|
||||
type: 'queue_update',
|
||||
queue: room.queue
|
||||
});
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
console.warn('Unknown message type:', data.type);
|
||||
break;
|
||||
|
||||
@@ -118,13 +118,7 @@ class CreateRoomModal {
|
||||
|
||||
this.close();
|
||||
|
||||
// REDIRECCIÓN:
|
||||
// Si estamos en la página de rooms, recargamos o dejamos que el socket actualice.
|
||||
// Si estamos en otra página, vamos a la sala creada.
|
||||
// Asumo que tu ruta de sala es /room (o query params).
|
||||
// Ajusta esta línea según tu router:
|
||||
window.location.href = `/room?id=${data.room.id}`;
|
||||
|
||||
window.open(`/room?id=${data.room.id}`, '_blank', 'noopener,noreferrer');
|
||||
} catch (err) {
|
||||
alert(err.message);
|
||||
} finally {
|
||||
|
||||
@@ -81,6 +81,14 @@ const RoomsApp = (function() {
|
||||
configError: document.getElementById('config-error'),
|
||||
|
||||
toastContainer: document.getElementById('video-toast-container'),
|
||||
|
||||
tabChatBtn: document.getElementById('tab-chat-btn'),
|
||||
tabQueueBtn: document.getElementById('tab-queue-btn'),
|
||||
tabContentChat: document.getElementById('tab-content-chat'),
|
||||
tabContentQueue: document.getElementById('tab-content-queue'),
|
||||
queueList: document.getElementById('queue-list'),
|
||||
queueCount: document.getElementById('queue-count'),
|
||||
btnAddQueue: document.getElementById('btn-add-queue'),
|
||||
};
|
||||
|
||||
const ui = {
|
||||
@@ -193,6 +201,11 @@ const RoomsApp = (function() {
|
||||
if (elements.roomExtSelect) elements.roomExtSelect.onchange = (e) => onQuickExtensionChange(e, false);
|
||||
if (elements.roomServerSelect) elements.roomServerSelect.onchange = onQuickServerChange;
|
||||
|
||||
elements.tabChatBtn.onclick = () => switchTab('chat');
|
||||
elements.tabQueueBtn.onclick = () => switchTab('queue');
|
||||
|
||||
if(elements.btnAddQueue) elements.btnAddQueue.onclick = () => launchStream(true, true);
|
||||
|
||||
if (elements.roomSdToggle) {
|
||||
elements.roomSdToggle.onclick = () => {
|
||||
if (!isHost) return;
|
||||
@@ -241,6 +254,16 @@ const RoomsApp = (function() {
|
||||
}
|
||||
}
|
||||
|
||||
function switchTab(tab) {
|
||||
elements.tabChatBtn.classList.toggle('active', tab === 'chat');
|
||||
elements.tabQueueBtn.classList.toggle('active', tab === 'queue');
|
||||
elements.tabContentChat.style.display = tab === 'chat' ? 'flex' : 'none';
|
||||
elements.tabContentQueue.style.display = tab === 'queue' ? 'flex' : 'none';
|
||||
|
||||
if(tab === 'queue') elements.chatForm.style.display = 'none';
|
||||
else elements.chatForm.style.display = 'flex';
|
||||
}
|
||||
|
||||
// --- QUICK CONTROLS LOGIC (Header) ---
|
||||
|
||||
async function populateQuickControls() {
|
||||
@@ -376,6 +399,7 @@ const RoomsApp = (function() {
|
||||
|
||||
if(ui.epInput) ui.epInput.value = 1;
|
||||
if(ui.launchBtn) ui.launchBtn.disabled = true;
|
||||
if(elements.btnAddQueue) elements.btnAddQueue.disabled = true;
|
||||
updateSDUI();
|
||||
|
||||
setupConfigListeners();
|
||||
@@ -439,6 +463,7 @@ const RoomsApp = (function() {
|
||||
configState.extension = ext;
|
||||
configState.server = null;
|
||||
ui.launchBtn.disabled = true;
|
||||
if(elements.btnAddQueue) elements.btnAddQueue.disabled = true;
|
||||
|
||||
loadServersForExtension(ext);
|
||||
};
|
||||
@@ -452,6 +477,7 @@ const RoomsApp = (function() {
|
||||
if (!extensionsReady) return;
|
||||
ui.serverContainer.innerHTML = '<div class="grid-loader"><div class="spinner" style="width:20px;height:20px;"></div> Loading servers...</div>';
|
||||
ui.launchBtn.disabled = true;
|
||||
if(elements.btnAddQueue) elements.btnAddQueue.disabled = true;
|
||||
|
||||
try {
|
||||
const settings = extensionsStore.settings[extName];
|
||||
@@ -496,6 +522,7 @@ const RoomsApp = (function() {
|
||||
|
||||
configState.server = srv;
|
||||
ui.launchBtn.disabled = false;
|
||||
if(elements.btnAddQueue) elements.btnAddQueue.disabled = false;
|
||||
};
|
||||
|
||||
ui.serverContainer.appendChild(chip);
|
||||
@@ -543,7 +570,7 @@ const RoomsApp = (function() {
|
||||
|
||||
// --- STREAM LAUNCHER (Unified) ---
|
||||
|
||||
async function launchStream(fromModal = false) {
|
||||
async function launchStream(fromModal = false, isQueueAction = false) {
|
||||
if (!selectedAnimeData) {
|
||||
console.warn("No anime selected data found");
|
||||
return;
|
||||
@@ -556,6 +583,10 @@ const RoomsApp = (function() {
|
||||
server = configState.server;
|
||||
episode = configState.episode;
|
||||
category = configState.category;
|
||||
if(isQueueAction) {
|
||||
elements.btnAddQueue.disabled = true;
|
||||
elements.btnAddQueue.textContent = 'Adding...';
|
||||
}
|
||||
} else {
|
||||
ext = elements.roomExtSelect.value;
|
||||
server = elements.roomServerSelect.value;
|
||||
@@ -585,12 +616,6 @@ const RoomsApp = (function() {
|
||||
return;
|
||||
}
|
||||
|
||||
if(fromModal) {
|
||||
elements.btnLaunch.disabled = true;
|
||||
elements.btnLaunch.innerHTML = '<div class="spinner" style="width:20px;height:20px;"></div> Fetching...';
|
||||
elements.configError.style.display = 'none';
|
||||
}
|
||||
|
||||
try {
|
||||
const apiUrl = `/api/watch/stream?animeId=${selectedAnimeData.id}&episode=${episode}&server=${encodeURIComponent(server)}&category=${category}&ext=${ext}&source=${selectedAnimeData.source}`;
|
||||
console.log('Fetching stream:', apiUrl);
|
||||
@@ -614,28 +639,36 @@ const RoomsApp = (function() {
|
||||
}));
|
||||
|
||||
const videoPayload = {
|
||||
type: 'video_update',
|
||||
video: {
|
||||
videoData: {
|
||||
url: proxyUrl,
|
||||
type: source.type || 'm3u8',
|
||||
headers: headers
|
||||
},
|
||||
subtitles: subtitles,
|
||||
currentTime: 0,
|
||||
isPlaying: true
|
||||
},
|
||||
metadata: {
|
||||
title: selectedAnimeData.title,
|
||||
episode: episode,
|
||||
image: selectedAnimeData.image,
|
||||
id: selectedAnimeData.id
|
||||
}
|
||||
videoData: { url: proxyUrl, type: source.type || 'm3u8', headers: headers },
|
||||
subtitles: subtitles
|
||||
};
|
||||
|
||||
const metaPayload = {
|
||||
title: selectedAnimeData.title,
|
||||
episode: episode,
|
||||
image: selectedAnimeData.image,
|
||||
id: selectedAnimeData.id,
|
||||
source: ext
|
||||
};
|
||||
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify(videoPayload));
|
||||
if (isQueueAction) {
|
||||
ws.send(JSON.stringify({
|
||||
type: 'queue_add',
|
||||
video: videoPayload,
|
||||
metadata: metaPayload
|
||||
}));
|
||||
|
||||
showSystemToast("Added to queue!");
|
||||
if(fromModal) closeAnimeSearchModal();
|
||||
|
||||
} else {
|
||||
ws.send(JSON.stringify({
|
||||
type: 'video_update',
|
||||
video: { ...videoPayload, currentTime: 0, isPlaying: true },
|
||||
metadata: metaPayload
|
||||
}));
|
||||
}
|
||||
loadVideo(videoPayload.video);
|
||||
updateHeaderInfo(videoPayload.metadata);
|
||||
|
||||
@@ -669,9 +702,9 @@ const RoomsApp = (function() {
|
||||
alert(msg);
|
||||
}
|
||||
} finally {
|
||||
if(fromModal) {
|
||||
elements.btnLaunch.disabled = false;
|
||||
elements.btnLaunch.innerHTML = 'Play in Room';
|
||||
if(fromModal && isQueueAction) {
|
||||
elements.btnAddQueue.disabled = false;
|
||||
elements.btnAddQueue.textContent = '+ Add to Queue';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -817,7 +850,7 @@ const RoomsApp = (function() {
|
||||
case 'init':
|
||||
const reconnectToast = document.getElementById('reconnecting-toast');
|
||||
if (reconnectToast) reconnectToast.remove();
|
||||
|
||||
if (data.room.queue) renderQueue(data.room.queue);
|
||||
elements.joinRoomModal.classList.remove('show');
|
||||
currentUserId = data.userId;
|
||||
currentUsername = data.username;
|
||||
@@ -842,6 +875,10 @@ const RoomsApp = (function() {
|
||||
}
|
||||
break;
|
||||
|
||||
case 'queue_update':
|
||||
renderQueue(data.queue);
|
||||
break;
|
||||
|
||||
case 'users_update':
|
||||
renderUsersList(data.users);
|
||||
break;
|
||||
@@ -932,6 +969,77 @@ const RoomsApp = (function() {
|
||||
}
|
||||
}
|
||||
|
||||
function renderQueue(queueItems) {
|
||||
if (!elements.queueList) return;
|
||||
|
||||
elements.queueCount.textContent = queueItems.length;
|
||||
|
||||
if (queueItems.length === 0) {
|
||||
elements.queueList.innerHTML = '<div class="queue-empty">Queue is empty</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
elements.queueList.innerHTML = queueItems.map((item, index) => {
|
||||
let actionsHtml = '';
|
||||
|
||||
if (isHost) {
|
||||
const isFirst = index === 0;
|
||||
const isLast = index === queueItems.length - 1;
|
||||
|
||||
actionsHtml = `
|
||||
<div class="q-actions">
|
||||
<button class="q-btn play" onclick="playQueueItem('${item.uid}')" title="Play Now">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>
|
||||
</button>
|
||||
<div style="display:flex; gap:2px;">
|
||||
${!isFirst ? `
|
||||
<button class="q-btn" onclick="moveQueueItem('${item.uid}', 'up')" title="Move Up">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 15l-6-6-6 6"/></svg>
|
||||
</button>` : ''}
|
||||
${!isLast ? `
|
||||
<button class="q-btn" onclick="moveQueueItem('${item.uid}', 'down')" title="Move Down">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 9l6 6 6-6"/></svg>
|
||||
</button>` : ''}
|
||||
</div>
|
||||
<button class="q-btn remove" onclick="removeQueueItem('${item.uid}')" title="Remove">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
return `
|
||||
<div class="queue-item">
|
||||
<img src="${item.metadata.image || '/public/assets/placeholder.png'}" class="q-img">
|
||||
<div class="q-info">
|
||||
<div class="q-title" title="${escapeHtml(item.metadata.title)}">${escapeHtml(item.metadata.title)}</div>
|
||||
<div class="q-meta">Ep ${item.metadata.episode} • ${escapeHtml(item.addedBy)}</div>
|
||||
</div>
|
||||
${actionsHtml}
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
// Funciones globales (window) para los botones onclick
|
||||
window.playQueueItem = function(uid) {
|
||||
if(ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ type: 'queue_play_item', itemUid: uid }));
|
||||
}
|
||||
};
|
||||
|
||||
window.moveQueueItem = function(uid, direction) {
|
||||
if(ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ type: 'queue_move', itemUid: uid, direction }));
|
||||
}
|
||||
};
|
||||
|
||||
window.removeQueueItem = function(uid) {
|
||||
if(ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ type: 'queue_remove', itemUid: uid }));
|
||||
}
|
||||
};
|
||||
|
||||
function updateRoomUI(room) {
|
||||
elements.roomName.textContent = room.name;
|
||||
elements.roomViewers.textContent = `${room.users.length}`;
|
||||
@@ -1361,6 +1469,16 @@ const RoomsApp = (function() {
|
||||
if(elements.timeDisplay) elements.timeDisplay.textContent = formatTime(video.currentTime) + " / " + formatTime(video.duration);
|
||||
if(elements.progressPlayed) elements.progressPlayed.style.width = (video.currentTime/video.duration*100) + "%";
|
||||
});
|
||||
video.addEventListener('ended', () => {
|
||||
if (isHost) {
|
||||
console.log('Video ended. Checking queue...');
|
||||
setTimeout(() => {
|
||||
if(ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ type: 'play_next' }));
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function formatTime(s) {
|
||||
|
||||
Reference in New Issue
Block a user