AppState.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. // Prefetch metadata for all unique URLs in batch (11.5% faster)
  81. if (uniqueUrls.length > 0 && window.MetadataService) {
  82. console.log(`[Batch Metadata] Fetching metadata for ${uniqueUrls.length} URLs...`);
  83. const startTime = performance.now();
  84. try {
  85. await window.MetadataService.prefetchMetadata(uniqueUrls);
  86. const duration = performance.now() - startTime;
  87. console.log(`[Batch Metadata] Completed in ${Math.round(duration)}ms (${Math.round(duration / uniqueUrls.length)}ms avg/video)`);
  88. } catch (error) {
  89. console.warn('[Batch Metadata] Batch prefetch failed, will fall back to individual fetches:', error.message);
  90. }
  91. }
  92. // Now create videos - metadata will be instantly available from cache
  93. for (const url of uniqueUrls) {
  94. try {
  95. const video = window.Video.fromUrl(url);
  96. this.addVideo(video);
  97. results.successful.push(video);
  98. } catch (error) {
  99. results.failed.push({ url, error: error.message });
  100. }
  101. }
  102. this.emit('videosAdded', { results });
  103. return results;
  104. }
  105. // Reorder videos in the array
  106. reorderVideos(fromIndex, toIndex) {
  107. if (fromIndex === toIndex) return;
  108. if (fromIndex < 0 || fromIndex >= this.videos.length ||
  109. toIndex < 0 || toIndex > this.videos.length) {
  110. throw new Error('Invalid indices for reordering');
  111. }
  112. // Remove from old position
  113. const [movedVideo] = this.videos.splice(fromIndex, 1);
  114. // Insert at new position
  115. const adjustedToIndex = fromIndex < toIndex ? toIndex - 1 : toIndex;
  116. this.videos.splice(adjustedToIndex, 0, movedVideo);
  117. this.emit('videosReordered', {
  118. fromIndex,
  119. toIndex: adjustedToIndex,
  120. videoId: movedVideo.id
  121. });
  122. console.log(`Reordered video from position ${fromIndex} to ${adjustedToIndex}`);
  123. }
  124. // Remove video from state
  125. removeVideo(videoId) {
  126. const index = this.videos.findIndex(v => v.id === videoId);
  127. if (index === -1) {
  128. throw new Error('Video not found');
  129. }
  130. const removedVideo = this.videos.splice(index, 1)[0];
  131. // Remove from selected videos if present
  132. this.ui.selectedVideos = this.ui.selectedVideos.filter(id => id !== videoId);
  133. this.emit('videoRemoved', { video: removedVideo });
  134. return removedVideo;
  135. }
  136. // Remove multiple videos
  137. removeVideos(videoIds) {
  138. const removedVideos = [];
  139. const errors = [];
  140. for (const videoId of videoIds) {
  141. try {
  142. const removed = this.removeVideo(videoId);
  143. removedVideos.push(removed);
  144. } catch (error) {
  145. errors.push({ videoId, error: error.message });
  146. }
  147. }
  148. this.emit('videosRemoved', { removedVideos, errors });
  149. return { removedVideos, errors };
  150. }
  151. // Update video in state
  152. updateVideo(videoId, properties) {
  153. const video = this.videos.find(v => v.id === videoId);
  154. if (!video) {
  155. throw new Error('Video not found');
  156. }
  157. const oldProperties = { ...video };
  158. video.update(properties);
  159. this.emit('videoUpdated', { video, oldProperties });
  160. return video;
  161. }
  162. // Get video by ID
  163. getVideo(videoId) {
  164. return this.videos.find(v => v.id === videoId);
  165. }
  166. // Get all videos
  167. getVideos() {
  168. return [...this.videos];
  169. }
  170. // Get videos by status
  171. getVideosByStatus(status) {
  172. return this.videos.filter(v => v.status === status);
  173. }
  174. // Get selected videos
  175. getSelectedVideos() {
  176. return this.videos.filter(v => this.ui.selectedVideos.includes(v.id));
  177. }
  178. // Clear all videos
  179. clearVideos() {
  180. const removedVideos = [...this.videos];
  181. this.videos = [];
  182. this.ui.selectedVideos = [];
  183. this.downloadQueue = [];
  184. this.emit('videosCleared', { removedVideos });
  185. return removedVideos;
  186. }
  187. // Selection management
  188. selectVideo(videoId, multiSelect = false) {
  189. if (!multiSelect) {
  190. this.ui.selectedVideos = [videoId];
  191. } else {
  192. if (!this.ui.selectedVideos.includes(videoId)) {
  193. this.ui.selectedVideos.push(videoId);
  194. }
  195. }
  196. this.emit('videoSelectionChanged', { selectedVideos: this.ui.selectedVideos });
  197. }
  198. deselectVideo(videoId) {
  199. this.ui.selectedVideos = this.ui.selectedVideos.filter(id => id !== videoId);
  200. this.emit('videoSelectionChanged', { selectedVideos: this.ui.selectedVideos });
  201. }
  202. selectAllVideos() {
  203. this.ui.selectedVideos = this.videos.map(v => v.id);
  204. this.emit('videoSelectionChanged', { selectedVideos: this.ui.selectedVideos });
  205. }
  206. deselectAllVideos() {
  207. this.ui.selectedVideos = [];
  208. this.emit('videoSelectionChanged', { selectedVideos: this.ui.selectedVideos });
  209. }
  210. toggleVideoSelection(videoId) {
  211. if (this.ui.selectedVideos.includes(videoId)) {
  212. this.deselectVideo(videoId);
  213. } else {
  214. this.selectVideo(videoId, true);
  215. }
  216. }
  217. // Sort videos
  218. sortVideos(sortBy, sortOrder = 'asc') {
  219. this.ui.sortBy = sortBy;
  220. this.ui.sortOrder = sortOrder;
  221. this.videos.sort((a, b) => {
  222. let valueA, valueB;
  223. switch (sortBy) {
  224. case 'title':
  225. valueA = a.getDisplayName().toLowerCase();
  226. valueB = b.getDisplayName().toLowerCase();
  227. break;
  228. case 'duration':
  229. valueA = a.duration || '00:00';
  230. valueB = b.duration || '00:00';
  231. break;
  232. case 'status':
  233. valueA = a.status;
  234. valueB = b.status;
  235. break;
  236. case 'quality':
  237. valueA = a.quality;
  238. valueB = b.quality;
  239. break;
  240. case 'format':
  241. valueA = a.format;
  242. valueB = b.format;
  243. break;
  244. case 'createdAt':
  245. default:
  246. valueA = a.createdAt.getTime();
  247. valueB = b.createdAt.getTime();
  248. break;
  249. }
  250. if (sortOrder === 'desc') {
  251. return valueA > valueB ? -1 : valueA < valueB ? 1 : 0;
  252. } else {
  253. return valueA < valueB ? -1 : valueA > valueB ? 1 : 0;
  254. }
  255. });
  256. this.emit('videosSorted', { sortBy, sortOrder });
  257. }
  258. // Configuration management
  259. updateConfig(newConfig) {
  260. const oldConfig = { ...this.config };
  261. Object.assign(this.config, newConfig);
  262. this.emit('configUpdated', { config: this.config, oldConfig });
  263. }
  264. // UI state management
  265. updateUI(newUIState) {
  266. const oldUIState = { ...this.ui };
  267. Object.assign(this.ui, newUIState);
  268. this.emit('uiUpdated', { ui: this.ui, oldUIState });
  269. }
  270. // Download queue management
  271. addToDownloadQueue(videoIds) {
  272. const newItems = videoIds.filter(id => !this.downloadQueue.includes(id));
  273. this.downloadQueue.push(...newItems);
  274. this.emit('downloadQueueUpdated', { downloadQueue: this.downloadQueue });
  275. }
  276. removeFromDownloadQueue(videoId) {
  277. this.downloadQueue = this.downloadQueue.filter(id => id !== videoId);
  278. this.emit('downloadQueueUpdated', { downloadQueue: this.downloadQueue });
  279. }
  280. clearDownloadQueue() {
  281. this.downloadQueue = [];
  282. this.emit('downloadQueueUpdated', { downloadQueue: this.downloadQueue });
  283. }
  284. // Event system for state changes
  285. on(event, callback) {
  286. if (!this.listeners.has(event)) {
  287. this.listeners.set(event, []);
  288. }
  289. this.listeners.get(event).push(callback);
  290. }
  291. off(event, callback) {
  292. if (this.listeners.has(event)) {
  293. const callbacks = this.listeners.get(event);
  294. const index = callbacks.indexOf(callback);
  295. if (index > -1) {
  296. callbacks.splice(index, 1);
  297. }
  298. }
  299. }
  300. emit(event, data) {
  301. if (this.listeners.has(event)) {
  302. this.listeners.get(event).forEach(callback => {
  303. try {
  304. callback(data);
  305. } catch (error) {
  306. console.error(`Error in event listener for ${event}:`, error);
  307. }
  308. });
  309. }
  310. }
  311. // Statistics and analytics
  312. getStats() {
  313. const statusCounts = {
  314. total: this.videos.length,
  315. ready: 0,
  316. downloading: 0,
  317. converting: 0,
  318. completed: 0,
  319. error: 0
  320. };
  321. this.videos.forEach(video => {
  322. statusCounts[video.status] = (statusCounts[video.status] || 0) + 1;
  323. });
  324. return {
  325. ...statusCounts,
  326. selected: this.ui.selectedVideos.length,
  327. queueLength: this.downloadQueue.length,
  328. downloadStats: { ...this.downloadStats }
  329. };
  330. }
  331. // Update download statistics
  332. updateDownloadStats(stats) {
  333. Object.assign(this.downloadStats, stats);
  334. this.emit('downloadStatsUpdated', { stats: this.downloadStats });
  335. }
  336. // Keyboard navigation support
  337. setKeyboardNavigationActive(active) {
  338. this.ui.keyboardNavigationActive = active;
  339. if (!active) {
  340. this.ui.currentFocusIndex = -1;
  341. }
  342. this.emit('keyboardNavigationChanged', { active });
  343. }
  344. setCurrentFocusIndex(index) {
  345. this.ui.currentFocusIndex = Math.max(-1, Math.min(index, this.videos.length - 1));
  346. this.emit('focusIndexChanged', { index: this.ui.currentFocusIndex });
  347. }
  348. // State persistence
  349. toJSON() {
  350. return {
  351. videos: this.videos.map(v => v.toJSON()),
  352. config: this.config,
  353. ui: {
  354. ...this.ui,
  355. selectedVideos: this.ui.selectedVideos // Keep selected videos
  356. },
  357. downloadQueue: this.downloadQueue,
  358. downloadStats: this.downloadStats,
  359. timestamp: new Date().toISOString()
  360. };
  361. }
  362. // State restoration
  363. fromJSON(data) {
  364. try {
  365. // Restore videos
  366. this.videos = (data.videos || []).map(v => window.Video.fromJSON(v));
  367. // Restore config with defaults
  368. this.config = {
  369. ...this.config,
  370. ...data.config
  371. };
  372. // Restore UI state with defaults
  373. this.ui = {
  374. ...this.ui,
  375. ...data.ui,
  376. keyboardNavigationActive: false, // Reset navigation state
  377. currentFocusIndex: -1
  378. };
  379. // Restore download queue and stats
  380. this.downloadQueue = data.downloadQueue || [];
  381. this.downloadStats = {
  382. ...this.downloadStats,
  383. ...data.downloadStats
  384. };
  385. this.emit('stateImported', { data });
  386. return true;
  387. } catch (error) {
  388. console.error('Failed to restore state from JSON:', error);
  389. return false;
  390. }
  391. }
  392. // Validation and cleanup
  393. validateState() {
  394. // Remove invalid videos
  395. this.videos = this.videos.filter(video => {
  396. try {
  397. return video instanceof window.Video && video.url;
  398. } catch (error) {
  399. console.warn('Removing invalid video:', error);
  400. return false;
  401. }
  402. });
  403. // Clean up selected videos
  404. const videoIds = this.videos.map(v => v.id);
  405. this.ui.selectedVideos = this.ui.selectedVideos.filter(id => videoIds.includes(id));
  406. // Clean up download queue
  407. this.downloadQueue = this.downloadQueue.filter(id => videoIds.includes(id));
  408. this.emit('stateValidated');
  409. }
  410. // Reset to initial state
  411. reset() {
  412. this.videos = [];
  413. this.ui.selectedVideos = [];
  414. this.ui.currentFocusIndex = -1;
  415. this.downloadQueue = [];
  416. this.downloadStats = {
  417. totalDownloads: 0,
  418. successfulDownloads: 0,
  419. failedDownloads: 0,
  420. totalBytesDownloaded: 0
  421. };
  422. this.emit('stateReset');
  423. }
  424. }
  425. // Export for use in other modules
  426. if (typeof module !== 'undefined' && module.exports) {
  427. // Node.js environment
  428. module.exports = AppState;
  429. } else {
  430. // Browser environment - attach to window
  431. window.AppState = AppState;
  432. }