AppState.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. // GrabZilla 2.1 - Application State Management
  2. // Centralized state management with event system
  3. class AppState {
  4. constructor() {
  5. this.videos = [];
  6. this.history = []; // Array of completed download history entries
  7. this.config = {
  8. savePath: this.getDefaultDownloadsPath(),
  9. defaultQuality: window.AppConfig?.APP_CONFIG?.DEFAULT_QUALITY || '1080p',
  10. defaultFormat: window.AppConfig?.APP_CONFIG?.DEFAULT_FORMAT || 'None',
  11. filenamePattern: window.AppConfig?.APP_CONFIG?.DEFAULT_FILENAME_PATTERN || '%(title)s.%(ext)s',
  12. cookieFile: null,
  13. maxHistoryEntries: 100 // Maximum number of history entries to keep
  14. };
  15. this.ui = {
  16. isDownloading: false,
  17. selectedVideos: [],
  18. sortBy: 'createdAt',
  19. sortOrder: 'desc',
  20. keyboardNavigationActive: false,
  21. currentFocusIndex: -1
  22. };
  23. this.listeners = new Map();
  24. this.downloadQueue = [];
  25. this.downloadStats = {
  26. totalDownloads: 0,
  27. successfulDownloads: 0,
  28. failedDownloads: 0,
  29. totalBytesDownloaded: 0
  30. };
  31. }
  32. // Get default downloads path based on platform
  33. getDefaultDownloadsPath() {
  34. const defaultPaths = window.AppConfig?.DEFAULT_PATHS || {
  35. darwin: '~/Downloads/GrabZilla_Videos',
  36. win32: 'C:\\Users\\Admin\\Desktop\\GrabZilla_Videos',
  37. linux: '~/Downloads/GrabZilla_Videos'
  38. };
  39. if (window.electronAPI) {
  40. try {
  41. const platform = window.electronAPI.getPlatform();
  42. return defaultPaths[platform] || defaultPaths.linux;
  43. } catch (error) {
  44. console.warn('Failed to get platform:', error);
  45. return defaultPaths.win32;
  46. }
  47. }
  48. return defaultPaths.win32;
  49. }
  50. // Video management methods
  51. addVideo(video) {
  52. if (!(video instanceof window.Video)) {
  53. throw new Error('Invalid video object');
  54. }
  55. // Check for duplicate URLs
  56. const existingVideo = this.videos.find(v => v.getNormalizedUrl() === video.getNormalizedUrl());
  57. if (existingVideo) {
  58. throw new Error('Video URL already exists in the list');
  59. }
  60. this.videos.push(video);
  61. this.emit('videoAdded', { video });
  62. return video;
  63. }
  64. // Add multiple videos from URLs
  65. async addVideosFromUrls(urls, options = {}) {
  66. const { allowDuplicates = false } = options;
  67. const results = {
  68. successful: [],
  69. failed: [],
  70. duplicates: []
  71. };
  72. // Filter out duplicates first (unless allowDuplicates is true)
  73. const uniqueUrls = [];
  74. for (const url of urls) {
  75. if (allowDuplicates) {
  76. // Skip duplicate check
  77. uniqueUrls.push(url);
  78. } else {
  79. const normalizedUrl = window.URLValidator ? window.URLValidator.normalizeUrl(url) : url;
  80. const existingVideo = this.videos.find(v => v.getNormalizedUrl() === normalizedUrl);
  81. if (existingVideo) {
  82. results.duplicates.push({ url, reason: 'URL already exists' });
  83. } else {
  84. uniqueUrls.push(url);
  85. }
  86. }
  87. }
  88. // Create videos immediately for instant UI feedback (non-blocking)
  89. for (const url of uniqueUrls) {
  90. try {
  91. const video = window.Video.fromUrl(url);
  92. this.addVideo(video);
  93. results.successful.push(video);
  94. } catch (error) {
  95. results.failed.push({ url, error: error.message });
  96. }
  97. }
  98. // Prefetch metadata in background (non-blocking, parallel for better UX)
  99. // Videos will update automatically via Video.fromUrl() metadata fetch
  100. if (uniqueUrls.length > 0 && window.MetadataService) {
  101. console.log(`[Batch Metadata] Starting background fetch for ${uniqueUrls.length} URLs...`);
  102. const startTime = performance.now();
  103. // Don't await - let it run in background
  104. window.MetadataService.prefetchMetadata(uniqueUrls)
  105. .then(() => {
  106. const duration = performance.now() - startTime;
  107. console.log(`[Batch Metadata] Completed in ${Math.round(duration)}ms (${Math.round(duration / uniqueUrls.length)}ms avg/video)`);
  108. })
  109. .catch(error => {
  110. console.warn('[Batch Metadata] Batch prefetch failed:', error.message);
  111. });
  112. }
  113. this.emit('videosAdded', { results });
  114. return results;
  115. }
  116. // Reorder videos in the array
  117. reorderVideos(fromIndex, toIndex) {
  118. if (fromIndex === toIndex) return;
  119. if (fromIndex < 0 || fromIndex >= this.videos.length ||
  120. toIndex < 0 || toIndex > this.videos.length) {
  121. throw new Error('Invalid indices for reordering');
  122. }
  123. // Remove from old position
  124. const [movedVideo] = this.videos.splice(fromIndex, 1);
  125. // Insert at new position
  126. const adjustedToIndex = fromIndex < toIndex ? toIndex - 1 : toIndex;
  127. this.videos.splice(adjustedToIndex, 0, movedVideo);
  128. this.emit('videosReordered', {
  129. fromIndex,
  130. toIndex: adjustedToIndex,
  131. videoId: movedVideo.id
  132. });
  133. console.log(`Reordered video from position ${fromIndex} to ${adjustedToIndex}`);
  134. }
  135. // Remove video from state
  136. removeVideo(videoId) {
  137. const index = this.videos.findIndex(v => v.id === videoId);
  138. if (index === -1) {
  139. throw new Error('Video not found');
  140. }
  141. const removedVideo = this.videos.splice(index, 1)[0];
  142. // Remove from selected videos if present
  143. this.ui.selectedVideos = this.ui.selectedVideos.filter(id => id !== videoId);
  144. this.emit('videoRemoved', { video: removedVideo });
  145. return removedVideo;
  146. }
  147. // Remove multiple videos
  148. removeVideos(videoIds) {
  149. const removedVideos = [];
  150. const errors = [];
  151. for (const videoId of videoIds) {
  152. try {
  153. const removed = this.removeVideo(videoId);
  154. removedVideos.push(removed);
  155. } catch (error) {
  156. errors.push({ videoId, error: error.message });
  157. }
  158. }
  159. this.emit('videosRemoved', { removedVideos, errors });
  160. return { removedVideos, errors };
  161. }
  162. // Update video in state
  163. updateVideo(videoId, properties) {
  164. const video = this.videos.find(v => v.id === videoId);
  165. if (!video) {
  166. throw new Error('Video not found');
  167. }
  168. const oldProperties = { ...video };
  169. video.update(properties);
  170. this.emit('videoUpdated', { video, oldProperties });
  171. return video;
  172. }
  173. // Get video by ID
  174. getVideo(videoId) {
  175. return this.videos.find(v => v.id === videoId);
  176. }
  177. // Get all videos
  178. getVideos() {
  179. return [...this.videos];
  180. }
  181. // Get videos by status
  182. getVideosByStatus(status) {
  183. return this.videos.filter(v => v.status === status);
  184. }
  185. // Get selected videos
  186. getSelectedVideos() {
  187. return this.videos.filter(v => this.ui.selectedVideos.includes(v.id));
  188. }
  189. // Clear all videos
  190. clearVideos() {
  191. const removedVideos = [...this.videos];
  192. this.videos = [];
  193. this.ui.selectedVideos = [];
  194. this.downloadQueue = [];
  195. this.emit('videosCleared', { removedVideos });
  196. return removedVideos;
  197. }
  198. // Selection management
  199. selectVideo(videoId, multiSelect = false) {
  200. if (!multiSelect) {
  201. this.ui.selectedVideos = [videoId];
  202. } else {
  203. if (!this.ui.selectedVideos.includes(videoId)) {
  204. this.ui.selectedVideos.push(videoId);
  205. }
  206. }
  207. this.emit('videoSelectionChanged', { selectedVideos: this.ui.selectedVideos });
  208. }
  209. deselectVideo(videoId) {
  210. this.ui.selectedVideos = this.ui.selectedVideos.filter(id => id !== videoId);
  211. this.emit('videoSelectionChanged', { selectedVideos: this.ui.selectedVideos });
  212. }
  213. selectAllVideos() {
  214. this.ui.selectedVideos = this.videos.map(v => v.id);
  215. this.emit('videoSelectionChanged', { selectedVideos: this.ui.selectedVideos });
  216. }
  217. deselectAllVideos() {
  218. this.ui.selectedVideos = [];
  219. this.emit('videoSelectionChanged', { selectedVideos: this.ui.selectedVideos });
  220. }
  221. toggleVideoSelection(videoId) {
  222. if (this.ui.selectedVideos.includes(videoId)) {
  223. this.deselectVideo(videoId);
  224. } else {
  225. this.selectVideo(videoId, true);
  226. }
  227. }
  228. // Sort videos
  229. sortVideos(sortBy, sortOrder = 'asc') {
  230. this.ui.sortBy = sortBy;
  231. this.ui.sortOrder = sortOrder;
  232. this.videos.sort((a, b) => {
  233. let valueA, valueB;
  234. switch (sortBy) {
  235. case 'title':
  236. valueA = a.getDisplayName().toLowerCase();
  237. valueB = b.getDisplayName().toLowerCase();
  238. break;
  239. case 'duration':
  240. valueA = a.duration || '00:00';
  241. valueB = b.duration || '00:00';
  242. break;
  243. case 'status':
  244. valueA = a.status;
  245. valueB = b.status;
  246. break;
  247. case 'quality':
  248. valueA = a.quality;
  249. valueB = b.quality;
  250. break;
  251. case 'format':
  252. valueA = a.format;
  253. valueB = b.format;
  254. break;
  255. case 'createdAt':
  256. default:
  257. valueA = a.createdAt.getTime();
  258. valueB = b.createdAt.getTime();
  259. break;
  260. }
  261. if (sortOrder === 'desc') {
  262. return valueA > valueB ? -1 : valueA < valueB ? 1 : 0;
  263. } else {
  264. return valueA < valueB ? -1 : valueA > valueB ? 1 : 0;
  265. }
  266. });
  267. this.emit('videosSorted', { sortBy, sortOrder });
  268. }
  269. // Configuration management
  270. updateConfig(newConfig) {
  271. const oldConfig = { ...this.config };
  272. Object.assign(this.config, newConfig);
  273. this.emit('configUpdated', { config: this.config, oldConfig });
  274. }
  275. // UI state management
  276. updateUI(newUIState) {
  277. const oldUIState = { ...this.ui };
  278. Object.assign(this.ui, newUIState);
  279. this.emit('uiUpdated', { ui: this.ui, oldUIState });
  280. }
  281. // Download queue management
  282. addToDownloadQueue(videoIds) {
  283. const newItems = videoIds.filter(id => !this.downloadQueue.includes(id));
  284. this.downloadQueue.push(...newItems);
  285. this.emit('downloadQueueUpdated', { downloadQueue: this.downloadQueue });
  286. }
  287. removeFromDownloadQueue(videoId) {
  288. this.downloadQueue = this.downloadQueue.filter(id => id !== videoId);
  289. this.emit('downloadQueueUpdated', { downloadQueue: this.downloadQueue });
  290. }
  291. clearDownloadQueue() {
  292. this.downloadQueue = [];
  293. this.emit('downloadQueueUpdated', { downloadQueue: this.downloadQueue });
  294. }
  295. // Event system for state changes
  296. on(event, callback) {
  297. if (!this.listeners.has(event)) {
  298. this.listeners.set(event, []);
  299. }
  300. this.listeners.get(event).push(callback);
  301. }
  302. off(event, callback) {
  303. if (this.listeners.has(event)) {
  304. const callbacks = this.listeners.get(event);
  305. const index = callbacks.indexOf(callback);
  306. if (index > -1) {
  307. callbacks.splice(index, 1);
  308. }
  309. }
  310. }
  311. emit(event, data) {
  312. if (this.listeners.has(event)) {
  313. this.listeners.get(event).forEach(callback => {
  314. try {
  315. callback(data);
  316. } catch (error) {
  317. console.error(`Error in event listener for ${event}:`, error);
  318. }
  319. });
  320. }
  321. }
  322. // Statistics and analytics
  323. getStats() {
  324. const statusCounts = {
  325. total: this.videos.length,
  326. ready: 0,
  327. downloading: 0,
  328. converting: 0,
  329. completed: 0,
  330. error: 0
  331. };
  332. this.videos.forEach(video => {
  333. statusCounts[video.status] = (statusCounts[video.status] || 0) + 1;
  334. });
  335. return {
  336. ...statusCounts,
  337. selected: this.ui.selectedVideos.length,
  338. queueLength: this.downloadQueue.length,
  339. downloadStats: { ...this.downloadStats }
  340. };
  341. }
  342. // Update download statistics
  343. updateDownloadStats(stats) {
  344. Object.assign(this.downloadStats, stats);
  345. this.emit('downloadStatsUpdated', { stats: this.downloadStats });
  346. }
  347. // Keyboard navigation support
  348. setKeyboardNavigationActive(active) {
  349. this.ui.keyboardNavigationActive = active;
  350. if (!active) {
  351. this.ui.currentFocusIndex = -1;
  352. }
  353. this.emit('keyboardNavigationChanged', { active });
  354. }
  355. setCurrentFocusIndex(index) {
  356. this.ui.currentFocusIndex = Math.max(-1, Math.min(index, this.videos.length - 1));
  357. this.emit('focusIndexChanged', { index: this.ui.currentFocusIndex });
  358. }
  359. // State persistence
  360. toJSON() {
  361. return {
  362. videos: this.videos.map(v => v.toJSON()),
  363. history: this.history,
  364. config: this.config,
  365. ui: {
  366. ...this.ui,
  367. selectedVideos: this.ui.selectedVideos // Keep selected videos
  368. },
  369. downloadQueue: this.downloadQueue,
  370. downloadStats: this.downloadStats,
  371. timestamp: new Date().toISOString()
  372. };
  373. }
  374. // State restoration
  375. fromJSON(data) {
  376. try {
  377. // Restore videos
  378. this.videos = (data.videos || []).map(v => window.Video.fromJSON(v));
  379. // Restore history
  380. this.history = data.history || [];
  381. // Restore config with defaults
  382. this.config = {
  383. ...this.config,
  384. ...data.config
  385. };
  386. // Restore UI state with defaults
  387. this.ui = {
  388. ...this.ui,
  389. ...data.ui,
  390. keyboardNavigationActive: false, // Reset navigation state
  391. currentFocusIndex: -1
  392. };
  393. // Restore download queue and stats
  394. this.downloadQueue = data.downloadQueue || [];
  395. this.downloadStats = {
  396. ...this.downloadStats,
  397. ...data.downloadStats
  398. };
  399. this.emit('stateImported', { data });
  400. return true;
  401. } catch (error) {
  402. console.error('Failed to restore state from JSON:', error);
  403. return false;
  404. }
  405. }
  406. // Validation and cleanup
  407. validateState() {
  408. // Remove invalid videos
  409. this.videos = this.videos.filter(video => {
  410. try {
  411. return video instanceof window.Video && video.url;
  412. } catch (error) {
  413. console.warn('Removing invalid video:', error);
  414. return false;
  415. }
  416. });
  417. // Clean up selected videos
  418. const videoIds = this.videos.map(v => v.id);
  419. this.ui.selectedVideos = this.ui.selectedVideos.filter(id => videoIds.includes(id));
  420. // Clean up download queue
  421. this.downloadQueue = this.downloadQueue.filter(id => videoIds.includes(id));
  422. this.emit('stateValidated');
  423. }
  424. // Add completed video to download history
  425. addToHistory(video) {
  426. const historyEntry = {
  427. id: video.id,
  428. url: video.url,
  429. title: video.title,
  430. thumbnail: video.thumbnail,
  431. duration: video.duration,
  432. quality: video.quality,
  433. format: video.format,
  434. filename: video.filename,
  435. downloadedAt: new Date().toISOString()
  436. };
  437. // Add to beginning of history array
  438. this.history.unshift(historyEntry);
  439. // Keep only maxHistoryEntries
  440. if (this.history.length > this.config.maxHistoryEntries) {
  441. this.history = this.history.slice(0, this.config.maxHistoryEntries);
  442. }
  443. this.emit('historyUpdated', { entry: historyEntry });
  444. }
  445. // Get all history entries
  446. getHistory() {
  447. return this.history;
  448. }
  449. // Clear all history
  450. clearHistory() {
  451. this.history = [];
  452. this.emit('historyCleared');
  453. }
  454. // Remove specific history entry
  455. removeHistoryEntry(entryId) {
  456. const index = this.history.findIndex(entry => entry.id === entryId);
  457. if (index !== -1) {
  458. const removed = this.history.splice(index, 1)[0];
  459. this.emit('historyEntryRemoved', { entry: removed });
  460. }
  461. }
  462. // Reset to initial state
  463. reset() {
  464. this.videos = [];
  465. this.history = [];
  466. this.ui.selectedVideos = [];
  467. this.ui.currentFocusIndex = -1;
  468. this.downloadQueue = [];
  469. this.downloadStats = {
  470. totalDownloads: 0,
  471. successfulDownloads: 0,
  472. failedDownloads: 0,
  473. totalBytesDownloaded: 0
  474. };
  475. this.emit('stateReset');
  476. }
  477. }
  478. // Export for use in other modules
  479. if (typeof module !== 'undefined' && module.exports) {
  480. // Node.js environment
  481. module.exports = AppState;
  482. } else {
  483. // Browser environment - attach to window
  484. window.AppState = AppState;
  485. }