Skip to content

Commit

Permalink
chore: convert to esm, add window.plebbitRpcAuthKey, add defaultMedia…
Browse files Browse the repository at this point in the history
…IpfsGatewayUrl
  • Loading branch information
plebeius-eth committed Jun 20, 2024
1 parent 0ea1364 commit bc2d201
Show file tree
Hide file tree
Showing 13 changed files with 399 additions and 666 deletions.
15 changes: 8 additions & 7 deletions electron/after-all-artifact-build.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
// hook that runs after electron-build

const fs = require('fs-extra');
const path = require('path');
const { execSync } = require('child_process');
const rootPath = path.resolve(__dirname, '..');
import fs from 'fs-extra';
import path from 'path';
import { execSync } from 'child_process';
import packageJson from '../package.json' assert { type: 'json' };
import { fileURLToPath } from 'url';
const rootPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const distFolderPath = path.resolve(rootPath, 'dist');

const addPortableToPortableExecutableFileName = () => {
Expand All @@ -21,9 +23,8 @@ const createHtmlArchive = () => {
if (process.platform !== 'linux') {
return;
}
const { version } = require('../package.json');
const zipBinPath = path.resolve(rootPath, 'node_modules', '7zip-bin', 'linux', 'x64', '7za');
const plebchanHtmlFolderName = `plebchan-html-${version}`;
const plebchanHtmlFolderName = `plebchan-html-${packageJson.version}`;
const outputFile = path.resolve(distFolderPath, `${plebchanHtmlFolderName}.zip`);
const inputFolder = path.resolve(rootPath, 'build');
try {
Expand All @@ -37,7 +38,7 @@ const createHtmlArchive = () => {
}
};

exports.default = async (buildResult) => {
export default async (buildResult) => {
addPortableToPortableExecutableFileName();
createHtmlArchive();
};
19 changes: 9 additions & 10 deletions electron/before-pack.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
// download the ipfs binaries before building the electron clients

const fs = require('fs-extra');
const ProgressBar = require('progress');
const https = require('https');
const decompress = require('decompress');
const path = require('path');
const ipfsClientsPath = path.join(__dirname, '..', 'bin');
import fs from 'fs-extra';
import ProgressBar from 'progress';
import https from 'https';
import decompress from 'decompress';
import path from 'path';
import { fileURLToPath } from 'url';
const ipfsClientsPath = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'bin');
const ipfsClientWindowsPath = path.join(ipfsClientsPath, 'win');
const ipfsClientMacPath = path.join(ipfsClientsPath, 'mac');
const ipfsClientLinuxPath = path.join(ipfsClientsPath, 'linux');
Expand Down Expand Up @@ -98,14 +99,12 @@ const downloadAndExtract = async (url, destinationPath) => {
fs.removeSync(dowloadPath);
};

const downloadIpfsClients = async () => {
export const downloadIpfsClients = async () => {
await downloadAndExtract(ipfsClientWindowsUrl, ipfsClientWindowsPath);
await downloadAndExtract(ipfsClientMacUrl, ipfsClientMacPath);
await downloadAndExtract(ipfsClientLinuxPUrl, ipfsClientLinuxPath);
};

exports.downloadIpfsClients = downloadIpfsClients;

exports.default = async (context) => {
export default async (context) => {
await downloadIpfsClients();
};
2 changes: 1 addition & 1 deletion electron/download-ipfs.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
const downloadIpfsClients = require('./before-pack').downloadIpfsClients;
import { downloadIpfsClients } from './before-pack.js';
downloadIpfsClients();
9 changes: 5 additions & 4 deletions electron/log.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
// require this file to log to file in case there's a crash

const envPaths = require('env-paths').default('plebbit', { suffix: false });
const util = require('util');
const fs = require('fs-extra');
const path = require('path');
import util from 'util';
import fs from 'fs-extra';
import path from 'path';
import EnvPaths from 'env-paths';
const envPaths = EnvPaths('plebbit', { suffix: false });

// previous version created a file instead of folder
// we should remove this at some point
Expand Down
35 changes: 22 additions & 13 deletions electron/main.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
require('./log');
const { app, BrowserWindow, Menu, MenuItem, Tray, screen: electronScreen, shell, dialog } = require('electron');
const isDev = require('electron-is-dev');
const path = require('path');
const startIpfs = require('./start-ipfs');
const startPlebbitRpcServer = require('./start-plebbit-rpc');
const { URL } = require('node:url');
import './log.js';
import { app, BrowserWindow, Menu, MenuItem, Tray, screen as electronScreen, shell, dialog, nativeTheme, ipcMain } from 'electron';
import isDev from 'electron-is-dev';
import fs from 'fs';
import path from 'path';
import EnvPaths from 'env-paths';
import startIpfs from './start-ipfs.js';
import './start-plebbit-rpc.js';
import { URL, fileURLToPath } from 'node:url';
import contextMenu from 'electron-context-menu';
import packageJson from '../package.json' assert { type: 'json' };
const dirname = path.join(path.dirname(fileURLToPath(import.meta.url)));

let startIpfsError;
startIpfs.onError = (error) => {
Expand All @@ -16,17 +21,21 @@ startIpfs.onError = (error) => {
}
};

// send plebbit rpc auth key to renderer
const plebbitDataPath = !isDev ? EnvPaths('plebbit', { suffix: false }).data : path.join(dirname, '..', '.plebbit');
const plebbitRpcAuthKey = fs.readFileSync(path.join(plebbitDataPath, 'auth-key'), 'utf8');
ipcMain.on('get-plebbit-rpc-auth-key', (event) => event.reply('plebbit-rpc-auth-key', plebbitRpcAuthKey));

// use common user agent instead of electron so img, video, audio, iframe elements don't get blocked
// https://www.whatismybrowser.com/guides/the-latest-version/chrome
// https://www.whatismybrowser.com/guides/the-latest-user-agent/chrome
// NOTE: eventually should probably fake sec-ch-ua header as well
let fakeUserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36';
if (process.platform === 'darwin') fakeUserAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 13_5_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36';
if (process.platform === 'linux') fakeUserAgent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36';
const realUserAgent = `plebchan/${require('../package.json').version}`;
const realUserAgent = `plebchan/${packageJson.version}`;

// add right click menu
const contextMenu = require('electron-context-menu');
contextMenu({
// prepend custom buttons to top
prepend: (defaultActions, parameters, browserWindow) => [
Expand Down Expand Up @@ -63,13 +72,13 @@ const createMainWindow = () => {
width: 1000,
height: 600,
show: false,
backgroundColor: '#fffee',
backgroundColor: nativeTheme.shouldUseDarkColors ? '#000000' : '#ffffff',
webPreferences: {
webSecurity: true, // must be true or iframe embeds like youtube can do remote code execution
nodeIntegration: false,
contextIsolation: true,
devTools: true, // TODO: change to isDev when no bugs left
preload: path.join(__dirname, 'preload.js'),
preload: path.join(dirname, 'preload.js'),
},
});

Expand Down Expand Up @@ -115,7 +124,7 @@ const createMainWindow = () => {
callback({ responseHeaders: details.responseHeaders });
});

const startURL = isDev ? 'http://localhost:3000' : `file://${path.join(__dirname, '../build/index.html')}`;
const startURL = isDev ? 'http://localhost:3000' : `file://${path.join(dirname, '../build/index.html')}`;

mainWindow.loadURL(startURL);

Expand Down Expand Up @@ -219,7 +228,7 @@ const createMainWindow = () => {

if (process.platform !== 'darwin') {
// tray
const trayIconPath = path.join(__dirname, '..', isDev ? 'public' : 'build', 'electron-tray-icon.png');
const trayIconPath = path.join(dirname, '..', isDev ? 'public' : 'build', 'electron-tray-icon.png');
const tray = new Tray(trayIconPath);
tray.setToolTip('plebchan');
const trayMenu = Menu.buildFromTemplate([
Expand Down
8 changes: 5 additions & 3 deletions electron/preload.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { contextBridge } = require('electron');
const { contextBridge, ipcRenderer } = require('electron');

// dev uses http://localhost, prod uses file://...index.html
const isDev = window.location.protocol === 'http:';
Expand All @@ -8,9 +8,11 @@ const defaultPlebbitOptions = {
};

contextBridge.exposeInMainWorld('defaultPlebbitOptions', defaultPlebbitOptions);
contextBridge.exposeInMainWorld('defaultMediaIpfsGatewayUrl', 'http://localhost:6473');

// expose a flag to indicate that we are running in electron
contextBridge.exposeInMainWorld('electron', { isElectron: true });
// receive plebbit rpc auth key from main
ipcRenderer.on('plebbit-rpc-auth-key', (event, plebbitRpcAuthKey) => contextBridge.exposeInMainWorld('plebbitRpcAuthKey', plebbitRpcAuthKey));
ipcRenderer.send('get-plebbit-rpc-auth-key');

// uncomment for logs
// localStorage.debug = 'plebbit-js:*,plebbit-react-hooks:*,plebchan:*'
6 changes: 3 additions & 3 deletions electron/proxy-server.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// use this proxy server to debug ipfs api requests made by electron

const http = require('http');
const httpProxy = require('http-proxy');
import http from 'http';
import httpProxy from 'http-proxy';

// start proxy
const proxy = httpProxy.createProxyServer({});
Expand Down Expand Up @@ -45,4 +45,4 @@ const start = ({ proxyPort, targetPort } = {}) => {
console.log(`proxy server listening on port ${proxyPort}`);
};

module.exports = { start };
export default { start };
30 changes: 19 additions & 11 deletions electron/start-ipfs.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
const isDev = require('electron-is-dev');
const path = require('path');
const { spawn } = require('child_process');
const fs = require('fs-extra');
const envPaths = require('env-paths').default('plebbit', { suffix: false });
const ps = require('node:process');
const proxyServer = require('./proxy-server');
const tcpPortUsed = require('tcp-port-used');
import isDev from 'electron-is-dev';
import path from 'path';
import { spawn } from 'child_process';
import fs from 'fs-extra';
import ps from 'node:process';
import proxyServer from './proxy-server.js';
import tcpPortUsed from 'tcp-port-used';
import EnvPaths from 'env-paths';
import { fileURLToPath } from 'url';
const dirname = path.join(path.dirname(fileURLToPath(import.meta.url)));
const envPaths = EnvPaths('plebbit', { suffix: false });

// use this custom function instead of spawnSync for better logging
// also spawnSync might have been causing crash on start on windows
Expand Down Expand Up @@ -37,8 +40,8 @@ const startIpfs = async () => {
if (process.platform === 'darwin') {
binFolderName = 'mac';
}
ipfsPath = path.join(__dirname, '..', 'bin', binFolderName, ipfsFileName);
ipfsDataPath = path.join(__dirname, '..', '.plebbit', 'ipfs');
ipfsPath = path.join(dirname, '..', 'bin', binFolderName, ipfsFileName);
ipfsDataPath = path.join(dirname, '..', '.plebbit', 'ipfs');
}

if (!fs.existsSync(ipfsPath)) {
Expand Down Expand Up @@ -104,6 +107,8 @@ const startIpfs = async () => {
});
};

const DefaultExport = {};

let pendingStart = false;
const start = async () => {
if (pendingStart) {
Expand All @@ -120,7 +125,7 @@ const start = async () => {
console.log('failed starting ipfs', e);
try {
// try to run exported onError callback, can be undefined
module.exports.onError(e)?.catch?.(console.log);
DefaultExport.onError(e)?.catch?.(console.log);
} catch (e) {}
}
pendingStart = false;
Expand All @@ -132,3 +137,6 @@ start();
setInterval(() => {
start();
}, 1000);

DefaultExport.start = start;
export default DefaultExport;
25 changes: 12 additions & 13 deletions electron/start-plebbit-rpc.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
const tcpPortUsed = require('tcp-port-used');
const { PlebbitWsServer } = require('@plebbit/plebbit-js/rpc');
const path = require('path');
const envPaths = require('env-paths').default('plebbit', { suffix: false });
const { randomBytes } = require('crypto');
const fs = require('fs-extra');

let isDev = true;
try {
isDev = require('electron-is-dev');
} catch (e) {}
import tcpPortUsed from 'tcp-port-used';
import EnvPaths from 'env-paths';
import { randomBytes } from 'crypto';
import fs from 'fs-extra';
import PlebbitRpc from '@plebbit/plebbit-js/dist/node/rpc/src/index.js';
import path from 'path';
import { fileURLToPath } from 'url';
import isDev from 'electron-is-dev';
const dirname = path.join(path.dirname(fileURLToPath(import.meta.url)));
const envPaths = EnvPaths('plebbit', { suffix: false });

// PLEB, always run plebbit rpc on this port so all clients can use it
const port = 9138;
const defaultPlebbitOptions = {
// find the user's OS data path
dataPath: !isDev ? envPaths.data : path.join(__dirname, '..', '.plebbit'),
dataPath: !isDev ? envPaths.data : path.join(dirname, '..', '.plebbit'),
ipfsHttpClientsOptions: ['http://localhost:5001/api/v0'],
// TODO: having to define pubsubHttpClientsOptions and ipfsHttpClientsOptions is a bug with plebbit-js
pubsubHttpClientsOptions: ['http://localhost:5001/api/v0'],
Expand Down Expand Up @@ -42,7 +41,7 @@ const start = async () => {
if (started) {
return;
}
const plebbitWebSocketServer = await PlebbitWsServer({ port, plebbitOptions: defaultPlebbitOptions, authKey: plebbitRpcAuthKey });
const plebbitWebSocketServer = await PlebbitRpc.PlebbitWsServer({ port, plebbitOptions: defaultPlebbitOptions, authKey: plebbitRpcAuthKey });

console.log(`plebbit rpc: listening on ws://localhost:${port} (local connections only)`);
console.log(`plebbit rpc: listening on ws://localhost:${port}/${plebbitRpcAuthKey} (secret auth key for remote connections)`);
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"name": "plebchan",
"version": "0.2.0",
"description": "A GUI for plebbit similar to 4chan",
"type": "module",
"author": "plebeius.eth",
"private": true,
"dependencies": {
Expand Down Expand Up @@ -93,8 +94,8 @@
"cross-env": "7.0.3",
"cz-conventional-changelog": "3.3.0",
"decompress": "4.2.1",
"electron": "19.1.8",
"electron-builder": "23.0.9",
"electron": "28.2.3",
"electron-builder": "24.13.2",
"husky": "4.3.8",
"lint-staged": "12.3.8",
"wait-on": "7.0.1"
Expand Down
File renamed without changes.
8 changes: 5 additions & 3 deletions scripts/release-body.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const {execSync} = require('child_process')
const path = require('path')
const conventionalChangelog = path.join('node_modules', '.bin', 'conventional-changelog')
import {execSync} from 'child_process'
import path from 'path'
import {fileURLToPath} from 'url'
const dirname = path.join(path.dirname(fileURLToPath(import.meta.url)))
const conventionalChangelog = path.join(dirname, '..', 'node_modules', '.bin', 'conventional-changelog')

// sometimes release-count 1 is empty
let releaseChangelog =
Expand Down
Loading

0 comments on commit bc2d201

Please sign in to comment.