ipc-integration.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. * @param {string} cookieFile - Optional path to cookie file for authentication
  129. * @returns {Promise<Object>} Video metadata (title, duration, thumbnail, etc.)
  130. */
  131. async getVideoMetadata(url, cookieFile = null) {
  132. if (!this.isElectronAvailable) {
  133. throw new Error('Metadata fetching not available in browser mode');
  134. }
  135. if (!url || typeof url !== 'string') {
  136. throw new Error('Valid URL is required for metadata fetching');
  137. }
  138. try {
  139. const metadata = await window.electronAPI.getVideoMetadata(url, cookieFile);
  140. return metadata;
  141. } catch (error) {
  142. console.error('Error fetching video metadata:', error);
  143. throw new Error(`Failed to fetch metadata: ${error.message}`);
  144. }
  145. }
  146. /**
  147. * Get metadata for multiple URLs in a single batch request (5-10x faster)
  148. * @param {string[]} urls - Array of video URLs to fetch metadata for
  149. * @param {string} cookieFile - Optional path to cookie file for authentication
  150. * @returns {Promise<Object[]>} Array of video metadata objects with url property
  151. */
  152. async getBatchVideoMetadata(urls, cookieFile = null) {
  153. if (!this.isElectronAvailable) {
  154. throw new Error('Batch metadata fetching not available in browser mode');
  155. }
  156. if (!Array.isArray(urls) || urls.length === 0) {
  157. throw new Error('Valid URL array is required for batch metadata fetching');
  158. }
  159. try {
  160. const results = await window.electronAPI.getBatchVideoMetadata(urls, cookieFile);
  161. return results;
  162. } catch (error) {
  163. console.error('Error fetching batch video metadata:', error);
  164. throw new Error(`Failed to fetch batch metadata: ${error.message}`);
  165. }
  166. }
  167. /**
  168. * Download video with specified options
  169. * @param {Object} options - Download options
  170. * @param {string} options.url - Video URL to download
  171. * @param {string} options.quality - Video quality (720p, 1080p, etc.)
  172. * @param {string} options.format - Output format (None, H264, ProRes, etc.)
  173. * @param {string} options.savePath - Directory to save the video
  174. * @param {string} [options.cookieFile] - Optional cookie file path
  175. * @returns {Promise<Object>} Download result
  176. */
  177. async downloadVideo(options) {
  178. if (!this.isElectronAvailable) {
  179. throw new Error('Video download not available in browser mode');
  180. }
  181. // Validate required options (now includes videoId for parallel processing)
  182. const requiredFields = ['videoId', 'url', 'quality', 'format', 'savePath'];
  183. for (const field of requiredFields) {
  184. if (!options[field]) {
  185. throw new Error(`Missing required field: ${field}`);
  186. }
  187. }
  188. // Sanitize options
  189. const sanitizedOptions = {
  190. videoId: options.videoId,
  191. url: options.url.trim(),
  192. quality: options.quality,
  193. format: options.format,
  194. savePath: options.savePath,
  195. cookieFile: options.cookieFile || null
  196. };
  197. try {
  198. const result = await window.electronAPI.downloadVideo(sanitizedOptions);
  199. return result;
  200. } catch (error) {
  201. console.error('Error downloading video:', error);
  202. throw new Error(`Download failed: ${error.message}`);
  203. }
  204. }
  205. /**
  206. * Get download manager statistics
  207. * @returns {Promise<Object>} Download stats
  208. */
  209. async getDownloadStats() {
  210. if (!this.isElectronAvailable) {
  211. return {
  212. active: 0,
  213. queued: 0,
  214. maxConcurrent: 1,
  215. completed: 0,
  216. canAcceptMore: true
  217. };
  218. }
  219. try {
  220. const result = await window.electronAPI.getDownloadStats();
  221. return result.stats;
  222. } catch (error) {
  223. console.error('Error getting download stats:', error);
  224. throw new Error(`Failed to get download stats: ${error.message}`);
  225. }
  226. }
  227. /**
  228. * Cancel a specific download
  229. * @param {string} videoId - Video ID to cancel
  230. * @returns {Promise<boolean>} Success status
  231. */
  232. async cancelDownload(videoId) {
  233. if (!this.isElectronAvailable) {
  234. throw new Error('Cancel download not available in browser mode');
  235. }
  236. try {
  237. const result = await window.electronAPI.cancelDownload(videoId);
  238. return result.success;
  239. } catch (error) {
  240. console.error('Error cancelling download:', error);
  241. throw new Error(`Failed to cancel download: ${error.message}`);
  242. }
  243. }
  244. /**
  245. * Cancel all queued downloads
  246. * @returns {Promise<Object>} Cancel result with counts
  247. */
  248. async cancelAllDownloads() {
  249. if (!this.isElectronAvailable) {
  250. throw new Error('Cancel all downloads not available in browser mode');
  251. }
  252. try {
  253. const result = await window.electronAPI.cancelAllDownloads();
  254. return result;
  255. } catch (error) {
  256. console.error('Error cancelling all downloads:', error);
  257. throw new Error(`Failed to cancel downloads: ${error.message}`);
  258. }
  259. }
  260. /**
  261. * Get app version information
  262. * @returns {string} App version
  263. */
  264. getAppVersion() {
  265. if (!this.isElectronAvailable) {
  266. return '2.1.0'; // Fallback version
  267. }
  268. try {
  269. return window.electronAPI.getAppVersion();
  270. } catch (error) {
  271. console.error('Error getting app version:', error);
  272. return '2.1.0';
  273. }
  274. }
  275. /**
  276. * Get platform information
  277. * @returns {string} Platform identifier (darwin, win32, linux)
  278. */
  279. getPlatform() {
  280. if (!this.isElectronAvailable) {
  281. return 'unknown';
  282. }
  283. try {
  284. return window.electronAPI.getPlatform();
  285. } catch (error) {
  286. console.error('Error getting platform:', error);
  287. return 'unknown';
  288. }
  289. }
  290. /**
  291. * Validate IPC connection and available methods
  292. * @returns {Object} Validation result with available methods
  293. */
  294. validateConnection() {
  295. if (!this.isElectronAvailable) {
  296. return {
  297. connected: false,
  298. error: 'Electron API not available',
  299. availableMethods: []
  300. };
  301. }
  302. const expectedMethods = [
  303. 'selectSaveDirectory',
  304. 'selectCookieFile',
  305. 'checkBinaryVersions',
  306. 'getVideoMetadata',
  307. 'getBatchVideoMetadata',
  308. 'downloadVideo',
  309. 'getAppVersion',
  310. 'getPlatform',
  311. 'onDownloadProgress'
  312. ];
  313. const availableMethods = expectedMethods.filter(method =>
  314. typeof window.electronAPI[method] === 'function'
  315. );
  316. const missingMethods = expectedMethods.filter(method =>
  317. typeof window.electronAPI[method] !== 'function'
  318. );
  319. return {
  320. connected: true,
  321. availableMethods,
  322. missingMethods,
  323. allMethodsAvailable: missingMethods.length === 0
  324. };
  325. }
  326. }
  327. // Export singleton instance
  328. const ipcManager = new IPCManager();
  329. // Export for use in other modules
  330. if (typeof module !== 'undefined' && module.exports) {
  331. module.exports = ipcManager;
  332. } else if (typeof window !== 'undefined') {
  333. window.IPCManager = ipcManager;
  334. }