| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563 |
- // GrabZilla 2.1 - Application State Management
- // Centralized state management with event system
- class AppState {
- constructor() {
- this.videos = [];
- this.history = []; // Array of completed download history entries
- this.config = {
- savePath: this.getDefaultDownloadsPath(),
- defaultQuality: window.AppConfig?.APP_CONFIG?.DEFAULT_QUALITY || '1080p',
- defaultFormat: window.AppConfig?.APP_CONFIG?.DEFAULT_FORMAT || 'None',
- filenamePattern: window.AppConfig?.APP_CONFIG?.DEFAULT_FILENAME_PATTERN || '%(title)s.%(ext)s',
- cookieFile: null,
- maxHistoryEntries: 100 // Maximum number of history entries to keep
- };
- this.ui = {
- isDownloading: false,
- selectedVideos: [],
- sortBy: 'createdAt',
- sortOrder: 'desc',
- keyboardNavigationActive: false,
- currentFocusIndex: -1
- };
- this.listeners = new Map();
- this.downloadQueue = [];
- this.downloadStats = {
- totalDownloads: 0,
- successfulDownloads: 0,
- failedDownloads: 0,
- totalBytesDownloaded: 0
- };
- }
- // Get default downloads path based on platform
- getDefaultDownloadsPath() {
- const defaultPaths = window.AppConfig?.DEFAULT_PATHS || {
- darwin: '~/Downloads/GrabZilla_Videos',
- win32: 'C:\\Users\\Admin\\Desktop\\GrabZilla_Videos',
- linux: '~/Downloads/GrabZilla_Videos'
- };
- if (window.electronAPI) {
- try {
- const platform = window.electronAPI.getPlatform();
- return defaultPaths[platform] || defaultPaths.linux;
- } catch (error) {
- console.warn('Failed to get platform:', error);
- return defaultPaths.win32;
- }
- }
- return defaultPaths.win32;
- }
- // Video management methods
- addVideo(video) {
- if (!(video instanceof window.Video)) {
- throw new Error('Invalid video object');
- }
- // Check for duplicate URLs
- const existingVideo = this.videos.find(v => v.getNormalizedUrl() === video.getNormalizedUrl());
- if (existingVideo) {
- throw new Error('Video URL already exists in the list');
- }
- this.videos.push(video);
- this.emit('videoAdded', { video });
- return video;
- }
- // Add multiple videos from URLs
- async addVideosFromUrls(urls, options = {}) {
- const { allowDuplicates = false } = options;
- const results = {
- successful: [],
- failed: [],
- duplicates: []
- };
- // Filter out duplicates first (unless allowDuplicates is true)
- const uniqueUrls = [];
- for (const url of urls) {
- if (allowDuplicates) {
- // Skip duplicate check
- uniqueUrls.push(url);
- } else {
- const normalizedUrl = window.URLValidator ? window.URLValidator.normalizeUrl(url) : url;
- const existingVideo = this.videos.find(v => v.getNormalizedUrl() === normalizedUrl);
- if (existingVideo) {
- results.duplicates.push({ url, reason: 'URL already exists' });
- } else {
- uniqueUrls.push(url);
- }
- }
- }
- // Create videos immediately for instant UI feedback (non-blocking)
- for (const url of uniqueUrls) {
- try {
- const video = window.Video.fromUrl(url);
- this.addVideo(video);
- results.successful.push(video);
- } catch (error) {
- results.failed.push({ url, error: error.message });
- }
- }
- // Prefetch metadata in background (non-blocking, parallel for better UX)
- // Videos will update automatically via Video.fromUrl() metadata fetch
- if (uniqueUrls.length > 0 && window.MetadataService) {
- console.log(`[Batch Metadata] Starting background fetch for ${uniqueUrls.length} URLs...`);
- const startTime = performance.now();
- // Don't await - let it run in background
- window.MetadataService.prefetchMetadata(uniqueUrls)
- .then(() => {
- const duration = performance.now() - startTime;
- console.log(`[Batch Metadata] Completed in ${Math.round(duration)}ms (${Math.round(duration / uniqueUrls.length)}ms avg/video)`);
- })
- .catch(error => {
- console.warn('[Batch Metadata] Batch prefetch failed:', error.message);
- });
- }
- this.emit('videosAdded', { results });
- return results;
- }
- // Reorder videos in the array
- reorderVideos(fromIndex, toIndex) {
- if (fromIndex === toIndex) return;
- if (fromIndex < 0 || fromIndex >= this.videos.length ||
- toIndex < 0 || toIndex > this.videos.length) {
- throw new Error('Invalid indices for reordering');
- }
- // Remove from old position
- const [movedVideo] = this.videos.splice(fromIndex, 1);
- // Insert at new position
- const adjustedToIndex = fromIndex < toIndex ? toIndex - 1 : toIndex;
- this.videos.splice(adjustedToIndex, 0, movedVideo);
- this.emit('videosReordered', {
- fromIndex,
- toIndex: adjustedToIndex,
- videoId: movedVideo.id
- });
- console.log(`Reordered video from position ${fromIndex} to ${adjustedToIndex}`);
- }
- // Remove video from state
- removeVideo(videoId) {
- const index = this.videos.findIndex(v => v.id === videoId);
- if (index === -1) {
- throw new Error('Video not found');
- }
- const removedVideo = this.videos.splice(index, 1)[0];
- // Remove from selected videos if present
- this.ui.selectedVideos = this.ui.selectedVideos.filter(id => id !== videoId);
- this.emit('videoRemoved', { video: removedVideo });
- return removedVideo;
- }
- // Remove multiple videos
- removeVideos(videoIds) {
- const removedVideos = [];
- const errors = [];
- for (const videoId of videoIds) {
- try {
- const removed = this.removeVideo(videoId);
- removedVideos.push(removed);
- } catch (error) {
- errors.push({ videoId, error: error.message });
- }
- }
- this.emit('videosRemoved', { removedVideos, errors });
- return { removedVideos, errors };
- }
- // Update video in state
- updateVideo(videoId, properties) {
- const video = this.videos.find(v => v.id === videoId);
- if (!video) {
- throw new Error('Video not found');
- }
- const oldProperties = { ...video };
- video.update(properties);
- this.emit('videoUpdated', { video, oldProperties });
- return video;
- }
- // Get video by ID
- getVideo(videoId) {
- return this.videos.find(v => v.id === videoId);
- }
- // Get all videos
- getVideos() {
- return [...this.videos];
- }
- // Get videos by status
- getVideosByStatus(status) {
- return this.videos.filter(v => v.status === status);
- }
- // Get selected videos
- getSelectedVideos() {
- return this.videos.filter(v => this.ui.selectedVideos.includes(v.id));
- }
- // Clear all videos
- clearVideos() {
- const removedVideos = [...this.videos];
- this.videos = [];
- this.ui.selectedVideos = [];
- this.downloadQueue = [];
- this.emit('videosCleared', { removedVideos });
- return removedVideos;
- }
- // Selection management
- selectVideo(videoId, multiSelect = false) {
- if (!multiSelect) {
- this.ui.selectedVideos = [videoId];
- } else {
- if (!this.ui.selectedVideos.includes(videoId)) {
- this.ui.selectedVideos.push(videoId);
- }
- }
- this.emit('videoSelectionChanged', { selectedVideos: this.ui.selectedVideos });
- }
- deselectVideo(videoId) {
- this.ui.selectedVideos = this.ui.selectedVideos.filter(id => id !== videoId);
- this.emit('videoSelectionChanged', { selectedVideos: this.ui.selectedVideos });
- }
- selectAllVideos() {
- this.ui.selectedVideos = this.videos.map(v => v.id);
- this.emit('videoSelectionChanged', { selectedVideos: this.ui.selectedVideos });
- }
- deselectAllVideos() {
- this.ui.selectedVideos = [];
- this.emit('videoSelectionChanged', { selectedVideos: this.ui.selectedVideos });
- }
- toggleVideoSelection(videoId) {
- if (this.ui.selectedVideos.includes(videoId)) {
- this.deselectVideo(videoId);
- } else {
- this.selectVideo(videoId, true);
- }
- }
- // Sort videos
- sortVideos(sortBy, sortOrder = 'asc') {
- this.ui.sortBy = sortBy;
- this.ui.sortOrder = sortOrder;
- this.videos.sort((a, b) => {
- let valueA, valueB;
- switch (sortBy) {
- case 'title':
- valueA = a.getDisplayName().toLowerCase();
- valueB = b.getDisplayName().toLowerCase();
- break;
- case 'duration':
- valueA = a.duration || '00:00';
- valueB = b.duration || '00:00';
- break;
- case 'status':
- valueA = a.status;
- valueB = b.status;
- break;
- case 'quality':
- valueA = a.quality;
- valueB = b.quality;
- break;
- case 'format':
- valueA = a.format;
- valueB = b.format;
- break;
- case 'createdAt':
- default:
- valueA = a.createdAt.getTime();
- valueB = b.createdAt.getTime();
- break;
- }
- if (sortOrder === 'desc') {
- return valueA > valueB ? -1 : valueA < valueB ? 1 : 0;
- } else {
- return valueA < valueB ? -1 : valueA > valueB ? 1 : 0;
- }
- });
- this.emit('videosSorted', { sortBy, sortOrder });
- }
- // Configuration management
- updateConfig(newConfig) {
- const oldConfig = { ...this.config };
- Object.assign(this.config, newConfig);
- this.emit('configUpdated', { config: this.config, oldConfig });
- }
- // UI state management
- updateUI(newUIState) {
- const oldUIState = { ...this.ui };
- Object.assign(this.ui, newUIState);
- this.emit('uiUpdated', { ui: this.ui, oldUIState });
- }
- // Download queue management
- addToDownloadQueue(videoIds) {
- const newItems = videoIds.filter(id => !this.downloadQueue.includes(id));
- this.downloadQueue.push(...newItems);
- this.emit('downloadQueueUpdated', { downloadQueue: this.downloadQueue });
- }
- removeFromDownloadQueue(videoId) {
- this.downloadQueue = this.downloadQueue.filter(id => id !== videoId);
- this.emit('downloadQueueUpdated', { downloadQueue: this.downloadQueue });
- }
- clearDownloadQueue() {
- this.downloadQueue = [];
- this.emit('downloadQueueUpdated', { downloadQueue: this.downloadQueue });
- }
- // Event system for state changes
- on(event, callback) {
- if (!this.listeners.has(event)) {
- this.listeners.set(event, []);
- }
- this.listeners.get(event).push(callback);
- }
- off(event, callback) {
- if (this.listeners.has(event)) {
- const callbacks = this.listeners.get(event);
- const index = callbacks.indexOf(callback);
- if (index > -1) {
- callbacks.splice(index, 1);
- }
- }
- }
- emit(event, data) {
- if (this.listeners.has(event)) {
- this.listeners.get(event).forEach(callback => {
- try {
- callback(data);
- } catch (error) {
- console.error(`Error in event listener for ${event}:`, error);
- }
- });
- }
- }
- // Statistics and analytics
- getStats() {
- const statusCounts = {
- total: this.videos.length,
- ready: 0,
- downloading: 0,
- converting: 0,
- completed: 0,
- error: 0
- };
- this.videos.forEach(video => {
- statusCounts[video.status] = (statusCounts[video.status] || 0) + 1;
- });
- return {
- ...statusCounts,
- selected: this.ui.selectedVideos.length,
- queueLength: this.downloadQueue.length,
- downloadStats: { ...this.downloadStats }
- };
- }
- // Update download statistics
- updateDownloadStats(stats) {
- Object.assign(this.downloadStats, stats);
- this.emit('downloadStatsUpdated', { stats: this.downloadStats });
- }
- // Keyboard navigation support
- setKeyboardNavigationActive(active) {
- this.ui.keyboardNavigationActive = active;
- if (!active) {
- this.ui.currentFocusIndex = -1;
- }
- this.emit('keyboardNavigationChanged', { active });
- }
- setCurrentFocusIndex(index) {
- this.ui.currentFocusIndex = Math.max(-1, Math.min(index, this.videos.length - 1));
- this.emit('focusIndexChanged', { index: this.ui.currentFocusIndex });
- }
- // State persistence
- toJSON() {
- return {
- videos: this.videos.map(v => v.toJSON()),
- history: this.history,
- config: this.config,
- ui: {
- ...this.ui,
- selectedVideos: this.ui.selectedVideos // Keep selected videos
- },
- downloadQueue: this.downloadQueue,
- downloadStats: this.downloadStats,
- timestamp: new Date().toISOString()
- };
- }
- // State restoration
- fromJSON(data) {
- try {
- // Restore videos
- this.videos = (data.videos || []).map(v => window.Video.fromJSON(v));
- // Restore history
- this.history = data.history || [];
- // Restore config with defaults
- this.config = {
- ...this.config,
- ...data.config
- };
- // Restore UI state with defaults
- this.ui = {
- ...this.ui,
- ...data.ui,
- keyboardNavigationActive: false, // Reset navigation state
- currentFocusIndex: -1
- };
- // Restore download queue and stats
- this.downloadQueue = data.downloadQueue || [];
- this.downloadStats = {
- ...this.downloadStats,
- ...data.downloadStats
- };
- this.emit('stateImported', { data });
- return true;
- } catch (error) {
- console.error('Failed to restore state from JSON:', error);
- return false;
- }
- }
- // Validation and cleanup
- validateState() {
- // Remove invalid videos
- this.videos = this.videos.filter(video => {
- try {
- return video instanceof window.Video && video.url;
- } catch (error) {
- console.warn('Removing invalid video:', error);
- return false;
- }
- });
- // Clean up selected videos
- const videoIds = this.videos.map(v => v.id);
- this.ui.selectedVideos = this.ui.selectedVideos.filter(id => videoIds.includes(id));
- // Clean up download queue
- this.downloadQueue = this.downloadQueue.filter(id => videoIds.includes(id));
- this.emit('stateValidated');
- }
- // Add completed video to download history
- addToHistory(video) {
- const historyEntry = {
- id: video.id,
- url: video.url,
- title: video.title,
- thumbnail: video.thumbnail,
- duration: video.duration,
- quality: video.quality,
- format: video.format,
- filename: video.filename,
- downloadedAt: new Date().toISOString()
- };
- // Add to beginning of history array
- this.history.unshift(historyEntry);
- // Keep only maxHistoryEntries
- if (this.history.length > this.config.maxHistoryEntries) {
- this.history = this.history.slice(0, this.config.maxHistoryEntries);
- }
- this.emit('historyUpdated', { entry: historyEntry });
- }
- // Get all history entries
- getHistory() {
- return this.history;
- }
- // Clear all history
- clearHistory() {
- this.history = [];
- this.emit('historyCleared');
- }
- // Remove specific history entry
- removeHistoryEntry(entryId) {
- const index = this.history.findIndex(entry => entry.id === entryId);
- if (index !== -1) {
- const removed = this.history.splice(index, 1)[0];
- this.emit('historyEntryRemoved', { entry: removed });
- }
- }
- // Reset to initial state
- reset() {
- this.videos = [];
- this.history = [];
- this.ui.selectedVideos = [];
- this.ui.currentFocusIndex = -1;
- this.downloadQueue = [];
- this.downloadStats = {
- totalDownloads: 0,
- successfulDownloads: 0,
- failedDownloads: 0,
- totalBytesDownloaded: 0
- };
- this.emit('stateReset');
- }
- }
- // Export for use in other modules
- if (typeof module !== 'undefined' && module.exports) {
- // Node.js environment
- module.exports = AppState;
- } else {
- // Browser environment - attach to window
- window.AppState = AppState;
- }
|