-
Notifications
You must be signed in to change notification settings - Fork 20
/
ipc-handlers.ts
634 lines (557 loc) · 19.3 KB
/
ipc-handlers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
import { exec } from 'child_process';
import crypto from 'crypto';
import {
BrowserWindow,
app,
clipboard,
dialog,
shell,
type IpcMainInvokeEvent,
Notification,
} from 'electron';
import fs from 'fs';
import nodePath from 'path';
import * as Sentry from '@sentry/electron/main';
import archiver from 'archiver';
import { copySync } from 'fs-extra';
import { SQLITE_FILENAME } from '../vendor/wp-now/src/constants';
import { downloadSqliteIntegrationPlugin } from '../vendor/wp-now/src/download';
import { executeWPCli } from '../vendor/wp-now/src/execute-wp-cli';
import { LIMIT_ARCHIVE_SIZE } from './constants';
import { isEmptyDir, pathExists, isWordPressDirectory, sanitizeFolderName } from './lib/fs-utils';
import { getImageData } from './lib/get-image-data';
import { isErrnoException } from './lib/is-errno-exception';
import { isInstalled } from './lib/is-installed';
import { getLocaleData, getSupportedLocale } from './lib/locale';
import * as oauthClient from './lib/oauth';
import { createPassword } from './lib/passwords';
import { phpGetThemeDetails } from './lib/php-get-theme-details';
import { sanitizeForLogging } from './lib/sanitize-for-logging';
import { sortSites } from './lib/sort-sites';
import {
isSqliteInstallationOutdated,
isSqlLiteInstalled,
removeLegacySqliteIntegrationPlugin,
} from './lib/sqlite-versions';
import * as windowsHelpers from './lib/windows-helpers';
import { writeLogToFile, type LogLevel } from './logging';
import { popupMenu } from './menu';
import { SiteServer, createSiteWorkingDirectory } from './site-server';
import { DEFAULT_SITE_PATH, getServerFilesPath, getSiteThumbnailPath } from './storage/paths';
import { loadUserData, saveUserData } from './storage/user-data';
const TEMP_DIR = nodePath.join( app.getPath( 'temp' ), 'com.wordpress.studio' ) + nodePath.sep;
if ( ! fs.existsSync( TEMP_DIR ) ) {
fs.mkdirSync( TEMP_DIR );
}
async function sendThumbnailChangedEvent( event: IpcMainInvokeEvent, id: string ) {
if ( event.sender.isDestroyed() ) {
return;
}
const thumbnailData = await getThumbnailData( event, id );
const parentWindow = BrowserWindow.fromWebContents( event.sender );
if ( parentWindow && ! parentWindow.isDestroyed() ) {
parentWindow.webContents.send( 'thumbnail-changed', id, thumbnailData );
}
}
async function mergeSiteDetailsWithRunningDetails(
sites: SiteDetails[]
): Promise< SiteDetails[] > {
return sites.map( ( site ) => {
const server = SiteServer.get( site.id );
if ( server ) {
return server.details;
}
return site;
} );
}
export async function getSiteDetails( _event: IpcMainInvokeEvent ): Promise< SiteDetails[] > {
const userData = await loadUserData();
// This is probably one of the first times the user data is loaded. Take the opportunity
// to log for debugging purposes.
console.log( 'Loaded user data', sanitizeForLogging( userData ) );
const { sites } = userData;
// Ensure we have an instance of a server for each site we know about
for ( const site of sites ) {
if ( ! SiteServer.get( site.id ) && ! site.running ) {
SiteServer.create( site );
}
}
return mergeSiteDetailsWithRunningDetails( sites );
}
export async function getInstalledApps( _event: IpcMainInvokeEvent ): Promise< InstalledApps > {
return {
vscode: isInstalled( 'vscode' ),
phpstorm: isInstalled( 'phpstorm' ),
};
}
// Use sqlite database and db.php file in situ
async function setupSqliteIntegration( path: string ) {
await downloadSqliteIntegrationPlugin();
const wpContentPath = nodePath.join( path, 'wp-content' );
const databasePath = nodePath.join( wpContentPath, 'database' );
fs.mkdirSync( databasePath, { recursive: true } );
const dbPhpPath = nodePath.join( wpContentPath, 'db.php' );
fs.copyFileSync( nodePath.join( getServerFilesPath(), SQLITE_FILENAME, 'db.copy' ), dbPhpPath );
const dbCopyContent = fs.readFileSync( dbPhpPath ).toString();
fs.writeFileSync(
dbPhpPath,
dbCopyContent.replace(
"'{SQLITE_IMPLEMENTATION_FOLDER_PATH}'",
`realpath( __DIR__ . '/mu-plugins/${ SQLITE_FILENAME }' )`
)
);
const sqlitePluginPath = nodePath.join( wpContentPath, 'mu-plugins', SQLITE_FILENAME );
copySync( nodePath.join( getServerFilesPath(), SQLITE_FILENAME ), sqlitePluginPath );
await removeLegacySqliteIntegrationPlugin( sqlitePluginPath );
}
export async function createSite(
event: IpcMainInvokeEvent,
path: string,
siteName?: string
): Promise< SiteDetails[] > {
const userData = await loadUserData();
const forceSetupSqlite = false;
// We only recursively create the directory if the user has not selected a
// path from the dialog (and thus they use the "default" or suggested path).
if ( ! ( await pathExists( path ) ) && path.startsWith( DEFAULT_SITE_PATH ) ) {
fs.mkdirSync( path, { recursive: true } );
}
if ( ! ( await isEmptyDir( path ) ) && ! isWordPressDirectory( path ) ) {
// Form validation should've prevented a non-empty directory from being selected
throw new Error( 'The selected directory is not empty nor an existing WordPress site.' );
}
const allPaths = userData?.sites?.map( ( site ) => site.path ) || [];
if ( allPaths.includes( path ) ) {
return userData.sites;
}
if ( ( await pathExists( path ) ) && ( await isEmptyDir( path ) ) ) {
try {
await createSiteWorkingDirectory( path );
} catch ( error ) {
// If site creation failed, remove the generated files and re-throw the
// error so it can be handled by the caller.
shell.trashItem( path );
throw error;
}
}
const details = {
id: crypto.randomUUID(),
name: siteName || nodePath.basename( path ),
path,
adminPassword: createPassword(),
running: false,
} as const;
const server = SiteServer.create( details );
if ( isWordPressDirectory( path ) ) {
// If the directory contains a WordPress installation, and user wants to force SQLite
// integration, let's rename the wp-config.php file to allow WP Now to create a new one
// and initialize things properly.
if ( forceSetupSqlite && ( await pathExists( nodePath.join( path, 'wp-config.php' ) ) ) ) {
fs.renameSync(
nodePath.join( path, 'wp-config.php' ),
nodePath.join( path, 'wp-config-studio.php' )
);
}
if ( ! ( await pathExists( nodePath.join( path, 'wp-config.php' ) ) ) ) {
await setupSqliteIntegration( path );
}
}
const parentWindow = BrowserWindow.fromWebContents( event.sender );
if ( parentWindow && ! parentWindow.isDestroyed() && ! event.sender.isDestroyed() ) {
parentWindow.webContents.send( 'theme-details-updating', details.id );
}
await server.start();
if ( parentWindow && ! parentWindow.isDestroyed() && ! event.sender.isDestroyed() ) {
parentWindow.webContents.send(
'theme-details-changed',
details.id,
server.details.themeDetails
);
}
server.updateCachedThumbnail().then( () => sendThumbnailChangedEvent( event, details.id ) );
userData.sites.push( server.details );
sortSites( userData.sites );
await saveUserData( userData );
return mergeSiteDetailsWithRunningDetails( userData.sites );
}
export async function updateSite(
event: IpcMainInvokeEvent,
updatedSite: SiteDetails
): Promise< SiteDetails[] > {
const userData = await loadUserData();
const updatedSites = userData.sites.map( ( site ) =>
site.id === updatedSite.id ? updatedSite : site
);
userData.sites = updatedSites;
const server = SiteServer.get( updatedSite.id );
if ( server ) {
server.updateSiteDetails( updatedSite );
}
await saveUserData( userData );
return mergeSiteDetailsWithRunningDetails( userData.sites );
}
export async function startServer(
event: IpcMainInvokeEvent,
id: string
): Promise< SiteDetails | null > {
const server = SiteServer.get( id );
if ( ! server ) {
return null;
}
const SQLitePath = `${ server.details.path }/wp-content/mu-plugins/${ SQLITE_FILENAME }`;
const hasWpConfig = fs.existsSync( nodePath.join( server.details.path, 'wp-config.php' ) );
const sqliteInstalled = await isSqlLiteInstalled( SQLitePath );
const sqliteOutdated = sqliteInstalled && ( await isSqliteInstallationOutdated( SQLitePath ) );
if ( ( ! sqliteInstalled && ! hasWpConfig ) || sqliteOutdated ) {
await setupSqliteIntegration( server.details.path );
}
const parentWindow = BrowserWindow.fromWebContents( event.sender );
await server.start();
if ( parentWindow && ! parentWindow.isDestroyed() && ! event.sender.isDestroyed() ) {
parentWindow.webContents.send( 'theme-details-changed', id, server.details.themeDetails );
}
server.updateCachedThumbnail().then( () => sendThumbnailChangedEvent( event, id ) );
console.log( 'Server started', server.details );
await updateSite( event, server.details );
return server.details;
}
export async function stopServer(
event: IpcMainInvokeEvent,
id: string
): Promise< SiteDetails | null > {
const server = SiteServer.get( id );
if ( ! server ) {
return null;
}
await server.stop();
return server.details;
}
export interface FolderDialogResponse {
path: string;
name: string;
isEmpty: boolean;
isWordPress: boolean;
}
export async function showOpenFolderDialog(
event: IpcMainInvokeEvent,
title: string
): Promise< FolderDialogResponse | null > {
const parentWindow = BrowserWindow.fromWebContents( event.sender );
if ( ! parentWindow ) {
throw new Error(
`No window found for sender of showOpenFolderDialog message: ${ event.frameId }`
);
}
if ( process.env.E2E && process.env.E2E_OPEN_FOLDER_DIALOG ) {
// Playwright's filechooser event isn't working in our e2e tests.
// Use an environment variable to manually set which folder gets selected.
return {
path: process.env.E2E_OPEN_FOLDER_DIALOG,
name: nodePath.basename( process.env.E2E_OPEN_FOLDER_DIALOG ),
isEmpty: await isEmptyDir( process.env.E2E_OPEN_FOLDER_DIALOG ),
isWordPress: isWordPressDirectory( process.env.E2E_OPEN_FOLDER_DIALOG ),
};
}
const { canceled, filePaths } = await dialog.showOpenDialog( parentWindow, {
title,
defaultPath: DEFAULT_SITE_PATH,
properties: [
'openDirectory',
'createDirectory', // allow user to create new directories; macOS only
],
} );
if ( canceled ) {
return null;
}
return {
path: filePaths[ 0 ],
name: nodePath.basename( filePaths[ 0 ] ),
isEmpty: await isEmptyDir( filePaths[ 0 ] ),
isWordPress: isWordPressDirectory( filePaths[ 0 ] ),
};
}
export async function showUserSettings( event: IpcMainInvokeEvent ): Promise< void > {
const parentWindow = BrowserWindow.fromWebContents( event.sender );
if ( ! parentWindow ) {
throw new Error( `No window found for sender of showUserSettings message: ${ event.frameId }` );
}
parentWindow.webContents.send( 'user-settings' );
}
function zipWordPressDirectory( { source, zipPath }: { source: string; zipPath: string } ) {
return new Promise( ( resolve, reject ) => {
const output = fs.createWriteStream( zipPath );
const archive = archiver( 'zip', {
zlib: { level: 9 }, // Sets the compression level.
} );
output.on( 'close', function () {
resolve( archive );
} );
archive.on( 'error', function ( err: Error ) {
reject( err );
} );
archive.pipe( output );
// Archive site wp-content
archive.directory( `${ source }/wp-content`, 'wp-content' );
archive.file( `${ source }/wp-config.php`, { name: 'wp-config.php' } );
archive.finalize();
} );
}
export async function archiveSite( event: IpcMainInvokeEvent, id: string ) {
const site = SiteServer.get( id );
if ( ! site ) {
throw new Error( 'Site not found.' );
}
const sitePath = site.details.path;
const zipPath = `${ TEMP_DIR }site_${ id }.zip`;
await zipWordPressDirectory( {
source: sitePath,
zipPath,
} );
const stats = fs.statSync( zipPath );
const zipContent = fs.readFileSync( zipPath );
return { zipPath, zipContent, exceedsSizeLimit: stats.size > LIMIT_ARCHIVE_SIZE };
}
export function removeTemporalFile( event: IpcMainInvokeEvent, path: string ) {
if ( ! path.includes( TEMP_DIR ) ) {
throw new Error( 'The given path is not a temporal file' );
}
try {
fs.unlinkSync( path );
} catch ( error ) {
if ( isErrnoException( error ) && error.code === 'ENOENT' ) {
// Silently ignore if the temporal file doesn't exist
Sentry.captureException( error );
}
}
}
export async function deleteSite( event: IpcMainInvokeEvent, id: string, deleteFiles = false ) {
const server = SiteServer.get( id );
console.log( 'Deleting site', id );
if ( ! server ) {
throw new Error( 'Site not found.' );
}
const userData = await loadUserData();
await server.delete();
try {
// Move files to trash
if ( deleteFiles ) {
await shell.trashItem( server.details.path );
}
} catch ( error ) {
/* We want to exit gracefully if the there is an error deleting the site files */
Sentry.captureException( error );
}
const newSites = userData.sites.filter( ( site ) => site.id !== id );
const newUserData = { ...userData, sites: newSites };
await saveUserData( newUserData );
return mergeSiteDetailsWithRunningDetails( newSites );
}
export function logRendererMessage(
event: IpcMainInvokeEvent,
level: LogLevel,
...args: unknown[]
): void {
// 4 characters long so it aligns with the main process logs
const processId = `ren${ event.sender.id }`;
writeLogToFile( level, processId, ...args );
}
export async function authenticate( _event: IpcMainInvokeEvent ): Promise< void > {
return oauthClient.authenticate();
}
export async function getAuthenticationToken(
_event: IpcMainInvokeEvent
): Promise< oauthClient.StoredToken | null > {
return oauthClient.getAuthenticationToken();
}
export async function isAuthenticated() {
return oauthClient.isAuthenticated();
}
export async function clearAuthenticationToken() {
return oauthClient.clearAuthenticationToken();
}
export async function saveSnapshotsToStorage( event: IpcMainInvokeEvent, snapshots: Snapshot[] ) {
const userData = await loadUserData();
await saveUserData( {
...userData,
snapshots: snapshots.map( ( { isLoading, ...restSnapshots } ) => restSnapshots ),
} );
}
export async function getSnapshots( _event: IpcMainInvokeEvent ): Promise< Snapshot[] > {
const userData = await loadUserData();
const { snapshots = [] } = userData;
return snapshots;
}
export async function openSiteURL( event: IpcMainInvokeEvent, id: string, relativeURL = '' ) {
const site = SiteServer.get( id );
if ( ! site ) {
throw new Error( 'Site not found.' );
}
shell.openExternal( site.server?.url + relativeURL );
}
export async function openURL( event: IpcMainInvokeEvent, url: string ) {
return shell.openExternal( url );
}
export async function copyText( event: IpcMainInvokeEvent, text: string ) {
return clipboard.writeText( text );
}
export async function getAppGlobals( _event: IpcMainInvokeEvent ): Promise< AppGlobals > {
const locale = getSupportedLocale();
const localeData = getLocaleData( locale );
return {
platform: process.platform,
locale,
localeData,
appName: app.name,
arm64Translation: app.runningUnderARM64Translation,
assistantEnabled: process.env.STUDIO_AI === 'true',
};
}
export async function getWpVersion( _event: IpcMainInvokeEvent, id: string ) {
const server = SiteServer.get( id );
if ( ! server ) {
return '-';
}
const wordPressPath = server.details.path;
let versionFileContent = '';
try {
versionFileContent = fs.readFileSync(
nodePath.join( wordPressPath, 'wp-includes', 'version.php' ),
'utf8'
);
} catch ( err ) {
return '-';
}
const matches = versionFileContent.match( /\$wp_version\s*=\s*'([0-9a-zA-Z.-]+)'/ );
return matches?.[ 1 ] || '-';
}
export async function generateProposedSitePath(
_event: IpcMainInvokeEvent,
siteName: string
): Promise< FolderDialogResponse > {
const path = nodePath.join( DEFAULT_SITE_PATH, sanitizeFolderName( siteName ) );
try {
return {
path,
name: siteName,
isEmpty: await isEmptyDir( path ),
isWordPress: isWordPressDirectory( path ),
};
} catch ( err ) {
if ( isErrnoException( err ) && err.code === 'ENOENT' ) {
return {
path,
name: siteName,
isEmpty: true,
isWordPress: false,
};
}
throw err;
}
}
export async function openLocalPath( _event: IpcMainInvokeEvent, path: string ) {
shell.openPath( path );
}
export async function getThemeDetails( event: IpcMainInvokeEvent, id: string ) {
const server = SiteServer.get( id );
if ( ! server ) {
throw new Error( 'Site not found.' );
}
if ( ! server.details.running || ! server.server ) {
return null;
}
const themeDetails = await phpGetThemeDetails( server.server );
const parentWindow = BrowserWindow.fromWebContents( event.sender );
if ( themeDetails?.path && themeDetails.path !== server.details.themeDetails?.path ) {
if ( parentWindow && ! parentWindow.isDestroyed() && ! event.sender.isDestroyed() ) {
parentWindow.webContents.send( 'theme-details-updating', id );
}
const updatedSite = {
...server.details,
themeDetails,
};
if ( parentWindow && ! parentWindow.isDestroyed() && ! event.sender.isDestroyed() ) {
parentWindow.webContents.send( 'theme-details-changed', id, themeDetails );
}
server.updateCachedThumbnail().then( () => sendThumbnailChangedEvent( event, id ) );
server.details.themeDetails = themeDetails;
await updateSite( event, updatedSite );
}
return themeDetails;
}
export async function getOnboardingData( _event: IpcMainInvokeEvent ): Promise< boolean > {
const userData = await loadUserData();
const { onboardingCompleted = false } = userData;
return onboardingCompleted;
}
export async function saveOnboarding(
_event: IpcMainInvokeEvent,
onboardingCompleted: boolean
): Promise< void > {
const userData = await loadUserData();
await saveUserData( {
...userData,
onboardingCompleted,
} );
}
export async function executeWPCLiInline(
_event: IpcMainInvokeEvent,
{ projectPath, args }: { projectPath: string; args: string[] }
) {
const { stdout, stderr } = await executeWPCli( projectPath, args );
return { stdout, stderr };
}
export async function getThumbnailData( _event: IpcMainInvokeEvent, id: string ) {
const path = getSiteThumbnailPath( id );
return getImageData( path );
}
export function openTerminalAtPath( _event: IpcMainInvokeEvent, targetPath: string ) {
return new Promise< void >( ( resolve, reject ) => {
const platform = process.platform;
let command: string;
if ( platform === 'win32' ) {
// Windows
command = `start cmd /K "cd /d ${ targetPath }"`;
} else if ( platform === 'darwin' ) {
// macOS
command = `open -a Terminal "${ targetPath }"`;
} else if ( platform === 'linux' ) {
// Linux
command = `gnome-terminal --working-directory=${ targetPath }`;
} else {
console.error( 'Unsupported platform:', platform );
return;
}
exec( command, ( error, _stdout, _stderr ) => {
if ( error ) {
reject( error );
return;
}
resolve();
} );
} );
}
export async function showMessageBox(
event: IpcMainInvokeEvent,
options: Electron.MessageBoxOptions
) {
const parentWindow = BrowserWindow.fromWebContents( event.sender );
if ( parentWindow && ! parentWindow.isDestroyed() && ! event.sender.isDestroyed() ) {
return dialog.showMessageBox( parentWindow, options );
}
return dialog.showMessageBox( options );
}
export async function showNotification(
_event: IpcMainInvokeEvent,
options: Electron.NotificationConstructorOptions
) {
new Notification( options ).show();
}
export function popupAppMenu( _event: IpcMainInvokeEvent ) {
popupMenu();
}
export async function promptWindowsSpeedUpSites(
_event: IpcMainInvokeEvent,
{ skipIfAlreadyPrompted }: { skipIfAlreadyPrompted: boolean }
) {
await windowsHelpers.promptWindowsSpeedUpSites( { skipIfAlreadyPrompted } );
}