ipc-integration.js 11 KB

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