AppState.js 16 KB

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