AppState.js 15 KB

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