app.js 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418
  1. // GrabZilla 2.1 - Application Entry Point
  2. // Modular architecture with clear separation of concerns
  3. class GrabZillaApp {
  4. constructor() {
  5. this.state = null;
  6. this.eventBus = null;
  7. this.initialized = false;
  8. this.modules = new Map();
  9. }
  10. // Initialize the application
  11. async init() {
  12. try {
  13. console.log('🚀 Initializing GrabZilla 2.1...');
  14. // Initialize event bus
  15. this.eventBus = window.eventBus;
  16. if (!this.eventBus) {
  17. throw new Error('EventBus not available');
  18. }
  19. // Initialize application state
  20. this.state = new window.AppState();
  21. if (!this.state) {
  22. throw new Error('AppState not available');
  23. }
  24. // Expose state globally for Video model to access current defaults
  25. window.appState = this.state;
  26. // Set up error handling
  27. this.setupErrorHandling();
  28. // Initialize UI components
  29. await this.initializeUI();
  30. // Set up event listeners
  31. this.setupEventListeners();
  32. // Load saved state if available
  33. await this.loadState();
  34. // Ensure save directory exists
  35. await this.ensureSaveDirectoryExists();
  36. // Check binary status and validate
  37. await this.checkAndValidateBinaries();
  38. // Initialize keyboard navigation
  39. this.initializeKeyboardNavigation();
  40. this.initialized = true;
  41. console.log('✅ GrabZilla 2.1 initialized successfully');
  42. // Notify that the app is ready
  43. this.eventBus.emit('app:ready', { app: this });
  44. } catch (error) {
  45. console.error('❌ Failed to initialize GrabZilla:', error);
  46. this.handleInitializationError(error);
  47. }
  48. }
  49. // Set up global error handling
  50. setupErrorHandling() {
  51. // Handle unhandled errors
  52. window.addEventListener('error', (event) => {
  53. console.error('Global error:', event.error);
  54. this.eventBus.emit('app:error', {
  55. type: 'global',
  56. error: event.error,
  57. filename: event.filename,
  58. lineno: event.lineno
  59. });
  60. });
  61. // Handle unhandled promise rejections
  62. window.addEventListener('unhandledrejection', (event) => {
  63. console.error('Unhandled promise rejection:', event.reason);
  64. this.eventBus.emit('app:error', {
  65. type: 'promise',
  66. error: event.reason
  67. });
  68. });
  69. // Listen for application errors
  70. this.eventBus.on('app:error', (errorData) => {
  71. // Handle errors appropriately
  72. this.displayError(errorData);
  73. });
  74. }
  75. // Initialize UI components
  76. async initializeUI() {
  77. // Update save path display
  78. this.updateSavePathDisplay();
  79. // Initialize dropdown values
  80. this.initializeDropdowns();
  81. // Set up video list
  82. this.initializeVideoList();
  83. // Set up status display
  84. this.updateStatusMessage('Ready to download videos');
  85. }
  86. // Set up main event listeners
  87. setupEventListeners() {
  88. // State change listeners
  89. this.state.on('videoAdded', (data) => this.onVideoAdded(data));
  90. this.state.on('videoRemoved', (data) => this.onVideoRemoved(data));
  91. this.state.on('videoUpdated', (data) => this.onVideoUpdated(data));
  92. this.state.on('videosReordered', (data) => this.onVideosReordered(data));
  93. this.state.on('videosCleared', (data) => this.onVideosCleared(data));
  94. this.state.on('configUpdated', (data) => this.onConfigUpdated(data));
  95. // UI event listeners
  96. this.setupButtonEventListeners();
  97. this.setupInputEventListeners();
  98. this.setupVideoListEventListeners();
  99. }
  100. // Set up button event listeners
  101. setupButtonEventListeners() {
  102. // Add Video button
  103. const addVideoBtn = document.getElementById('addVideoBtn');
  104. if (addVideoBtn) {
  105. addVideoBtn.addEventListener('click', () => this.handleAddVideo());
  106. }
  107. // Import URLs button
  108. const importUrlsBtn = document.getElementById('importUrlsBtn');
  109. if (importUrlsBtn) {
  110. importUrlsBtn.addEventListener('click', () => this.handleImportUrls());
  111. }
  112. // Save Path button
  113. const savePathBtn = document.getElementById('savePathBtn');
  114. if (savePathBtn) {
  115. savePathBtn.addEventListener('click', () => this.handleSelectSavePath());
  116. }
  117. // Cookie File button
  118. const cookieFileBtn = document.getElementById('cookieFileBtn');
  119. if (cookieFileBtn) {
  120. cookieFileBtn.addEventListener('click', () => this.handleSelectCookieFile());
  121. }
  122. // Control panel buttons
  123. const clearListBtn = document.getElementById('clearListBtn');
  124. if (clearListBtn) {
  125. clearListBtn.addEventListener('click', () => this.handleClearList());
  126. }
  127. const downloadVideosBtn = document.getElementById('downloadVideosBtn');
  128. if (downloadVideosBtn) {
  129. downloadVideosBtn.addEventListener('click', () => this.handleDownloadVideos());
  130. }
  131. const cancelDownloadsBtn = document.getElementById('cancelDownloadsBtn');
  132. if (cancelDownloadsBtn) {
  133. cancelDownloadsBtn.addEventListener('click', () => this.handleCancelDownloads());
  134. }
  135. const updateDepsBtn = document.getElementById('updateDepsBtn');
  136. if (updateDepsBtn) {
  137. updateDepsBtn.addEventListener('click', () => this.handleUpdateDependencies());
  138. }
  139. }
  140. // Set up input event listeners
  141. setupInputEventListeners() {
  142. // URL input - no paste handler needed, user clicks "Add Video" button
  143. const urlInput = document.getElementById('urlInput');
  144. if (urlInput) {
  145. // Optional: could add real-time validation feedback here
  146. }
  147. // Configuration inputs
  148. const defaultQuality = document.getElementById('defaultQuality');
  149. if (defaultQuality) {
  150. defaultQuality.addEventListener('change', (e) => {
  151. const newValue = e.target.value;
  152. this.state.updateConfig({ defaultQuality: newValue });
  153. // Ask if user wants to update existing videos
  154. this.promptUpdateExistingVideos('quality', newValue);
  155. });
  156. }
  157. const defaultFormat = document.getElementById('defaultFormat');
  158. if (defaultFormat) {
  159. defaultFormat.addEventListener('change', (e) => {
  160. const newValue = e.target.value;
  161. this.state.updateConfig({ defaultFormat: newValue });
  162. // Ask if user wants to update existing videos
  163. this.promptUpdateExistingVideos('format', newValue);
  164. });
  165. }
  166. }
  167. // Set up video list event listeners
  168. setupVideoListEventListeners() {
  169. const videoList = document.getElementById('videoList');
  170. if (videoList) {
  171. videoList.addEventListener('click', (e) => this.handleVideoListClick(e));
  172. videoList.addEventListener('change', (e) => this.handleVideoListChange(e));
  173. this.setupDragAndDrop(videoList);
  174. }
  175. }
  176. // Set up drag-and-drop reordering
  177. setupDragAndDrop(videoList) {
  178. let draggedElement = null;
  179. let draggedVideoId = null;
  180. videoList.addEventListener('dragstart', (e) => {
  181. const videoItem = e.target.closest('.video-item');
  182. if (!videoItem) return;
  183. draggedElement = videoItem;
  184. draggedVideoId = videoItem.dataset.videoId;
  185. videoItem.classList.add('opacity-50');
  186. e.dataTransfer.effectAllowed = 'move';
  187. e.dataTransfer.setData('text/html', videoItem.innerHTML);
  188. });
  189. videoList.addEventListener('dragover', (e) => {
  190. e.preventDefault();
  191. const videoItem = e.target.closest('.video-item');
  192. if (!videoItem || videoItem === draggedElement) return;
  193. e.dataTransfer.dropEffect = 'move';
  194. // Visual feedback - show where it will drop
  195. const rect = videoItem.getBoundingClientRect();
  196. const midpoint = rect.top + rect.height / 2;
  197. if (e.clientY < midpoint) {
  198. videoItem.classList.add('border-t-2', 'border-[#155dfc]');
  199. videoItem.classList.remove('border-b-2');
  200. } else {
  201. videoItem.classList.add('border-b-2', 'border-[#155dfc]');
  202. videoItem.classList.remove('border-t-2');
  203. }
  204. });
  205. videoList.addEventListener('dragleave', (e) => {
  206. const videoItem = e.target.closest('.video-item');
  207. if (videoItem) {
  208. videoItem.classList.remove('border-t-2', 'border-b-2', 'border-[#155dfc]');
  209. }
  210. });
  211. videoList.addEventListener('drop', (e) => {
  212. e.preventDefault();
  213. const targetItem = e.target.closest('.video-item');
  214. if (!targetItem || !draggedVideoId) return;
  215. const targetVideoId = targetItem.dataset.videoId;
  216. // Calculate drop position
  217. const rect = targetItem.getBoundingClientRect();
  218. const midpoint = rect.top + rect.height / 2;
  219. const dropBefore = e.clientY < midpoint;
  220. // Reorder in state
  221. this.handleVideoReorder(draggedVideoId, targetVideoId, dropBefore);
  222. // Clean up visual feedback
  223. targetItem.classList.remove('border-t-2', 'border-b-2', 'border-[#155dfc]');
  224. });
  225. videoList.addEventListener('dragend', (e) => {
  226. const videoItem = e.target.closest('.video-item');
  227. if (videoItem) {
  228. videoItem.classList.remove('opacity-50');
  229. }
  230. // Clean up all visual feedback
  231. document.querySelectorAll('.video-item').forEach(item => {
  232. item.classList.remove('border-t-2', 'border-b-2', 'border-[#155dfc]');
  233. });
  234. draggedElement = null;
  235. draggedVideoId = null;
  236. });
  237. }
  238. handleVideoReorder(draggedId, targetId, insertBefore) {
  239. const videos = this.state.getVideos();
  240. const draggedIndex = videos.findIndex(v => v.id === draggedId);
  241. const targetIndex = videos.findIndex(v => v.id === targetId);
  242. if (draggedIndex === -1 || targetIndex === -1) return;
  243. let newIndex = targetIndex;
  244. if (draggedIndex < targetIndex && !insertBefore) {
  245. newIndex = targetIndex;
  246. } else if (draggedIndex > targetIndex && insertBefore) {
  247. newIndex = targetIndex;
  248. } else if (insertBefore) {
  249. newIndex = targetIndex;
  250. } else {
  251. newIndex = targetIndex + 1;
  252. }
  253. this.state.reorderVideos(draggedIndex, newIndex);
  254. }
  255. // Handle clicks in video list (checkboxes, delete buttons)
  256. handleVideoListClick(event) {
  257. const target = event.target;
  258. const videoItem = target.closest('.video-item');
  259. if (!videoItem) return;
  260. const videoId = videoItem.dataset.videoId;
  261. if (!videoId) return;
  262. // Handle checkbox click
  263. if (target.closest('.video-checkbox')) {
  264. event.preventDefault();
  265. this.toggleVideoSelection(videoId);
  266. return;
  267. }
  268. // Handle delete button click (if we add one later)
  269. if (target.closest('.delete-video-btn')) {
  270. event.preventDefault();
  271. this.handleRemoveVideo(videoId);
  272. return;
  273. }
  274. }
  275. // Handle dropdown changes in video list (quality, format)
  276. handleVideoListChange(event) {
  277. const target = event.target;
  278. const videoItem = target.closest('.video-item');
  279. if (!videoItem) return;
  280. const videoId = videoItem.dataset.videoId;
  281. if (!videoId) return;
  282. // Handle quality dropdown change
  283. if (target.classList.contains('quality-select')) {
  284. const quality = target.value;
  285. this.state.updateVideo(videoId, { quality });
  286. console.log(`Updated video ${videoId} quality to ${quality}`);
  287. return;
  288. }
  289. // Handle format dropdown change
  290. if (target.classList.contains('format-select')) {
  291. const format = target.value;
  292. this.state.updateVideo(videoId, { format });
  293. console.log(`Updated video ${videoId} format to ${format}`);
  294. return;
  295. }
  296. }
  297. // Toggle video selection
  298. toggleVideoSelection(videoId) {
  299. this.state.toggleVideoSelection(videoId);
  300. this.updateVideoCheckbox(videoId);
  301. }
  302. // Update checkbox visual state
  303. updateVideoCheckbox(videoId) {
  304. const videoItem = document.querySelector(`[data-video-id="${videoId}"]`);
  305. if (!videoItem) return;
  306. const checkbox = videoItem.querySelector('.video-checkbox');
  307. if (!checkbox) return;
  308. const isSelected = this.state.ui.selectedVideos.includes(videoId);
  309. checkbox.setAttribute('aria-checked', isSelected ? 'true' : 'false');
  310. // Update checkbox SVG
  311. const svg = checkbox.querySelector('svg');
  312. if (svg) {
  313. if (isSelected) {
  314. svg.innerHTML = `<rect x="3" y="3" width="10" height="10" stroke="currentColor" stroke-width="1.5" fill="currentColor" rx="2" />
  315. <path d="M5 8L7 10L11 6" stroke="white" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/>`;
  316. } else {
  317. svg.innerHTML = `<rect x="3" y="3" width="10" height="10" stroke="currentColor" stroke-width="1.5" fill="none" rx="2" />`;
  318. }
  319. }
  320. }
  321. // Remove video from list
  322. handleRemoveVideo(videoId) {
  323. try {
  324. const video = this.state.getVideo(videoId);
  325. if (video && confirm(`Remove "${video.getDisplayName()}"?`)) {
  326. this.state.removeVideo(videoId);
  327. this.updateStatusMessage('Video removed');
  328. }
  329. } catch (error) {
  330. console.error('Error removing video:', error);
  331. this.showError(`Failed to remove video: ${error.message}`);
  332. }
  333. }
  334. // Event handlers
  335. async handleAddVideo() {
  336. const urlInput = document.getElementById('urlInput');
  337. const inputText = urlInput?.value.trim();
  338. if (!inputText) {
  339. this.showError('Please enter a URL');
  340. return;
  341. }
  342. try {
  343. this.updateStatusMessage('Adding videos...');
  344. // Validate URLs
  345. const validation = window.URLValidator.validateMultipleUrls(inputText);
  346. if (validation.invalid.length > 0) {
  347. this.showError(`Invalid URLs found: ${validation.invalid.join(', ')}`);
  348. return;
  349. }
  350. if (validation.valid.length === 0) {
  351. this.showError('No valid URLs found');
  352. return;
  353. }
  354. // Add videos to state
  355. const results = await this.state.addVideosFromUrls(validation.valid);
  356. // Clear input on success
  357. if (urlInput) {
  358. urlInput.value = '';
  359. }
  360. // Show results
  361. const successCount = results.successful.length;
  362. const duplicateCount = results.duplicates.length;
  363. const failedCount = results.failed.length;
  364. let message = `Added ${successCount} video(s)`;
  365. if (duplicateCount > 0) {
  366. message += `, ${duplicateCount} duplicate(s) skipped`;
  367. }
  368. if (failedCount > 0) {
  369. message += `, ${failedCount} failed`;
  370. }
  371. this.updateStatusMessage(message);
  372. } catch (error) {
  373. console.error('Error adding videos:', error);
  374. this.showError(`Failed to add videos: ${error.message}`);
  375. }
  376. }
  377. async handleImportUrls() {
  378. if (!window.electronAPI) {
  379. this.showError('File import requires Electron environment');
  380. return;
  381. }
  382. try {
  383. // Implementation would use Electron file dialog
  384. this.updateStatusMessage('Import URLs functionality coming soon');
  385. } catch (error) {
  386. this.showError(`Failed to import URLs: ${error.message}`);
  387. }
  388. }
  389. async handleSelectSavePath() {
  390. if (!window.IPCManager || !window.IPCManager.isAvailable()) {
  391. this.showError('Path selection requires Electron environment');
  392. return;
  393. }
  394. try {
  395. this.updateStatusMessage('Select download directory...');
  396. const result = await window.IPCManager.selectSaveDirectory();
  397. if (result && result.success && result.path) {
  398. this.state.updateConfig({ savePath: result.path });
  399. await this.ensureSaveDirectoryExists(); // Auto-create directory
  400. this.updateSavePathDisplay();
  401. this.updateStatusMessage(`Save path set to: ${result.path}`);
  402. } else if (result && result.error) {
  403. this.showError(result.error);
  404. } else {
  405. this.updateStatusMessage('No directory selected');
  406. }
  407. } catch (error) {
  408. console.error('Error selecting save path:', error);
  409. this.showError(`Failed to select save path: ${error.message}`);
  410. }
  411. }
  412. async handleSelectCookieFile() {
  413. if (!window.IPCManager || !window.IPCManager.isAvailable()) {
  414. this.showError('File selection requires Electron environment');
  415. return;
  416. }
  417. try {
  418. this.updateStatusMessage('Select cookie file...');
  419. const result = await window.IPCManager.selectCookieFile();
  420. if (result && result.success && result.path) {
  421. this.state.updateConfig({ cookieFile: result.path });
  422. this.updateStatusMessage(`Cookie file set: ${result.path}`);
  423. // Update UI to show selected cookie file
  424. const cookieFilePathElement = document.getElementById('cookieFilePath');
  425. if (cookieFilePathElement) {
  426. const fileName = result.path.split('/').pop() || result.path.split('\\').pop();
  427. cookieFilePathElement.textContent = fileName;
  428. cookieFilePathElement.title = result.path;
  429. }
  430. } else if (result && result.error) {
  431. this.showError(result.error);
  432. } else {
  433. this.updateStatusMessage('No file selected');
  434. }
  435. } catch (error) {
  436. console.error('Error selecting cookie file:', error);
  437. this.showError(`Failed to select cookie file: ${error.message}`);
  438. }
  439. }
  440. handleClearList() {
  441. if (this.state.getVideos().length === 0) {
  442. this.updateStatusMessage('No videos to clear');
  443. return;
  444. }
  445. const removedVideos = this.state.clearVideos();
  446. this.updateStatusMessage(`Cleared ${removedVideos.length} video(s)`);
  447. }
  448. async handleDownloadVideos() {
  449. // Check if IPC is available
  450. if (!window.IPCManager || !window.IPCManager.isAvailable()) {
  451. this.showError('Download functionality requires Electron environment');
  452. return;
  453. }
  454. // Get downloadable videos (either selected or all ready videos)
  455. const selectedVideos = this.state.getSelectedVideos().filter(v => v.isDownloadable());
  456. const videos = selectedVideos.length > 0
  457. ? selectedVideos
  458. : this.state.getVideos().filter(v => v.isDownloadable());
  459. if (videos.length === 0) {
  460. this.showError('No videos ready for download');
  461. return;
  462. }
  463. // Validate save path
  464. if (!this.state.config.savePath) {
  465. this.showError('Please select a save directory first');
  466. return;
  467. }
  468. this.state.updateUI({ isDownloading: true });
  469. this.updateStatusMessage(`Starting download of ${videos.length} video(s)...`);
  470. // Set up download progress listener
  471. window.IPCManager.onDownloadProgress('app', (progressData) => {
  472. this.handleDownloadProgress(progressData);
  473. });
  474. // Download videos sequentially
  475. let successCount = 0;
  476. let failedCount = 0;
  477. for (const video of videos) {
  478. try {
  479. // Update video status to downloading
  480. this.state.updateVideo(video.id, { status: 'downloading', progress: 0 });
  481. const result = await window.IPCManager.downloadVideo({
  482. videoId: video.id,
  483. url: video.url,
  484. quality: video.quality,
  485. format: video.format,
  486. savePath: this.state.config.savePath,
  487. cookieFile: this.state.config.cookieFile
  488. });
  489. if (result.success) {
  490. this.state.updateVideo(video.id, {
  491. status: 'completed',
  492. progress: 100,
  493. filename: result.filename
  494. });
  495. successCount++;
  496. // Show notification for successful download
  497. this.showDownloadNotification(video, 'success');
  498. } else {
  499. this.state.updateVideo(video.id, {
  500. status: 'error',
  501. error: result.error || 'Download failed'
  502. });
  503. failedCount++;
  504. // Show notification for failed download
  505. this.showDownloadNotification(video, 'error', result.error);
  506. }
  507. } catch (error) {
  508. console.error(`Error downloading video ${video.id}:`, error);
  509. this.state.updateVideo(video.id, {
  510. status: 'error',
  511. error: error.message
  512. });
  513. failedCount++;
  514. }
  515. }
  516. // Clean up progress listener
  517. window.IPCManager.removeDownloadProgressListener('app');
  518. this.state.updateUI({ isDownloading: false });
  519. // Show final status
  520. let message = `Download complete: ${successCount} succeeded`;
  521. if (failedCount > 0) {
  522. message += `, ${failedCount} failed`;
  523. }
  524. this.updateStatusMessage(message);
  525. }
  526. // Handle download progress updates from IPC
  527. handleDownloadProgress(progressData) {
  528. const { url, progress, status, stage, message } = progressData;
  529. // Find video by URL
  530. const video = this.state.getVideos().find(v => v.url === url);
  531. if (!video) return;
  532. // Update video progress
  533. this.state.updateVideo(video.id, {
  534. progress: Math.round(progress),
  535. status: status || 'downloading'
  536. });
  537. }
  538. // Show download notification
  539. async showDownloadNotification(video, type, errorMessage = null) {
  540. if (!window.electronAPI) return;
  541. try {
  542. const notificationOptions = {
  543. title: type === 'success' ? 'Download Complete' : 'Download Failed',
  544. message: type === 'success'
  545. ? `${video.getDisplayName()}`
  546. : `${video.getDisplayName()}: ${errorMessage || 'Unknown error'}`,
  547. sound: true
  548. };
  549. await window.electronAPI.showNotification(notificationOptions);
  550. } catch (error) {
  551. console.warn('Failed to show notification:', error);
  552. }
  553. }
  554. async handleCancelDownloads() {
  555. const activeDownloads = this.state.getVideosByStatus('downloading').length +
  556. this.state.getVideosByStatus('converting').length;
  557. if (activeDownloads === 0) {
  558. this.updateStatusMessage('No active downloads to cancel');
  559. return;
  560. }
  561. if (!window.IPCManager || !window.IPCManager.isAvailable()) {
  562. this.showError('Cancel functionality requires Electron environment');
  563. return;
  564. }
  565. try {
  566. this.updateStatusMessage(`Cancelling ${activeDownloads} active download(s)...`);
  567. // Cancel all conversions via IPC
  568. await window.electronAPI.cancelAllConversions();
  569. // Update video statuses to ready
  570. const downloadingVideos = this.state.getVideosByStatus('downloading');
  571. const convertingVideos = this.state.getVideosByStatus('converting');
  572. [...downloadingVideos, ...convertingVideos].forEach(video => {
  573. this.state.updateVideo(video.id, {
  574. status: 'ready',
  575. progress: 0,
  576. error: 'Cancelled by user'
  577. });
  578. });
  579. this.state.updateUI({ isDownloading: false });
  580. this.updateStatusMessage('Downloads cancelled');
  581. } catch (error) {
  582. console.error('Error cancelling downloads:', error);
  583. this.showError(`Failed to cancel downloads: ${error.message}`);
  584. }
  585. }
  586. async handleUpdateDependencies() {
  587. if (!window.IPCManager || !window.IPCManager.isAvailable()) {
  588. this.showError('Update functionality requires Electron environment');
  589. return;
  590. }
  591. const btn = document.getElementById('updateDepsBtn');
  592. const originalBtnHTML = btn ? btn.innerHTML : '';
  593. try {
  594. // Show loading state
  595. this.updateStatusMessage('Checking binary versions...');
  596. if (btn) {
  597. btn.disabled = true;
  598. btn.innerHTML = '<img src="assets/icons/refresh.svg" alt="" width="16" height="16" loading="lazy" class="animate-spin">Checking...';
  599. }
  600. const versions = await window.IPCManager.checkBinaryVersions();
  601. // Handle both ytDlp (from main.js) and ytdlp (legacy) formats
  602. const ytdlp = versions.ytDlp || versions.ytdlp;
  603. const ffmpeg = versions.ffmpeg;
  604. if (versions && (ytdlp || ffmpeg)) {
  605. // Update both button status and version display
  606. const ytdlpMissing = !ytdlp || !ytdlp.available;
  607. const ffmpegMissing = !ffmpeg || !ffmpeg.available;
  608. if (ytdlpMissing || ffmpegMissing) {
  609. this.updateDependenciesButtonStatus('missing');
  610. this.updateBinaryVersionDisplay(null);
  611. } else {
  612. this.updateDependenciesButtonStatus('ok');
  613. // Normalize the format for display
  614. const normalizedVersions = {
  615. ytdlp: ytdlp,
  616. ffmpeg: ffmpeg
  617. };
  618. this.updateBinaryVersionDisplay(normalizedVersions);
  619. // Show dialog if updates are available
  620. if (ytdlp.updateAvailable) {
  621. this.showInfo({
  622. title: 'Update Available',
  623. message: `A newer version of yt-dlp is available:\nInstalled: ${ytdlp.version}\nLatest: ${ytdlp.latestVersion || 'newer version'}\n\nPlease run 'npm run setup' to update.`
  624. });
  625. }
  626. }
  627. } else {
  628. this.showError('Could not check binary versions');
  629. }
  630. } catch (error) {
  631. console.error('Error checking dependencies:', error);
  632. this.showError(`Failed to check dependencies: ${error.message}`);
  633. } finally {
  634. // Restore button state
  635. if (btn) {
  636. btn.disabled = false;
  637. btn.innerHTML = originalBtnHTML || '<img src="assets/icons/refresh.svg" alt="" width="16" height="16" loading="lazy">Check for Updates';
  638. }
  639. }
  640. }
  641. // State change handlers
  642. onVideoAdded(data) {
  643. this.renderVideoList();
  644. this.updateStatsDisplay();
  645. }
  646. onVideoRemoved(data) {
  647. this.renderVideoList();
  648. this.updateStatsDisplay();
  649. }
  650. onVideoUpdated(data) {
  651. this.updateVideoElement(data.video);
  652. this.updateStatsDisplay();
  653. }
  654. onVideosReordered(data) {
  655. // Re-render entire list to reflect new order
  656. this.renderVideoList();
  657. console.log('Video order updated:', data);
  658. }
  659. onVideosCleared(data) {
  660. this.renderVideoList();
  661. this.updateStatsDisplay();
  662. }
  663. onConfigUpdated(data) {
  664. this.updateConfigUI(data.config);
  665. }
  666. // UI update methods
  667. updateSavePathDisplay() {
  668. const savePathElement = document.getElementById('savePath');
  669. if (savePathElement) {
  670. savePathElement.textContent = this.state.config.savePath;
  671. }
  672. }
  673. initializeDropdowns() {
  674. // Set dropdown values from config
  675. const defaultQuality = document.getElementById('defaultQuality');
  676. if (defaultQuality) {
  677. defaultQuality.value = this.state.config.defaultQuality;
  678. }
  679. const defaultFormat = document.getElementById('defaultFormat');
  680. if (defaultFormat) {
  681. defaultFormat.value = this.state.config.defaultFormat;
  682. }
  683. }
  684. initializeVideoList() {
  685. this.renderVideoList();
  686. }
  687. renderVideoList() {
  688. const videoList = document.getElementById('videoList');
  689. if (!videoList) return;
  690. const videos = this.state.getVideos();
  691. // Clear all existing videos (including mockups)
  692. videoList.innerHTML = '';
  693. // If no videos, show empty state
  694. if (videos.length === 0) {
  695. videoList.innerHTML = `
  696. <div class="text-center py-12 text-[#90a1b9]">
  697. <p class="text-lg mb-2">No videos yet</p>
  698. <p class="text-sm">Paste YouTube or Vimeo URLs above to get started</p>
  699. </div>
  700. `;
  701. return;
  702. }
  703. // Render each video
  704. videos.forEach(video => {
  705. const videoElement = this.createVideoElement(video);
  706. videoList.appendChild(videoElement);
  707. });
  708. }
  709. createVideoElement(video) {
  710. const div = document.createElement('div');
  711. div.className = 'video-item grid grid-cols-[40px_40px_1fr_120px_100px_120px_100px_40px] gap-4 items-center p-2 rounded bg-[#314158] hover:bg-[#3a4a68] transition-colors duration-200';
  712. div.dataset.videoId = video.id;
  713. div.setAttribute('draggable', 'true'); // Make video item draggable
  714. div.innerHTML = `
  715. <!-- Checkbox -->
  716. <div class="flex items-center justify-center">
  717. <button class="video-checkbox w-6 h-6 rounded flex items-center justify-center hover:bg-[#45556c] transition-colors"
  718. role="checkbox" aria-checked="false" aria-label="Select ${video.getDisplayName()}">
  719. <svg width="16" height="16" viewBox="0 0 16 16" fill="none" class="text-white">
  720. <rect x="3" y="3" width="10" height="10" stroke="currentColor" stroke-width="1.5" fill="none" rx="2" />
  721. </svg>
  722. </button>
  723. </div>
  724. <!-- Drag Handle -->
  725. <div class="flex items-center justify-center text-[#90a1b9] hover:text-white cursor-grab transition-colors">
  726. <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
  727. <circle cx="4" cy="4" r="1" />
  728. <circle cx="4" cy="8" r="1" />
  729. <circle cx="4" cy="12" r="1" />
  730. <circle cx="8" cy="4" r="1" />
  731. <circle cx="8" cy="8" r="1" />
  732. <circle cx="8" cy="12" r="1" />
  733. <circle cx="12" cy="4" r="1" />
  734. <circle cx="12" cy="8" r="1" />
  735. <circle cx="12" cy="12" r="1" />
  736. </svg>
  737. </div>
  738. <!-- Video Info -->
  739. <div class="flex items-center gap-3 min-w-0">
  740. <div class="w-16 h-12 bg-[#45556c] rounded overflow-hidden flex-shrink-0">
  741. ${video.isFetchingMetadata ?
  742. `<div class="w-full h-full bg-gradient-to-br from-[#4a5568] to-[#2d3748] flex items-center justify-center">
  743. <svg class="animate-spin h-5 w-5 text-[#155dfc]" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
  744. <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
  745. <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
  746. </svg>
  747. </div>` :
  748. video.thumbnail ?
  749. `<img src="${video.thumbnail}" alt="${video.getDisplayName()}" class="w-full h-full object-cover">` :
  750. `<div class="w-full h-full bg-gradient-to-br from-[#4a5568] to-[#2d3748] flex items-center justify-center">
  751. <svg width="24" height="24" viewBox="0 0 24 24" fill="none" class="text-[#90a1b9]">
  752. <path d="M8 5V19L19 12L8 5Z" stroke="currentColor" stroke-width="2" stroke-linejoin="round" />
  753. </svg>
  754. </div>`
  755. }
  756. </div>
  757. <div class="min-w-0 flex-1">
  758. <div class="text-sm text-white truncate font-medium">${video.getDisplayName()}</div>
  759. ${video.isFetchingMetadata ?
  760. `<div class="text-xs text-[#155dfc] animate-pulse">Fetching info...</div>` :
  761. ''
  762. }
  763. </div>
  764. </div>
  765. <!-- Duration -->
  766. <div class="text-sm text-[#cad5e2] text-center">${video.duration || '--:--'}</div>
  767. <!-- Quality Dropdown -->
  768. <div class="flex justify-center">
  769. <select class="quality-select bg-[#314158] border border-[#45556c] text-[#cad5e2] px-2 py-1 rounded text-xs font-medium min-w-0 w-full text-center"
  770. aria-label="Quality for ${video.getDisplayName()}">
  771. <option value="4K" ${video.quality === '4K' ? 'selected' : ''}>4K</option>
  772. <option value="1440p" ${video.quality === '1440p' ? 'selected' : ''}>1440p</option>
  773. <option value="1080p" ${video.quality === '1080p' ? 'selected' : ''}>1080p</option>
  774. <option value="720p" ${video.quality === '720p' ? 'selected' : ''}>720p</option>
  775. </select>
  776. </div>
  777. <!-- Format Dropdown -->
  778. <div class="flex justify-center">
  779. <select class="format-select bg-[#314158] border border-[#45556c] text-[#cad5e2] px-2 py-1 rounded text-xs font-medium min-w-0 w-full text-center"
  780. aria-label="Format for ${video.getDisplayName()}">
  781. <option value="None" ${video.format === 'None' ? 'selected' : ''}>None</option>
  782. <option value="H264" ${video.format === 'H264' ? 'selected' : ''}>H264</option>
  783. <option value="ProRes" ${video.format === 'ProRes' ? 'selected' : ''}>ProRes</option>
  784. <option value="DNxHR" ${video.format === 'DNxHR' ? 'selected' : ''}>DNxHR</option>
  785. <option value="Audio only" ${video.format === 'Audio only' ? 'selected' : ''}>Audio only</option>
  786. </select>
  787. </div>
  788. <!-- Status Badge -->
  789. <div class="flex justify-center status-column">
  790. <span class="status-badge ${video.status}" role="status" aria-live="polite">
  791. ${this.getStatusText(video)}
  792. </span>
  793. </div>
  794. <!-- Delete Button -->
  795. <div class="flex items-center justify-center">
  796. <button class="delete-video-btn w-6 h-6 rounded flex items-center justify-center hover:bg-red-600 hover:text-white text-[#90a1b9] transition-colors duration-200"
  797. aria-label="Delete ${video.getDisplayName()}" title="Remove from queue">
  798. <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5">
  799. <path d="M3 4h10M5 4V3a1 1 0 011-1h4a1 1 0 011 1v1M6 7v4M10 7v4M4 4l1 9a1 1 0 001 1h4a1 1 0 001-1l1-9"
  800. stroke-linecap="round" stroke-linejoin="round"/>
  801. </svg>
  802. </button>
  803. </div>
  804. `;
  805. return div;
  806. }
  807. getStatusText(video) {
  808. switch (video.status) {
  809. case 'downloading':
  810. return `Downloading ${video.progress || 0}%`;
  811. case 'converting':
  812. return `Converting ${video.progress || 0}%`;
  813. case 'completed':
  814. return 'Completed';
  815. case 'error':
  816. return 'Error';
  817. case 'ready':
  818. default:
  819. return 'Ready';
  820. }
  821. }
  822. updateVideoElement(video) {
  823. const videoElement = document.querySelector(`[data-video-id="${video.id}"]`);
  824. if (!videoElement) return;
  825. // Update thumbnail - show loading spinner if fetching metadata
  826. const thumbnailContainer = videoElement.querySelector('.w-16.h-12');
  827. if (thumbnailContainer) {
  828. if (video.isFetchingMetadata) {
  829. thumbnailContainer.innerHTML = `
  830. <div class="w-full h-full bg-gradient-to-br from-[#4a5568] to-[#2d3748] flex items-center justify-center">
  831. <svg class="animate-spin h-5 w-5 text-[#155dfc]" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
  832. <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
  833. <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
  834. </svg>
  835. </div>`;
  836. } else if (video.thumbnail) {
  837. thumbnailContainer.innerHTML = `<img src="${video.thumbnail}" alt="${video.getDisplayName()}" class="w-full h-full object-cover">`;
  838. } else {
  839. thumbnailContainer.innerHTML = `
  840. <div class="w-full h-full bg-gradient-to-br from-[#4a5568] to-[#2d3748] flex items-center justify-center">
  841. <svg width="24" height="24" viewBox="0 0 24 24" fill="none" class="text-[#90a1b9]">
  842. <path d="M8 5V19L19 12L8 5Z" stroke="currentColor" stroke-width="2" stroke-linejoin="round" />
  843. </svg>
  844. </div>`;
  845. }
  846. }
  847. // Update title and loading message
  848. const titleContainer = videoElement.querySelector('.min-w-0.flex-1');
  849. if (titleContainer) {
  850. const titleElement = titleContainer.querySelector('.text-sm.text-white.truncate');
  851. if (titleElement) {
  852. titleElement.textContent = video.getDisplayName();
  853. }
  854. // Update or remove "Fetching info..." message
  855. const existingLoadingMsg = titleContainer.querySelector('.text-xs.text-\\[\\#155dfc\\]');
  856. if (video.isFetchingMetadata && !existingLoadingMsg) {
  857. const loadingMsg = document.createElement('div');
  858. loadingMsg.className = 'text-xs text-[#155dfc] animate-pulse';
  859. loadingMsg.textContent = 'Fetching info...';
  860. titleContainer.appendChild(loadingMsg);
  861. } else if (!video.isFetchingMetadata && existingLoadingMsg) {
  862. existingLoadingMsg.remove();
  863. }
  864. }
  865. // Update duration
  866. const durationElement = videoElement.querySelector('.text-sm.text-\\[\\#cad5e2\\].text-center');
  867. if (durationElement) {
  868. durationElement.textContent = video.duration || '--:--';
  869. }
  870. // Update quality dropdown
  871. const qualitySelect = videoElement.querySelector('.quality-select');
  872. if (qualitySelect) {
  873. qualitySelect.value = video.quality;
  874. }
  875. // Update format dropdown
  876. const formatSelect = videoElement.querySelector('.format-select');
  877. if (formatSelect) {
  878. formatSelect.value = video.format;
  879. }
  880. // Update status badge with progress
  881. const statusBadge = videoElement.querySelector('.status-badge');
  882. if (statusBadge) {
  883. statusBadge.className = `status-badge ${video.status}`;
  884. statusBadge.textContent = this.getStatusText(video);
  885. // Add progress bar for downloading/converting states
  886. if (video.status === 'downloading' || video.status === 'converting') {
  887. const progress = video.progress || 0;
  888. statusBadge.style.background = `linear-gradient(to right, #155dfc ${progress}%, #314158 ${progress}%)`;
  889. } else {
  890. statusBadge.style.background = '';
  891. }
  892. }
  893. }
  894. updateStatsDisplay() {
  895. const stats = this.state.getStats();
  896. // Update UI with current statistics
  897. }
  898. updateConfigUI(config) {
  899. this.updateSavePathDisplay();
  900. this.initializeDropdowns();
  901. }
  902. updateStatusMessage(message) {
  903. const statusElement = document.getElementById('statusMessage');
  904. if (statusElement) {
  905. statusElement.textContent = message;
  906. }
  907. // Auto-clear success messages
  908. if (!message.toLowerCase().includes('error') && !message.toLowerCase().includes('failed')) {
  909. setTimeout(() => {
  910. if (statusElement && statusElement.textContent === message) {
  911. statusElement.textContent = 'Ready to download videos';
  912. }
  913. }, 5000);
  914. }
  915. }
  916. showError(message) {
  917. this.updateStatusMessage(`Error: ${message}`);
  918. console.error('App Error:', message);
  919. this.eventBus.emit('app:error', { type: 'user', message });
  920. }
  921. displayError(errorData) {
  922. const message = errorData.error?.message || errorData.message || 'An error occurred';
  923. this.updateStatusMessage(`Error: ${message}`);
  924. }
  925. /**
  926. * Prompt user to update existing videos with new default settings
  927. * @param {string} property - 'quality' or 'format'
  928. * @param {string} newValue - New default value
  929. */
  930. promptUpdateExistingVideos(property, newValue) {
  931. const allVideos = this.state.getVideos();
  932. const selectedVideos = this.state.getSelectedVideos();
  933. // Determine which videos to potentially update
  934. // If videos are selected, only update those; otherwise, update all downloadable videos
  935. const videosToCheck = selectedVideos.length > 0
  936. ? selectedVideos.filter(v => v.status === 'ready' || v.status === 'error')
  937. : allVideos.filter(v => v.status === 'ready' || v.status === 'error');
  938. // Only prompt if there are videos that could be updated
  939. if (videosToCheck.length === 0) {
  940. return;
  941. }
  942. const propertyName = property === 'quality' ? 'quality' : 'format';
  943. const scope = selectedVideos.length > 0 ? 'selected' : 'all';
  944. const message = `Update ${scope} ${videosToCheck.length} video(s) in the list to use ${propertyName}: ${newValue}?`;
  945. if (confirm(message)) {
  946. let updatedCount = 0;
  947. videosToCheck.forEach(video => {
  948. this.state.updateVideo(video.id, { [property]: newValue });
  949. updatedCount++;
  950. });
  951. this.updateStatusMessage(`Updated ${updatedCount} ${scope} video(s) with new ${propertyName}: ${newValue}`);
  952. this.renderVideoList();
  953. }
  954. }
  955. // Keyboard navigation
  956. initializeKeyboardNavigation() {
  957. // Basic keyboard navigation setup
  958. document.addEventListener('keydown', (e) => {
  959. if (e.ctrlKey || e.metaKey) {
  960. switch (e.key) {
  961. case 'a':
  962. e.preventDefault();
  963. this.state.selectAllVideos();
  964. break;
  965. case 'd':
  966. e.preventDefault();
  967. this.handleDownloadVideos();
  968. break;
  969. }
  970. }
  971. });
  972. }
  973. // Ensure save directory exists
  974. async ensureSaveDirectoryExists() {
  975. const savePath = this.state.config.savePath;
  976. if (!savePath || !window.electronAPI) return;
  977. try {
  978. const result = await window.electronAPI.createDirectory(savePath);
  979. if (!result.success) {
  980. console.warn('Failed to create save directory:', result.error);
  981. } else {
  982. console.log('Save directory ready:', result.path);
  983. }
  984. } catch (error) {
  985. console.error('Error creating directory:', error);
  986. }
  987. }
  988. // Check binary status and validate with blocking dialog if missing
  989. async checkAndValidateBinaries() {
  990. if (!window.IPCManager || !window.IPCManager.isAvailable()) return;
  991. try {
  992. const versions = await window.IPCManager.checkBinaryVersions();
  993. // Handle both ytDlp (from main.js) and ytdlp (legacy) formats
  994. const ytdlp = versions.ytDlp || versions.ytdlp;
  995. const ffmpeg = versions.ffmpeg;
  996. if (!versions || !ytdlp || !ytdlp.available || !ffmpeg || !ffmpeg.available) {
  997. this.updateDependenciesButtonStatus('missing');
  998. this.updateBinaryVersionDisplay(null);
  999. // Show blocking dialog to warn user
  1000. await this.showMissingBinariesDialog(ytdlp, ffmpeg);
  1001. } else {
  1002. this.updateDependenciesButtonStatus('ok');
  1003. // Normalize the format for display
  1004. const normalizedVersions = {
  1005. ytdlp: ytdlp,
  1006. ffmpeg: ffmpeg
  1007. };
  1008. this.updateBinaryVersionDisplay(normalizedVersions);
  1009. }
  1010. } catch (error) {
  1011. console.error('Error checking binary status:', error);
  1012. // Set missing status on error
  1013. this.updateDependenciesButtonStatus('missing');
  1014. this.updateBinaryVersionDisplay(null);
  1015. // Show dialog on error too
  1016. await this.showMissingBinariesDialog(null, null);
  1017. }
  1018. }
  1019. // Show blocking dialog when binaries are missing
  1020. async showMissingBinariesDialog(ytdlp, ffmpeg) {
  1021. // Determine which binaries are missing
  1022. const missingBinaries = [];
  1023. if (!ytdlp || !ytdlp.available) missingBinaries.push('yt-dlp');
  1024. if (!ffmpeg || !ffmpeg.available) missingBinaries.push('ffmpeg');
  1025. const missingList = missingBinaries.length > 0
  1026. ? missingBinaries.join(', ')
  1027. : 'yt-dlp and ffmpeg';
  1028. if (window.electronAPI && window.electronAPI.showErrorDialog) {
  1029. // Use native Electron dialog
  1030. await window.electronAPI.showErrorDialog({
  1031. title: 'Required Binaries Missing',
  1032. message: `The following required binaries are missing: ${missingList}`,
  1033. detail: 'Please run "npm run setup" in the terminal to download the required binaries.\n\n' +
  1034. 'Without these binaries, GrabZilla cannot download or convert videos.\n\n' +
  1035. 'After running "npm run setup", restart the application.'
  1036. });
  1037. } else {
  1038. // Fallback to browser alert
  1039. alert(
  1040. `⚠️ Required Binaries Missing\n\n` +
  1041. `Missing: ${missingList}\n\n` +
  1042. `Please run "npm run setup" to download the required binaries.\n\n` +
  1043. `Without these binaries, GrabZilla cannot download or convert videos.`
  1044. );
  1045. }
  1046. }
  1047. // Check binary status and update UI (non-blocking version for updates)
  1048. async checkBinaryStatus() {
  1049. if (!window.IPCManager || !window.IPCManager.isAvailable()) return;
  1050. try {
  1051. const versions = await window.IPCManager.checkBinaryVersions();
  1052. // Handle both ytDlp (from main.js) and ytdlp (legacy) formats
  1053. const ytdlp = versions.ytDlp || versions.ytdlp;
  1054. const ffmpeg = versions.ffmpeg;
  1055. if (!versions || !ytdlp || !ytdlp.available || !ffmpeg || !ffmpeg.available) {
  1056. this.updateDependenciesButtonStatus('missing');
  1057. this.updateBinaryVersionDisplay(null);
  1058. } else {
  1059. this.updateDependenciesButtonStatus('ok');
  1060. // Normalize the format for display
  1061. const normalizedVersions = {
  1062. ytdlp: ytdlp,
  1063. ffmpeg: ffmpeg
  1064. };
  1065. this.updateBinaryVersionDisplay(normalizedVersions);
  1066. }
  1067. } catch (error) {
  1068. console.error('Error checking binary status:', error);
  1069. // Set missing status on error
  1070. this.updateDependenciesButtonStatus('missing');
  1071. this.updateBinaryVersionDisplay(null);
  1072. }
  1073. }
  1074. updateBinaryVersionDisplay(versions) {
  1075. const statusMessage = document.getElementById('statusMessage');
  1076. const ytdlpVersionNumber = document.getElementById('ytdlpVersionNumber');
  1077. const ytdlpUpdateBadge = document.getElementById('ytdlpUpdateBadge');
  1078. const ffmpegVersionNumber = document.getElementById('ffmpegVersionNumber');
  1079. const lastUpdateCheck = document.getElementById('lastUpdateCheck');
  1080. if (!versions) {
  1081. // Binaries missing
  1082. if (statusMessage) statusMessage.textContent = 'Ready to download videos - Binaries required';
  1083. if (ytdlpVersionNumber) ytdlpVersionNumber.textContent = 'missing';
  1084. if (ffmpegVersionNumber) ffmpegVersionNumber.textContent = 'missing';
  1085. if (ytdlpUpdateBadge) ytdlpUpdateBadge.classList.add('hidden');
  1086. if (lastUpdateCheck) lastUpdateCheck.textContent = '--';
  1087. return;
  1088. }
  1089. // Update yt-dlp version
  1090. if (ytdlpVersionNumber) {
  1091. const ytdlpVersion = versions.ytdlp?.version || 'unknown';
  1092. ytdlpVersionNumber.textContent = ytdlpVersion;
  1093. }
  1094. // Show/hide update badge for yt-dlp
  1095. if (ytdlpUpdateBadge) {
  1096. if (versions.ytdlp?.updateAvailable) {
  1097. ytdlpUpdateBadge.classList.remove('hidden');
  1098. ytdlpUpdateBadge.title = `Update available: ${versions.ytdlp.latestVersion || 'newer version'}`;
  1099. } else {
  1100. ytdlpUpdateBadge.classList.add('hidden');
  1101. }
  1102. }
  1103. // Update ffmpeg version
  1104. if (ffmpegVersionNumber) {
  1105. const ffmpegVersion = versions.ffmpeg?.version || 'unknown';
  1106. ffmpegVersionNumber.textContent = ffmpegVersion;
  1107. }
  1108. // Update last check timestamp
  1109. if (lastUpdateCheck) {
  1110. const now = new Date();
  1111. const timeString = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  1112. lastUpdateCheck.textContent = `checked ${timeString}`;
  1113. lastUpdateCheck.title = `Last update check: ${now.toLocaleString()}`;
  1114. }
  1115. // Update status message
  1116. if (statusMessage) {
  1117. const hasUpdates = versions.ytdlp?.updateAvailable;
  1118. statusMessage.textContent = hasUpdates ?
  1119. 'Update available for yt-dlp' :
  1120. 'Ready to download videos';
  1121. }
  1122. }
  1123. updateDependenciesButtonStatus(status) {
  1124. const btn = document.getElementById('updateDepsBtn');
  1125. if (!btn) return;
  1126. if (status === 'missing') {
  1127. btn.classList.add('bg-red-600', 'animate-pulse');
  1128. btn.classList.remove('bg-[#314158]');
  1129. btn.innerHTML = '<img src="assets/icons/refresh.svg" alt="" width="16" height="16" loading="lazy">⚠️ Required';
  1130. } else {
  1131. btn.classList.remove('bg-red-600', 'animate-pulse');
  1132. btn.classList.add('bg-[#314158]');
  1133. btn.innerHTML = '<img src="assets/icons/refresh.svg" alt="" width="16" height="16" loading="lazy">Check for Updates';
  1134. }
  1135. }
  1136. // State persistence
  1137. async loadState() {
  1138. try {
  1139. const savedState = localStorage.getItem('grabzilla-state');
  1140. if (savedState) {
  1141. const data = JSON.parse(savedState);
  1142. this.state.fromJSON(data);
  1143. console.log('✅ Loaded saved state');
  1144. // Re-render video list to show restored videos
  1145. this.renderVideoList();
  1146. this.updateSavePathDisplay();
  1147. this.updateStatsDisplay();
  1148. }
  1149. } catch (error) {
  1150. console.warn('Failed to load saved state:', error);
  1151. }
  1152. }
  1153. async saveState() {
  1154. try {
  1155. const stateData = this.state.toJSON();
  1156. localStorage.setItem('grabzilla-state', JSON.stringify(stateData));
  1157. } catch (error) {
  1158. console.warn('Failed to save state:', error);
  1159. }
  1160. }
  1161. // Lifecycle methods
  1162. handleInitializationError(error) {
  1163. // Show fallback UI or error message
  1164. const statusElement = document.getElementById('statusMessage');
  1165. if (statusElement) {
  1166. statusElement.textContent = 'Failed to initialize application';
  1167. }
  1168. }
  1169. destroy() {
  1170. // Clean up resources
  1171. if (this.state) {
  1172. this.saveState();
  1173. }
  1174. // Remove event listeners
  1175. this.eventBus?.removeAllListeners();
  1176. this.initialized = false;
  1177. console.log('🧹 GrabZilla app destroyed');
  1178. }
  1179. }
  1180. // Initialize function to be called after all scripts are loaded
  1181. window.initializeGrabZilla = function() {
  1182. window.app = new GrabZillaApp();
  1183. window.app.init();
  1184. };
  1185. // Auto-save state on page unload
  1186. window.addEventListener('beforeunload', () => {
  1187. if (window.app?.initialized) {
  1188. window.app.saveState();
  1189. }
  1190. });
  1191. // Export the app class
  1192. if (typeof module !== 'undefined' && module.exports) {
  1193. module.exports = GrabZillaApp;
  1194. } else {
  1195. window.GrabZillaApp = GrabZillaApp;
  1196. }