AppState.js 18 KB

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