549 lines
17 KiB
JavaScript
549 lines
17 KiB
JavaScript
// Global error handler
|
|
window.addEventListener('error', (event) => {
|
|
console.error('[Ticky Error]', event.message, 'at', event.filename + ':' + event.lineno);
|
|
});
|
|
|
|
// Authentication Manager
|
|
class AuthManager {
|
|
constructor() {
|
|
this.token = localStorage.getItem('ticky_token');
|
|
this.pin = sessionStorage.getItem('ticky_pin');
|
|
const protocol = window.location.protocol;
|
|
const hostname = window.location.hostname;
|
|
this.apiUrl = `${protocol}//${hostname}:3001`;
|
|
}
|
|
|
|
async login(pin) {
|
|
try {
|
|
const response = await fetch(`${this.apiUrl}/api/login`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ pin })
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error('Invalid PIN');
|
|
}
|
|
|
|
const data = await response.json();
|
|
this.token = data.token;
|
|
this.pin = pin;
|
|
localStorage.setItem('ticky_token', this.token);
|
|
sessionStorage.setItem('ticky_pin', this.pin);
|
|
return true;
|
|
} catch (error) {
|
|
console.error('Login failed:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
logout() {
|
|
this.token = null;
|
|
this.pin = null;
|
|
localStorage.removeItem('ticky_token');
|
|
sessionStorage.removeItem('ticky_pin');
|
|
}
|
|
|
|
isAuthenticated() {
|
|
return !!this.token && !!this.pin;
|
|
}
|
|
|
|
getAuthHeader() {
|
|
return `Bearer ${this.token}`;
|
|
}
|
|
}
|
|
|
|
// Encrypted Video Scroller
|
|
class EncryptedVideoScroller {
|
|
constructor(auth) {
|
|
this.auth = auth;
|
|
this.currentIndex = 0;
|
|
this.videos = [];
|
|
this.isLoading = false;
|
|
this.container = document.getElementById('videoContainer');
|
|
this.loadingEl = document.getElementById('loading');
|
|
this.touchStartY = 0;
|
|
this.touchEndY = 0;
|
|
this.isDragging = false;
|
|
this.decryptedBlobs = {};
|
|
|
|
this.init();
|
|
}
|
|
|
|
async init() {
|
|
this.setupEventListeners();
|
|
await this.loadVideos();
|
|
this.renderVideos();
|
|
}
|
|
|
|
setupEventListeners() {
|
|
// Touch events
|
|
document.addEventListener('touchstart', (e) => this.handleTouchStart(e), { passive: false });
|
|
document.addEventListener('touchmove', (e) => e.preventDefault(), { passive: false });
|
|
document.addEventListener('touchend', (e) => this.handleTouchEnd(e), { passive: false });
|
|
|
|
// Keyboard
|
|
document.addEventListener('keydown', (e) => this.handleKeydown(e));
|
|
|
|
// Mouse wheel
|
|
document.addEventListener('wheel', (e) => this.handleWheel(e), { passive: false });
|
|
|
|
// Toggle header on tap (but not on buttons)
|
|
this.container.addEventListener('click', (e) => {
|
|
if (!e.target.closest('.download-btn') && !e.target.closest('.video-title')) {
|
|
this.toggleHeader();
|
|
}
|
|
});
|
|
}
|
|
|
|
toggleHeader() {
|
|
const header = document.querySelector('.app-header');
|
|
header.classList.toggle('hidden');
|
|
}
|
|
|
|
handleTouchStart(e) {
|
|
this.touchStartY = e.changedTouches[0].clientY;
|
|
this.isDragging = true;
|
|
}
|
|
|
|
handleTouchEnd(e) {
|
|
this.touchEndY = e.changedTouches[0].clientY;
|
|
this.isDragging = false;
|
|
this.handleSwipe();
|
|
}
|
|
|
|
handleSwipe() {
|
|
const diff = this.touchStartY - this.touchEndY;
|
|
const minSwipeDistance = 50;
|
|
|
|
if (Math.abs(diff) < minSwipeDistance) return;
|
|
|
|
if (diff > 0) {
|
|
// Swiped up - next video
|
|
this.nextVideo();
|
|
} else {
|
|
// Swiped down - previous video
|
|
this.prevVideo();
|
|
}
|
|
}
|
|
|
|
handleWheel(e) {
|
|
e.preventDefault();
|
|
|
|
if (e.deltaY > 0) {
|
|
this.nextVideo();
|
|
} else {
|
|
this.prevVideo();
|
|
}
|
|
}
|
|
|
|
handleKeydown(e) {
|
|
if (e.key === 'ArrowDown' || e.key === ' ') {
|
|
e.preventDefault();
|
|
this.nextVideo();
|
|
} else if (e.key === 'ArrowUp') {
|
|
e.preventDefault();
|
|
this.prevVideo();
|
|
}
|
|
}
|
|
|
|
async loadVideos() {
|
|
try {
|
|
this.showLoading();
|
|
const response = await fetch(`${this.auth.apiUrl}/api/encrypted-videos`, {
|
|
headers: {
|
|
'Authorization': this.auth.getAuthHeader()
|
|
}
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error('Failed to load videos');
|
|
}
|
|
|
|
const newVideos = await response.json();
|
|
this.videos = newVideos;
|
|
} catch (error) {
|
|
console.error('Error loading videos:', error);
|
|
this.showLoadingError();
|
|
} finally {
|
|
this.hideLoading();
|
|
}
|
|
}
|
|
|
|
renderVideos() {
|
|
// Keep only current and adjacent videos in DOM for performance
|
|
const startIndex = Math.max(0, this.currentIndex - 1);
|
|
const endIndex = Math.min(this.videos.length, this.currentIndex + 2);
|
|
|
|
// Clear existing videos
|
|
const existingItems = this.container.querySelectorAll('.video-item');
|
|
existingItems.forEach(item => item.remove());
|
|
|
|
// Render videos
|
|
for (let i = startIndex; i < endIndex; i++) {
|
|
if (this.videos[i]) {
|
|
this.renderVideo(this.videos[i], i);
|
|
}
|
|
}
|
|
|
|
this.updateActiveVideo();
|
|
}
|
|
|
|
renderVideo(video, index) {
|
|
const item = document.createElement('div');
|
|
item.className = 'video-item';
|
|
item.dataset.index = index;
|
|
item.style.minHeight = '100vh';
|
|
|
|
const videoEl = document.createElement('video');
|
|
videoEl.preload = 'auto';
|
|
videoEl.controls = false;
|
|
videoEl.loop = true;
|
|
videoEl.autoplay = index === this.currentIndex;
|
|
videoEl.muted = true;
|
|
videoEl.playsInline = true;
|
|
videoEl.setAttribute('webkit-playsinline', 'webkit-playsinline');
|
|
videoEl.setAttribute('x5-playsinline', 'x5-playsinline');
|
|
videoEl.style.width = '100%';
|
|
videoEl.style.height = '100%';
|
|
videoEl.style.objectFit = 'contain';
|
|
|
|
const info = document.createElement('div');
|
|
info.className = 'video-info';
|
|
info.innerHTML = `
|
|
<div>
|
|
<div class="video-title">${this.escapeHtml(video.filename)}</div>
|
|
<div class="video-description">Swipe up for more</div>
|
|
</div>
|
|
`;
|
|
|
|
const downloadBtn = document.createElement('button');
|
|
downloadBtn.className = 'download-btn';
|
|
downloadBtn.title = 'Download video';
|
|
downloadBtn.innerHTML = '⬇';
|
|
downloadBtn.onclick = (e) => {
|
|
e.stopPropagation();
|
|
this.downloadVideo(video);
|
|
};
|
|
info.appendChild(downloadBtn);
|
|
|
|
item.appendChild(videoEl);
|
|
item.appendChild(info);
|
|
|
|
// Load encrypted video on demand
|
|
if (index === this.currentIndex) {
|
|
this.decryptAndPlayVideo(video, videoEl);
|
|
}
|
|
|
|
this.container.appendChild(item);
|
|
}
|
|
|
|
async decryptAndPlayVideo(video, videoEl) {
|
|
try {
|
|
if (this.decryptedBlobs[video.id]) {
|
|
videoEl.src = this.decryptedBlobs[video.id];
|
|
videoEl.play().catch(e => console.log('Play error:', e));
|
|
return;
|
|
}
|
|
|
|
this.showLoading();
|
|
|
|
const response = await fetch(
|
|
`${this.auth.apiUrl}/api/decrypt-video/${video.id}`,
|
|
{
|
|
headers: {
|
|
'Authorization': this.auth.getAuthHeader()
|
|
}
|
|
}
|
|
);
|
|
|
|
if (!response.ok) {
|
|
throw new Error('Failed to decrypt video');
|
|
}
|
|
|
|
const blob = await response.blob();
|
|
const blobUrl = URL.createObjectURL(blob);
|
|
this.decryptedBlobs[video.id] = blobUrl;
|
|
|
|
videoEl.src = blobUrl;
|
|
videoEl.play().catch(e => console.log('Play error:', e));
|
|
} catch (error) {
|
|
console.error('Decryption error:', error);
|
|
this.showLoadingError();
|
|
} finally {
|
|
this.hideLoading();
|
|
}
|
|
}
|
|
|
|
async downloadVideo(video) {
|
|
try {
|
|
// Check if already decrypted
|
|
let blobUrl = this.decryptedBlobs[video.id];
|
|
|
|
if (!blobUrl) {
|
|
// Decrypt the video for download
|
|
const response = await fetch(
|
|
`${this.auth.apiUrl}/api/decrypt-video/${video.id}`,
|
|
{
|
|
headers: {
|
|
'Authorization': this.auth.getAuthHeader()
|
|
}
|
|
}
|
|
);
|
|
|
|
if (!response.ok) {
|
|
throw new Error('Failed to download video');
|
|
}
|
|
|
|
const blob = await response.blob();
|
|
blobUrl = URL.createObjectURL(blob);
|
|
}
|
|
|
|
// Create a temporary download link
|
|
const link = document.createElement('a');
|
|
link.href = blobUrl;
|
|
|
|
// Use original filename or generate one
|
|
const filename = video.filename || `video_${video.id}.mp4`;
|
|
link.download = filename;
|
|
|
|
// Trigger download
|
|
document.body.appendChild(link);
|
|
link.click();
|
|
document.body.removeChild(link);
|
|
|
|
// Clean up the object URL if it wasn't already cached
|
|
if (!this.decryptedBlobs[video.id]) {
|
|
setTimeout(() => URL.revokeObjectURL(blobUrl), 100);
|
|
}
|
|
} catch (error) {
|
|
console.error('Download error:', error);
|
|
alert('Failed to download video: ' + error.message);
|
|
}
|
|
}
|
|
|
|
updateActiveVideo() {
|
|
const items = this.container.querySelectorAll('.video-item');
|
|
items.forEach(item => {
|
|
const index = parseInt(item.dataset.index);
|
|
const video = item.querySelector('video');
|
|
|
|
item.classList.remove('active', 'prev', 'next');
|
|
|
|
if (index === this.currentIndex) {
|
|
item.classList.add('active');
|
|
video.play().catch(e => console.log('Play error:', e));
|
|
} else if (index < this.currentIndex) {
|
|
item.classList.add('prev');
|
|
video.pause();
|
|
} else {
|
|
item.classList.add('next');
|
|
video.pause();
|
|
}
|
|
});
|
|
|
|
// Preload next video
|
|
this.preloadNextVideo();
|
|
}
|
|
|
|
preloadNextVideo() {
|
|
const nextIndex = this.currentIndex + 1;
|
|
if (nextIndex < this.videos.length && nextIndex > this.currentIndex + 1) {
|
|
// Preload video metadata
|
|
const nextVideo = this.videos[nextIndex];
|
|
if (nextVideo) {
|
|
const img = new Image();
|
|
img.src = `${this.apiUrl}${nextVideo.url}`;
|
|
}
|
|
}
|
|
}
|
|
|
|
async nextVideo() {
|
|
if (this.currentIndex < this.videos.length - 1) {
|
|
this.currentIndex++;
|
|
this.renderVideos();
|
|
}
|
|
}
|
|
|
|
prevVideo() {
|
|
if (this.currentIndex > 0) {
|
|
this.currentIndex--;
|
|
this.renderVideos();
|
|
}
|
|
}
|
|
|
|
showLoading() {
|
|
this.isLoading = true;
|
|
this.loadingEl.classList.add('show');
|
|
this.loadingEl.innerHTML = '<div class="spinner"></div>';
|
|
}
|
|
|
|
hideLoading() {
|
|
this.isLoading = false;
|
|
this.loadingEl.classList.remove('show');
|
|
}
|
|
|
|
showLoadingError() {
|
|
this.loadingEl.innerHTML = 'Failed to load';
|
|
this.loadingEl.classList.add('show');
|
|
setTimeout(() => this.loadingEl.classList.remove('show'), 3000);
|
|
}
|
|
|
|
escapeHtml(text) {
|
|
const div = document.createElement('div');
|
|
div.textContent = text;
|
|
return div.innerHTML;
|
|
}
|
|
}
|
|
|
|
// App Controller
|
|
class TickyApp {
|
|
constructor() {
|
|
this.auth = new AuthManager();
|
|
this.scroller = null;
|
|
this.init();
|
|
}
|
|
|
|
async checkFirstLogin() {
|
|
try {
|
|
// Try to access a protected endpoint without auth to see if marker file exists
|
|
const response = await fetch(`${this.auth.apiUrl}/api/health`);
|
|
return !response.ok;
|
|
} catch {
|
|
return true; // Assume first login if we can't check
|
|
}
|
|
}
|
|
|
|
init() {
|
|
if (this.auth.isAuthenticated()) {
|
|
this.showApp();
|
|
} else {
|
|
this.showLogin();
|
|
}
|
|
}
|
|
|
|
showLogin() {
|
|
const loginScreen = document.getElementById('loginScreen');
|
|
const mainApp = document.getElementById('mainApp');
|
|
loginScreen.classList.add('active');
|
|
mainApp.classList.remove('active');
|
|
|
|
const loginForm = document.getElementById('loginForm');
|
|
const pinInput = document.getElementById('pinInput');
|
|
const loginError = document.getElementById('loginError');
|
|
const setupMode = document.getElementById('setupMode');
|
|
|
|
// Check if this is first login by attempting to fetch marker file status
|
|
this.checkFirstLogin().then(isFirstLogin => {
|
|
if (isFirstLogin) {
|
|
setupMode.style.display = 'block';
|
|
pinInput.placeholder = 'Create 6-digit PIN';
|
|
}
|
|
});
|
|
|
|
loginForm.addEventListener('submit', async (e) => {
|
|
e.preventDefault();
|
|
const pin = pinInput.value;
|
|
|
|
if (!pin.match(/^\d{6}$/)) {
|
|
loginError.textContent = 'PIN must be 6 digits';
|
|
loginError.style.display = 'block';
|
|
return;
|
|
}
|
|
|
|
try {
|
|
await this.auth.login(pin);
|
|
this.showApp();
|
|
} catch (error) {
|
|
loginError.textContent = 'Invalid PIN';
|
|
loginError.style.display = 'block';
|
|
pinInput.value = '';
|
|
}
|
|
});
|
|
}
|
|
|
|
showApp() {
|
|
const loginScreen = document.getElementById('loginScreen');
|
|
const mainApp = document.getElementById('mainApp');
|
|
loginScreen.classList.remove('active');
|
|
mainApp.classList.add('active');
|
|
|
|
if (!this.scroller) {
|
|
this.scroller = new EncryptedVideoScroller(this.auth);
|
|
}
|
|
|
|
this.setupAppControls();
|
|
}
|
|
|
|
setupAppControls() {
|
|
const logoutBtn = document.getElementById('logoutBtn');
|
|
const uploadBtn = document.getElementById('uploadBtn');
|
|
const uploadModal = document.getElementById('uploadModal');
|
|
const closeUploadBtn = document.getElementById('closeUploadBtn');
|
|
const uploadForm = document.getElementById('uploadForm');
|
|
const uploadError = document.getElementById('uploadError');
|
|
|
|
logoutBtn.addEventListener('click', () => {
|
|
this.auth.logout();
|
|
window.location.reload();
|
|
});
|
|
|
|
uploadBtn.addEventListener('click', () => {
|
|
uploadModal.classList.add('show');
|
|
});
|
|
|
|
closeUploadBtn.addEventListener('click', () => {
|
|
uploadModal.classList.remove('show');
|
|
});
|
|
|
|
uploadModal.addEventListener('click', (e) => {
|
|
if (e.target === uploadModal) {
|
|
uploadModal.classList.remove('show');
|
|
}
|
|
});
|
|
|
|
uploadForm.addEventListener('submit', async (e) => {
|
|
e.preventDefault();
|
|
const fileInput = document.getElementById('fileInput');
|
|
const file = fileInput.files[0];
|
|
|
|
uploadError.textContent = '';
|
|
uploadError.style.display = 'none';
|
|
|
|
try {
|
|
const formData = new FormData();
|
|
formData.append('file', file);
|
|
|
|
const response = await fetch(`${this.auth.apiUrl}/api/upload`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Authorization': this.auth.getAuthHeader()
|
|
},
|
|
body: formData
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error('Upload failed');
|
|
}
|
|
|
|
uploadForm.reset();
|
|
uploadModal.classList.remove('show');
|
|
|
|
// Reload videos
|
|
await this.scroller.loadVideos();
|
|
this.scroller.renderVideos();
|
|
|
|
alert('Video uploaded and encrypted successfully!');
|
|
} catch (error) {
|
|
uploadError.textContent = 'Upload failed: ' + error.message;
|
|
uploadError.style.display = 'block';
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
// Initialize on page load
|
|
document.addEventListener('DOMContentLoaded', () => {
|
|
new TickyApp();
|
|
});
|