Spaces:
Running

ghostchat / index.html
stanx974's picture
Add 2 files
9993b81 verified
Raw History Blame Contribute Delete
34.3 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GhostChat - Anonymous WebRTC Chat with File Sharing</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/peerjs@1.4.7/dist/peerjs.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
.message-container {
scrollbar-width: thin;
scrollbar-color: #4B5563 #1F2937;
}
.message-container::-webkit-scrollbar {
width: 6px;
}
.message-container::-webkit-scrollbar-track {
background: #1F2937;
}
.message-container::-webkit-scrollbar-thumb {
background-color: #4B5563;
border-radius: 3px;
}
.typing-indicator::after {
content: '...';
position: absolute;
animation: typing 1.5s infinite;
}
@keyframes typing {
0% { content: '.'; }
33% { content: '..'; }
66% { content: '...'; }
}
.peer-id-input:focus + .peer-id-label,
.peer-id-input:not(:placeholder-shown) + .peer-id-label {
transform: translateY(-1.5rem) scale(0.85);
color: #9CA3AF;
}
.file-preview {
max-width: 300px;
max-height: 200px;
object-fit: contain;
}
.progress-bar {
height: 4px;
background-color: #4B5563;
border-radius: 2px;
overflow: hidden;
}
.progress-fill {
height: 100%;
background-color: #8B5CF6;
transition: width 0.3s ease;
}
.file-dropzone {
border: 2px dashed #4B5563;
border-radius: 0.375rem;
transition: all 0.2s ease;
}
.file-dropzone.active {
border-color: #8B5CF6;
background-color: rgba(139, 92, 246, 0.1);
}
</style>
</head>
<body class="bg-gray-900 text-gray-100 min-h-screen flex flex-col">
<header class="bg-gray-800 py-4 px-6 shadow-lg">
<div class="container mx-auto flex justify-between items-center">
<div class="flex items-center space-x-2">
<i class="fas fa-ghost text-purple-500 text-2xl"></i>
<h1 class="text-xl font-bold">GhostChat</h1>
</div>
<div id="connection-status" class="flex items-center space-x-2">
<span class="text-sm text-gray-400">Status:</span>
<span id="status-text" class="px-2 py-1 rounded-full text-xs bg-gray-700">Disconnected</span>
</div>
</div>
</header>
<main class="flex-1 container mx-auto p-4 md:p-6 flex flex-col md:flex-row gap-6">
<!-- Connection Panel -->
<div class="w-full md:w-1/3 lg:w-1/4 bg-gray-800 rounded-lg p-4 shadow-lg">
<div class="space-y-6">
<div>
<h2 class="text-lg font-semibold mb-3">Your Ghost ID</h2>
<div class="relative">
<input type="text" id="your-id" readonly
class="w-full bg-gray-700 rounded px-3 py-2 text-sm font-mono cursor-not-allowed"
placeholder="Generating...">
<button id="copy-id" class="absolute right-2 top-2 text-gray-400 hover:text-purple-500">
<i class="far fa-copy"></i>
</button>
</div>
</div>
<div>
<h2 class="text-lg font-semibold mb-3">Connect to Ghost</h2>
<div class="relative">
<input type="text" id="peer-id"
class="peer-id-input w-full bg-gray-700 rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-purple-500"
placeholder=" ">
<label for="peer-id" class="peer-id-label absolute left-3 top-2 text-gray-400 text-sm transition-all duration-200">Enter Ghost ID</label>
<button id="connect-btn" class="w-full mt-4 bg-purple-600 hover:bg-purple-700 text-white py-2 px-4 rounded-md transition-colors">
Connect
</button>
</div>
</div>
<div class="pt-4 border-t border-gray-700">
<h3 class="text-sm font-semibold text-gray-400 mb-2">Quick Tips</h3>
<ul class="text-xs space-y-2 text-gray-300">
<li class="flex items-start space-x-2">
<i class="fas fa-info-circle text-purple-400 mt-0.5"></i>
<span>Share your Ghost ID to start chatting</span>
</li>
<li class="flex items-start space-x-2">
<i class="fas fa-shield-alt text-purple-400 mt-0.5"></i>
<span>All messages and files are end-to-end encrypted</span>
</li>
<li class="flex items-start space-x-2">
<i class="fas fa-user-secret text-purple-400 mt-0.5"></i>
<span>No accounts, no tracking, completely anonymous</span>
</li>
<li class="flex items-start space-x-2">
<i class="fas fa-file-upload text-purple-400 mt-0.5"></i>
<span>Drag & drop files to share them instantly</span>
</li>
</ul>
</div>
</div>
</div>
<!-- Chat Panel -->
<div class="flex-1 flex flex-col bg-gray-800 rounded-lg shadow-lg overflow-hidden">
<div class="p-4 border-b border-gray-700 flex justify-between items-center">
<h2 class="text-lg font-semibold">
<span id="chat-with">Ghost Messages</span>
<span id="typing-indicator" class="typing-indicator text-sm text-gray-400 ml-2 hidden"></span>
</h2>
<button id="disconnect-btn" class="text-sm bg-gray-700 hover:bg-gray-600 px-3 py-1 rounded-md hidden">
Disconnect
</button>
</div>
<div id="message-container" class="message-container flex-1 p-4 overflow-y-auto max-h-[60vh] space-y-3">
<div class="text-center py-10 text-gray-500">
<i class="fas fa-comment-slash text-3xl mb-2"></i>
<p>No active connection. Connect to another Ghost to start chatting.</p>
</div>
</div>
<div class="p-4 border-t border-gray-700 space-y-3">
<!-- File dropzone -->
<div id="file-dropzone" class="file-dropzone p-4 text-center cursor-pointer">
<input type="file" id="file-input" class="hidden" multiple>
<label for="file-input" class="cursor-pointer">
<div class="flex flex-col items-center justify-center space-y-2">
<i class="fas fa-cloud-upload-alt text-2xl text-purple-500"></i>
<p class="text-sm">Drag & drop files here or click to browse</p>
<p class="text-xs text-gray-500">Supports all file types (max 50MB)</p>
</div>
</label>
</div>
<!-- File upload progress -->
<div id="upload-progress" class="hidden">
<div class="flex justify-between text-xs mb-1">
<span>Sending file...</span>
<span id="upload-percentage">0%</span>
</div>
<div class="progress-bar">
<div id="progress-fill" class="progress-fill" style="width: 0%"></div>
</div>
</div>
<!-- Message input -->
<div class="flex space-x-2">
<input type="text" id="message-input"
class="flex-1 bg-gray-700 rounded-l-md px-3 py-2 focus:outline-none focus:ring-1 focus:ring-purple-500"
placeholder="Type a message..." disabled>
<button id="send-btn" class="bg-purple-600 hover:bg-purple-700 text-white px-4 rounded-r-md transition-colors" disabled>
<i class="fas fa-paper-plane"></i>
</button>
</div>
<p class="text-xs text-gray-500">
Press Enter to send. Messages disappear when you disconnect.
</p>
</div>
</div>
</main>
<footer class="bg-gray-800 py-3 px-6 text-center text-sm text-gray-500">
<p>GhostChat - Anonymous peer-to-peer messaging with file sharing. No logs, no tracking.</p>
</footer>
<script>
document.addEventListener('DOMContentLoaded', () => {
// UI Elements
const yourIdInput = document.getElementById('your-id');
const peerIdInput = document.getElementById('peer-id');
const connectBtn = document.getElementById('connect-btn');
const disconnectBtn = document.getElementById('disconnect-btn');
const messageInput = document.getElementById('message-input');
const sendBtn = document.getElementById('send-btn');
const messageContainer = document.getElementById('message-container');
const statusText = document.getElementById('status-text');
const chatWithText = document.getElementById('chat-with');
const typingIndicator = document.getElementById('typing-indicator');
const copyIdBtn = document.getElementById('copy-id');
const fileInput = document.getElementById('file-input');
const fileDropzone = document.getElementById('file-dropzone');
const uploadProgress = document.getElementById('upload-progress');
const progressFill = document.getElementById('progress-fill');
const uploadPercentage = document.getElementById('upload-percentage');
// PeerJS variables
let peer;
let conn;
let dataConnection;
let lastTypingTime = 0;
const TYPING_INTERVAL = 2000; // 2 seconds
const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB
// Initialize Peer
function initializePeer() {
// Generate a random ID for this session
const randomId = 'ghost-' + Math.random().toString(36).substr(2, 9);
peer = new Peer(randomId, {
host: '0.peerjs.com',
port: 443,
path: '/',
secure: true,
debug: 3
});
peer.on('open', (id) => {
yourIdInput.value = id;
updateStatus('Ready to connect', 'bg-blue-600');
});
peer.on('connection', (connection) => {
if (conn && conn.open) {
connection.close();
return;
}
setupConnection(connection);
updateStatus(`Connected to ${connection.peer.substr(0, 8)}...`, 'bg-green-600');
chatWithText.textContent = `Ghost ${connection.peer.substr(0, 8)}...`;
});
// Set up data channel for file transfers
peer.on('call', (call) => {
call.answer(); // Automatically answer
call.on('stream', (stream) => {
// Not used for file transfer, but required by PeerJS
});
call.on('close', () => {
console.log('File transfer connection closed');
});
});
peer.on('error', (err) => {
console.error('Peer error:', err);
updateStatus('Connection error', 'bg-red-600');
});
peer.on('disconnected', () => {
updateStatus('Disconnected', 'bg-yellow-600');
setTimeout(() => initializePeer(), 5000); // Try to reconnect
});
peer.on('close', () => {
updateStatus('Disconnected', 'bg-gray-600');
});
}
// Set up a connection
function setupConnection(connection) {
conn = connection;
conn.on('open', () => {
updateStatus(`Connected to ${conn.peer.substr(0, 8)}...`, 'bg-green-600');
chatWithText.textContent = `Ghost ${conn.peer.substr(0, 8)}...`;
messageInput.disabled = false;
sendBtn.disabled = false;
disconnectBtn.classList.remove('hidden');
// Clear previous messages
messageContainer.innerHTML = '';
// Add welcome message
addMessage('system', 'You are now connected to another Ghost. Messages and files are end-to-end encrypted.', 'text-gray-400');
// Set up data channel for file transfers
setupDataConnection();
});
conn.on('data', (data) => {
if (data.type === 'message') {
addMessage('remote', data.text, 'bg-gray-700');
} else if (data.type === 'typing') {
showTypingIndicator();
} else if (data.type === 'file-meta') {
// Show that a file is being received
addMessage('remote', `Sending you a file: ${data.name} (${formatFileSize(data.size)})`, 'bg-gray-700');
} else if (data.type === 'file-ack') {
// Acknowledge file receipt
addMessage('system', `File transfer completed: ${data.name}`, 'text-gray-400');
}
});
conn.on('close', () => {
handleDisconnection();
});
conn.on('error', (err) => {
console.error('Connection error:', err);
handleDisconnection();
});
}
// Set up data connection for file transfers
function setupDataConnection() {
dataConnection = peer.connect(conn.peer, {
reliable: true,
serialization: 'none',
metadata: { type: 'data-channel' }
});
dataConnection.on('open', () => {
console.log('Data channel ready for file transfers');
});
dataConnection.on('data', (data) => {
if (data instanceof ArrayBuffer || data instanceof Blob) {
// Handle incoming file chunks
handleFileChunk(data);
}
});
dataConnection.on('close', () => {
console.log('Data channel closed');
});
dataConnection.on('error', (err) => {
console.error('Data channel error:', err);
});
}
// Handle incoming file chunks
let receivedFileChunks = [];
let currentFileMeta = null;
function handleFileChunk(chunk) {
if (!currentFileMeta) {
// First chunk should be metadata
try {
const decoder = new TextDecoder();
const metaString = decoder.decode(chunk);
currentFileMeta = JSON.parse(metaString);
receivedFileChunks = [];
return;
} catch (e) {
console.error('Error parsing file metadata:', e);
return;
}
}
// Add chunk to array
receivedFileChunks.push(chunk);
// Update progress
const receivedSize = receivedFileChunks.reduce((acc, chunk) => acc + chunk.byteLength, 0);
const progress = Math.min(100, Math.round((receivedSize / currentFileMeta.size) * 100));
if (progress === 100) {
// File transfer complete
const fileBlob = new Blob(receivedFileChunks, { type: currentFileMeta.type });
displayReceivedFile(fileBlob, currentFileMeta.name, currentFileMeta.size);
// Send acknowledgment
if (conn && conn.open) {
conn.send({
type: 'file-ack',
name: currentFileMeta.name,
size: currentFileMeta.size
});
}
currentFileMeta = null;
receivedFileChunks = [];
}
}
// Display received file in chat
function displayReceivedFile(fileBlob, fileName, fileSize) {
const messageDiv = document.createElement('div');
messageDiv.className = `flex justify-start mb-3`;
const fileUrl = URL.createObjectURL(fileBlob);
const fileExtension = fileName.split('.').pop().toLowerCase();
let fileContent = '';
if (['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(fileExtension)) {
fileContent = `
<div class="bg-gray-700 rounded-lg p-3">
<img src="${fileUrl}" alt="${fileName}" class="file-preview rounded">
<div class="mt-2 text-sm">
<p>${fileName}</p>
<p class="text-xs text-gray-400">${formatFileSize(fileSize)}</p>
<a href="${fileUrl}" download="${fileName}" class="text-purple-400 hover:text-purple-300 text-xs mt-1 inline-block">
<i class="fas fa-download mr-1"></i>Download
</a>
</div>
</div>
`;
} else if (['mp4', 'webm', 'ogg'].includes(fileExtension)) {
fileContent = `
<div class="bg-gray-700 rounded-lg p-3">
<video controls class="file-preview rounded">
<source src="${fileUrl}" type="${fileBlob.type}">
Your browser does not support the video tag.
</video>
<div class="mt-2 text-sm">
<p>${fileName}</p>
<p class="text-xs text-gray-400">${formatFileSize(fileSize)}</p>
<a href="${fileUrl}" download="${fileName}" class="text-purple-400 hover:text-purple-300 text-xs mt-1 inline-block">
<i class="fas fa-download mr-1"></i>Download
</a>
</div>
</div>
`;
} else if (['mp3', 'wav', 'ogg'].includes(fileExtension)) {
fileContent = `
<div class="bg-gray-700 rounded-lg p-3">
<audio controls class="w-full">
<source src="${fileUrl}" type="${fileBlob.type}">
Your browser does not support the audio element.
</audio>
<div class="mt-2 text-sm">
<p>${fileName}</p>
<p class="text-xs text-gray-400">${formatFileSize(fileSize)}</p>
<a href="${fileUrl}" download="${fileName}" class="text-purple-400 hover:text-purple-300 text-xs mt-1 inline-block">
<i class="fas fa-download mr-1"></i>Download
</a>
</div>
</div>
`;
} else {
fileContent = `
<div class="bg-gray-700 rounded-lg p-3">
<div class="flex items-center">
<i class="fas fa-file ${getFileIconClass(fileExtension)} text-2xl mr-3"></i>
<div>
<p class="text-sm">${fileName}</p>
<p class="text-xs text-gray-400">${formatFileSize(fileSize)}</p>
<a href="${fileUrl}" download="${fileName}" class="text-purple-400 hover:text-purple-300 text-xs mt-1 inline-block">
<i class="fas fa-download mr-1"></i>Download
</a>
</div>
</div>
</div>
`;
}
messageDiv.innerHTML = fileContent;
messageContainer.appendChild(messageDiv);
messageContainer.scrollTop = messageContainer.scrollHeight;
}
// Get appropriate icon class for file type
function getFileIconClass(extension) {
const iconMap = {
'pdf': 'text-red-500',
'doc': 'text-blue-500',
'docx': 'text-blue-500',
'xls': 'text-green-500',
'xlsx': 'text-green-500',
'ppt': 'text-orange-500',
'pptx': 'text-orange-500',
'zip': 'text-yellow-500',
'rar': 'text-yellow-500',
'txt': 'text-gray-400',
'csv': 'text-green-400',
'html': 'text-purple-500',
'js': 'text-yellow-300',
'json': 'text-gray-400'
};
return iconMap[extension] || 'text-gray-300';
}
// Handle disconnection
function handleDisconnection() {
updateStatus('Disconnected', 'bg-gray-600');
messageInput.disabled = true;
sendBtn.disabled = true;
disconnectBtn.classList.add('hidden');
if (messageContainer.children.length > 0) {
addMessage('system', 'The other Ghost has disappeared...', 'text-gray-400');
}
}
// Update status UI
function updateStatus(text, bgClass) {
statusText.textContent = text;
statusText.className = `px-2 py-1 rounded-full text-xs ${bgClass}`;
}
// Add a message to the UI
function addMessage(type, text, additionalClasses = '') {
const messageDiv = document.createElement('div');
if (type === 'local') {
messageDiv.className = `flex justify-end`;
messageDiv.innerHTML = `
<div class="max-w-xs md:max-w-md lg:max-w-lg bg-purple-600 rounded-lg px-4 py-2 ${additionalClasses}">
<p>${text}</p>
<p class="text-xs text-purple-200 mt-1 text-right">just now</p>
</div>
`;
} else if (type === 'remote') {
messageDiv.className = `flex justify-start`;
messageDiv.innerHTML = `
<div class="max-w-xs md:max-w-md lg:max-w-lg rounded-lg px-4 py-2 ${additionalClasses}">
<p>${text}</p>
<p class="text-xs text-gray-400 mt-1">ghost</p>
</div>
`;
} else { // system
messageDiv.className = `flex justify-center`;
messageDiv.innerHTML = `
<div class="text-sm ${additionalClasses} px-4 py-2 text-center">
<p>${text}</p>
</div>
`;
}
messageContainer.appendChild(messageDiv);
messageContainer.scrollTop = messageContainer.scrollHeight;
}
// Show typing indicator
function showTypingIndicator() {
typingIndicator.classList.remove('hidden');
setTimeout(() => {
typingIndicator.classList.add('hidden');
}, TYPING_INTERVAL);
}
// Format file size
function formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
// Send file to peer
async function sendFile(file) {
if (!conn || !conn.open || !dataConnection || !dataConnection.open) {
alert('Not connected to another Ghost');
return;
}
if (file.size > MAX_FILE_SIZE) {
alert(`File too large. Maximum size is ${formatFileSize(MAX_FILE_SIZE)}`);
return;
}
// Show sending message
addMessage('local', `Sending file: ${file.name} (${formatFileSize(file.size)})`, 'bg-purple-600');
// Notify peer about incoming file
conn.send({
type: 'file-meta',
name: file.name,
size: file.size,
type: file.type
});
// Show progress bar
uploadProgress.classList.remove('hidden');
progressFill.style.width = '0%';
uploadPercentage.textContent = '0%';
// Read file as array buffer
const reader = new FileReader();
reader.onload = async (event) => {
const arrayBuffer = event.target.result;
// First send metadata
const meta = {
name: file.name,
size: file.size,
type: file.type
};
const metaString = JSON.stringify(meta);
const encoder = new TextEncoder();
const metaData = encoder.encode(metaString);
dataConnection.send(metaData);
// Then send file in chunks
const CHUNK_SIZE = 16 * 1024; // 16KB chunks
const totalChunks = Math.ceil(arrayBuffer.byteLength / CHUNK_SIZE);
for (let i = 0; i < totalChunks; i++) {
const start = i * CHUNK_SIZE;
const end = Math.min(start + CHUNK_SIZE, arrayBuffer.byteLength);
const chunk = arrayBuffer.slice(start, end);
dataConnection.send(chunk);
// Update progress
const progress = Math.round(((i + 1) / totalChunks) * 100);
progressFill.style.width = `${progress}%`;
uploadPercentage.textContent = `${progress}%`;
// Small delay between chunks to prevent overwhelming the connection
await new Promise(resolve => setTimeout(resolve, 10));
}
// Hide progress bar after a short delay
setTimeout(() => {
uploadProgress.classList.add('hidden');
}, 1000);
};
reader.readAsArrayBuffer(file);
}
// Event Listeners
connectBtn.addEventListener('click', () => {
const peerId = peerIdInput.value.trim();
if (!peerId) {
alert('Please enter a Ghost ID to connect');
return;
}
if (conn && conn.open) {
alert('Already connected to a Ghost');
return;
}
const connection = peer.connect(peerId, {
reliable: true,
serialization: 'json'
});
setupConnection(connection);
});
disconnectBtn.addEventListener('click', () => {
if (conn) {
conn.close();
handleDisconnection();
}
});
messageInput.addEventListener('keyup', (e) => {
// Send typing indicator
const now = Date.now();
if (now - lastTypingTime > TYPING_INTERVAL) {
if (conn && conn.open && messageInput.value) {
conn.send({ type: 'typing' });
lastTypingTime = now;
}
}
// Send message on Enter
if (e.key === 'Enter' && messageInput.value.trim()) {
sendMessage();
}
});
sendBtn.addEventListener('click', () => {
if (messageInput.value.trim()) {
sendMessage();
}
});
copyIdBtn.addEventListener('click', () => {
yourIdInput.select();
document.execCommand('copy');
// Show copied tooltip
const originalText = copyIdBtn.innerHTML;
copyIdBtn.innerHTML = '<i class="fas fa-check"></i>';
setTimeout(() => {
copyIdBtn.innerHTML = originalText;
}, 2000);
});
// File input handling
fileInput.addEventListener('change', (e) => {
if (e.target.files.length > 0) {
sendFile(e.target.files[0]);
fileInput.value = ''; // Reset input
}
});
// Drag and drop handling
fileDropzone.addEventListener('dragover', (e) => {
e.preventDefault();
fileDropzone.classList.add('active');
});
fileDropzone.addEventListener('dragleave', (e) => {
e.preventDefault();
fileDropzone.classList.remove('active');
});
fileDropzone.addEventListener('drop', (e) => {
e.preventDefault();
fileDropzone.classList.remove('active');
if (e.dataTransfer.files.length > 0) {
sendFile(e.dataTransfer.files[0]);
}
});
// Click on dropzone to open file dialog
fileDropzone.addEventListener('click', () => {
fileInput.click();
});
// Send message function
function sendMessage() {
const text = messageInput.value.trim();
if (!text || !conn || !conn.open) return;
conn.send({ type: 'message', text });
addMessage('local', text);
messageInput.value = '';
messageInput.focus();
}
// Initialize the app
initializePeer();
});
</script>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=stanx974/ghostchat" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>