ipc-integration.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. /**
  2. * @fileoverview IPC Integration utilities for Electron desktop app functionality
  3. * @author GrabZilla Development Team
  4. * @version 2.1.0
  5. * @since 2024-01-01
  6. */
  7. /**
  8. * IPC INTEGRATION MODULE
  9. *
  10. * Provides secure communication layer between renderer and main process
  11. *
  12. * Features:
  13. * - File system operations (save directory, cookie file selection)
  14. * - Binary version checking and management
  15. * - Video download operations with progress tracking
  16. * - Secure IPC channel management
  17. *
  18. * Dependencies:
  19. * - Electron contextBridge API (exposed via preload script)
  20. * - Main process IPC handlers
  21. *
  22. * Security:
  23. * - All IPC calls are validated and sanitized
  24. * - No direct access to Node.js APIs from renderer
  25. * - Secure contextBridge exposure pattern
  26. */
  27. class IPCManager {
  28. constructor() {
  29. this.isElectronAvailable = typeof window !== 'undefined' && window.electronAPI;
  30. this.downloadProgressListeners = new Map();
  31. if (this.isElectronAvailable) {
  32. this.setupProgressListener();
  33. }
  34. }
  35. /**
  36. * Check if Electron IPC is available
  37. * @returns {boolean} True if running in Electron environment
  38. */
  39. isAvailable() {
  40. return this.isElectronAvailable;
  41. }
  42. /**
  43. * Set up download progress listener
  44. */
  45. setupProgressListener() {
  46. if (!this.isElectronAvailable) return;
  47. window.electronAPI.onDownloadProgress((event, progressData) => {
  48. const { url, progress } = progressData;
  49. // Notify all registered listeners
  50. this.downloadProgressListeners.forEach((callback, listenerId) => {
  51. try {
  52. callback({ url, progress });
  53. } catch (error) {
  54. console.error(`Error in download progress listener ${listenerId}:`, error);
  55. }
  56. });
  57. });
  58. }
  59. /**
  60. * Register download progress listener
  61. * @param {string} listenerId - Unique identifier for the listener
  62. * @param {Function} callback - Callback function to handle progress updates
  63. */
  64. onDownloadProgress(listenerId, callback) {
  65. if (typeof callback !== 'function') {
  66. throw new Error('Progress callback must be a function');
  67. }
  68. this.downloadProgressListeners.set(listenerId, callback);
  69. }
  70. /**
  71. * Remove download progress listener
  72. * @param {string} listenerId - Listener identifier to remove
  73. */
  74. removeDownloadProgressListener(listenerId) {
  75. this.downloadProgressListeners.delete(listenerId);
  76. }
  77. /**
  78. * Select save directory using native file dialog
  79. * @returns {Promise<string|null>} Selected directory path or null if cancelled
  80. */
  81. async selectSaveDirectory() {
  82. if (!this.isElectronAvailable) {
  83. throw new Error('File selection not available in browser mode');
  84. }
  85. try {
  86. const directoryPath = await window.electronAPI.selectSaveDirectory();
  87. return directoryPath;
  88. } catch (error) {
  89. console.error('Error selecting save directory:', error);
  90. throw new Error('Failed to select save directory');
  91. }
  92. }
  93. /**
  94. * Select cookie file using native file dialog
  95. * @returns {Promise<string|null>} Selected file path or null if cancelled
  96. */
  97. async selectCookieFile() {
  98. if (!this.isElectronAvailable) {
  99. throw new Error('File selection not available in browser mode');
  100. }
  101. try {
  102. const filePath = await window.electronAPI.selectCookieFile();
  103. return filePath;
  104. } catch (error) {
  105. console.error('Error selecting cookie file:', error);
  106. throw new Error('Failed to select cookie file');
  107. }
  108. }
  109. /**
  110. * Check binary versions (yt-dlp, ffmpeg)
  111. * @returns {Promise<Object>} Binary version information
  112. */
  113. async checkBinaryVersions() {
  114. if (!this.isElectronAvailable) {
  115. throw new Error('Binary checking not available in browser mode');
  116. }
  117. try {
  118. const versions = await window.electronAPI.checkBinaryVersions();
  119. return versions;
  120. } catch (error) {
  121. console.error('Error checking binary versions:', error);
  122. throw new Error('Failed to check binary versions');
  123. }
  124. }
  125. /**
  126. * Get video metadata from URL
  127. * @param {string} url - Video URL to fetch metadata for
  128. * @returns {Promise<Object>} Video metadata (title, duration, thumbnail, etc.)
  129. */
  130. async getVideoMetadata(url) {
  131. if (!this.isElectronAvailable) {
  132. throw new Error('Metadata fetching not available in browser mode');
  133. }
  134. if (!url || typeof url !== 'string') {
  135. throw new Error('Valid URL is required for metadata fetching');
  136. }
  137. try {
  138. const metadata = await window.electronAPI.getVideoMetadata(url);
  139. return metadata;
  140. } catch (error) {
  141. console.error('Error fetching video metadata:', error);
  142. throw new Error(`Failed to fetch metadata: ${error.message}`);
  143. }
  144. }
  145. /**
  146. * Get metadata for multiple URLs in a single batch request (5-10x faster)
  147. * @param {string[]} urls - Array of video URLs to fetch metadata for
  148. * @returns {Promise<Object[]>} Array of video metadata objects with url property
  149. */
  150. async getBatchVideoMetadata(urls) {
  151. if (!this.isElectronAvailable) {
  152. throw new Error('Batch metadata fetching not available in browser mode');
  153. }
  154. if (!Array.isArray(urls) || urls.length === 0) {
  155. throw new Error('Valid URL array is required for batch metadata fetching');
  156. }
  157. try {
  158. const results = await window.electronAPI.getBatchVideoMetadata(urls);
  159. return results;
  160. } catch (error) {
  161. console.error('Error fetching batch video metadata:', error);
  162. throw new Error(`Failed to fetch batch metadata: ${error.message}`);
  163. }
  164. }
  165. /**
  166. * Download video with specified options
  167. * @param {Object} options - Download options
  168. * @param {string} options.url - Video URL to download
  169. * @param {string} options.quality - Video quality (720p, 1080p, etc.)
  170. * @param {string} options.format - Output format (None, H264, ProRes, etc.)
  171. * @param {string} options.savePath - Directory to save the video
  172. * @param {string} [options.cookieFile] - Optional cookie file path
  173. * @returns {Promise<Object>} Download result
  174. */
  175. async downloadVideo(options) {
  176. if (!this.isElectronAvailable) {
  177. throw new Error('Video download not available in browser mode');
  178. }
  179. // Validate required options (now includes videoId for parallel processing)
  180. const requiredFields = ['videoId', 'url', 'quality', 'format', 'savePath'];
  181. for (const field of requiredFields) {
  182. if (!options[field]) {
  183. throw new Error(`Missing required field: ${field}`);
  184. }
  185. }
  186. // Sanitize options
  187. const sanitizedOptions = {
  188. videoId: options.videoId,
  189. url: options.url.trim(),
  190. quality: options.quality,
  191. format: options.format,
  192. savePath: options.savePath,
  193. cookieFile: options.cookieFile || null
  194. };
  195. try {
  196. const result = await window.electronAPI.downloadVideo(sanitizedOptions);
  197. return result;
  198. } catch (error) {
  199. console.error('Error downloading video:', error);
  200. throw new Error(`Download failed: ${error.message}`);
  201. }
  202. }
  203. /**
  204. * Get download manager statistics
  205. * @returns {Promise<Object>} Download stats
  206. */
  207. async getDownloadStats() {
  208. if (!this.isElectronAvailable) {
  209. return {
  210. active: 0,
  211. queued: 0,
  212. maxConcurrent: 1,
  213. completed: 0,
  214. canAcceptMore: true
  215. };
  216. }
  217. try {
  218. const result = await window.electronAPI.getDownloadStats();
  219. return result.stats;
  220. } catch (error) {
  221. console.error('Error getting download stats:', error);
  222. throw new Error(`Failed to get download stats: ${error.message}`);
  223. }
  224. }
  225. /**
  226. * Cancel a specific download
  227. * @param {string} videoId - Video ID to cancel
  228. * @returns {Promise<boolean>} Success status
  229. */
  230. async cancelDownload(videoId) {
  231. if (!this.isElectronAvailable) {
  232. throw new Error('Cancel download not available in browser mode');
  233. }
  234. try {
  235. const result = await window.electronAPI.cancelDownload(videoId);
  236. return result.success;
  237. } catch (error) {
  238. console.error('Error cancelling download:', error);
  239. throw new Error(`Failed to cancel download: ${error.message}`);
  240. }
  241. }
  242. /**
  243. * Cancel all queued downloads
  244. * @returns {Promise<Object>} Cancel result with counts
  245. */
  246. async cancelAllDownloads() {
  247. if (!this.isElectronAvailable) {
  248. throw new Error('Cancel all downloads not available in browser mode');
  249. }
  250. try {
  251. const result = await window.electronAPI.cancelAllDownloads();
  252. return result;
  253. } catch (error) {
  254. console.error('Error cancelling all downloads:', error);
  255. throw new Error(`Failed to cancel downloads: ${error.message}`);
  256. }
  257. }
  258. /**
  259. * Get app version information
  260. * @returns {string} App version
  261. */
  262. getAppVersion() {
  263. if (!this.isElectronAvailable) {
  264. return '2.1.0'; // Fallback version
  265. }
  266. try {
  267. return window.electronAPI.getAppVersion();
  268. } catch (error) {
  269. console.error('Error getting app version:', error);
  270. return '2.1.0';
  271. }
  272. }
  273. /**
  274. * Get platform information
  275. * @returns {string} Platform identifier (darwin, win32, linux)
  276. */
  277. getPlatform() {
  278. if (!this.isElectronAvailable) {
  279. return 'unknown';
  280. }
  281. try {
  282. return window.electronAPI.getPlatform();
  283. } catch (error) {
  284. console.error('Error getting platform:', error);
  285. return 'unknown';
  286. }
  287. }
  288. /**
  289. * Validate IPC connection and available methods
  290. * @returns {Object} Validation result with available methods
  291. */
  292. validateConnection() {
  293. if (!this.isElectronAvailable) {
  294. return {
  295. connected: false,
  296. error: 'Electron API not available',
  297. availableMethods: []
  298. };
  299. }
  300. const expectedMethods = [
  301. 'selectSaveDirectory',
  302. 'selectCookieFile',
  303. 'checkBinaryVersions',
  304. 'getVideoMetadata',
  305. 'getBatchVideoMetadata',
  306. 'downloadVideo',
  307. 'getAppVersion',
  308. 'getPlatform',
  309. 'onDownloadProgress'
  310. ];
  311. const availableMethods = expectedMethods.filter(method =>
  312. typeof window.electronAPI[method] === 'function'
  313. );
  314. const missingMethods = expectedMethods.filter(method =>
  315. typeof window.electronAPI[method] !== 'function'
  316. );
  317. return {
  318. connected: true,
  319. availableMethods,
  320. missingMethods,
  321. allMethodsAvailable: missingMethods.length === 0
  322. };
  323. }
  324. }
  325. // Export singleton instance
  326. const ipcManager = new IPCManager();
  327. // Export for use in other modules
  328. if (typeof module !== 'undefined' && module.exports) {
  329. module.exports = ipcManager;
  330. } else if (typeof window !== 'undefined') {
  331. window.IPCManager = ipcManager;
  332. }