chore: convert to esm, add window.plebbitRpcAuthKey, add defaultMediaIpfsGatewayUrl

This commit is contained in:
Tom (plebeius.eth)
2024-06-20 15:35:28 +02:00
parent 0ea136421d
commit bc2d201d80
13 changed files with 398 additions and 665 deletions
+8 -7
View File
@@ -1,9 +1,11 @@
// hook that runs after electron-build // hook that runs after electron-build
const fs = require('fs-extra'); import fs from 'fs-extra';
const path = require('path'); import path from 'path';
const { execSync } = require('child_process'); import { execSync } from 'child_process';
const rootPath = path.resolve(__dirname, '..'); 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 distFolderPath = path.resolve(rootPath, 'dist');
const addPortableToPortableExecutableFileName = () => { const addPortableToPortableExecutableFileName = () => {
@@ -21,9 +23,8 @@ const createHtmlArchive = () => {
if (process.platform !== 'linux') { if (process.platform !== 'linux') {
return; return;
} }
const { version } = require('../package.json');
const zipBinPath = path.resolve(rootPath, 'node_modules', '7zip-bin', 'linux', 'x64', '7za'); 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 outputFile = path.resolve(distFolderPath, `${plebchanHtmlFolderName}.zip`);
const inputFolder = path.resolve(rootPath, 'build'); const inputFolder = path.resolve(rootPath, 'build');
try { try {
@@ -37,7 +38,7 @@ const createHtmlArchive = () => {
} }
}; };
exports.default = async (buildResult) => { export default async (buildResult) => {
addPortableToPortableExecutableFileName(); addPortableToPortableExecutableFileName();
createHtmlArchive(); createHtmlArchive();
}; };
+9 -10
View File
@@ -1,11 +1,12 @@
// download the ipfs binaries before building the electron clients // download the ipfs binaries before building the electron clients
const fs = require('fs-extra'); import fs from 'fs-extra';
const ProgressBar = require('progress'); import ProgressBar from 'progress';
const https = require('https'); import https from 'https';
const decompress = require('decompress'); import decompress from 'decompress';
const path = require('path'); import path from 'path';
const ipfsClientsPath = path.join(__dirname, '..', 'bin'); import { fileURLToPath } from 'url';
const ipfsClientsPath = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'bin');
const ipfsClientWindowsPath = path.join(ipfsClientsPath, 'win'); const ipfsClientWindowsPath = path.join(ipfsClientsPath, 'win');
const ipfsClientMacPath = path.join(ipfsClientsPath, 'mac'); const ipfsClientMacPath = path.join(ipfsClientsPath, 'mac');
const ipfsClientLinuxPath = path.join(ipfsClientsPath, 'linux'); const ipfsClientLinuxPath = path.join(ipfsClientsPath, 'linux');
@@ -98,14 +99,12 @@ const downloadAndExtract = async (url, destinationPath) => {
fs.removeSync(dowloadPath); fs.removeSync(dowloadPath);
}; };
const downloadIpfsClients = async () => { export const downloadIpfsClients = async () => {
await downloadAndExtract(ipfsClientWindowsUrl, ipfsClientWindowsPath); await downloadAndExtract(ipfsClientWindowsUrl, ipfsClientWindowsPath);
await downloadAndExtract(ipfsClientMacUrl, ipfsClientMacPath); await downloadAndExtract(ipfsClientMacUrl, ipfsClientMacPath);
await downloadAndExtract(ipfsClientLinuxPUrl, ipfsClientLinuxPath); await downloadAndExtract(ipfsClientLinuxPUrl, ipfsClientLinuxPath);
}; };
exports.downloadIpfsClients = downloadIpfsClients; export default async (context) => {
exports.default = async (context) => {
await downloadIpfsClients(); await downloadIpfsClients();
}; };
+1 -1
View File
@@ -1,2 +1,2 @@
const downloadIpfsClients = require('./before-pack').downloadIpfsClients; import { downloadIpfsClients } from './before-pack.js';
downloadIpfsClients(); downloadIpfsClients();
+5 -4
View File
@@ -1,9 +1,10 @@
// require this file to log to file in case there's a crash // require this file to log to file in case there's a crash
const envPaths = require('env-paths').default('plebbit', { suffix: false }); import util from 'util';
const util = require('util'); import fs from 'fs-extra';
const fs = require('fs-extra'); import path from 'path';
const path = require('path'); import EnvPaths from 'env-paths';
const envPaths = EnvPaths('plebbit', { suffix: false });
// previous version created a file instead of folder // previous version created a file instead of folder
// we should remove this at some point // we should remove this at some point
+22 -13
View File
@@ -1,10 +1,15 @@
require('./log'); import './log.js';
const { app, BrowserWindow, Menu, MenuItem, Tray, screen: electronScreen, shell, dialog } = require('electron'); import { app, BrowserWindow, Menu, MenuItem, Tray, screen as electronScreen, shell, dialog, nativeTheme, ipcMain } from 'electron';
const isDev = require('electron-is-dev'); import isDev from 'electron-is-dev';
const path = require('path'); import fs from 'fs';
const startIpfs = require('./start-ipfs'); import path from 'path';
const startPlebbitRpcServer = require('./start-plebbit-rpc'); import EnvPaths from 'env-paths';
const { URL } = require('node:url'); 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; let startIpfsError;
startIpfs.onError = (error) => { startIpfs.onError = (error) => {
@@ -16,6 +21,11 @@ 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 // 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-version/chrome
// https://www.whatismybrowser.com/guides/the-latest-user-agent/chrome // https://www.whatismybrowser.com/guides/the-latest-user-agent/chrome
@@ -23,10 +33,9 @@ startIpfs.onError = (error) => {
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'; 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 === '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'; 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 // add right click menu
const contextMenu = require('electron-context-menu');
contextMenu({ contextMenu({
// prepend custom buttons to top // prepend custom buttons to top
prepend: (defaultActions, parameters, browserWindow) => [ prepend: (defaultActions, parameters, browserWindow) => [
@@ -63,13 +72,13 @@ const createMainWindow = () => {
width: 1000, width: 1000,
height: 600, height: 600,
show: false, show: false,
backgroundColor: '#fffee', backgroundColor: nativeTheme.shouldUseDarkColors ? '#000000' : '#ffffff',
webPreferences: { webPreferences: {
webSecurity: true, // must be true or iframe embeds like youtube can do remote code execution webSecurity: true, // must be true or iframe embeds like youtube can do remote code execution
nodeIntegration: false, nodeIntegration: false,
contextIsolation: true, contextIsolation: true,
devTools: true, // TODO: change to isDev when no bugs left devTools: true, // TODO: change to isDev when no bugs left
preload: path.join(__dirname, 'preload.js'), preload: path.join(dirname, 'preload.js'),
}, },
}); });
@@ -115,7 +124,7 @@ const createMainWindow = () => {
callback({ responseHeaders: details.responseHeaders }); 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); mainWindow.loadURL(startURL);
@@ -219,7 +228,7 @@ const createMainWindow = () => {
if (process.platform !== 'darwin') { if (process.platform !== 'darwin') {
// tray // 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); const tray = new Tray(trayIconPath);
tray.setToolTip('plebchan'); tray.setToolTip('plebchan');
const trayMenu = Menu.buildFromTemplate([ const trayMenu = Menu.buildFromTemplate([
+5 -3
View File
@@ -1,4 +1,4 @@
const { contextBridge } = require('electron'); const { contextBridge, ipcRenderer } = require('electron');
// dev uses http://localhost, prod uses file://...index.html // dev uses http://localhost, prod uses file://...index.html
const isDev = window.location.protocol === 'http:'; const isDev = window.location.protocol === 'http:';
@@ -8,9 +8,11 @@ const defaultPlebbitOptions = {
}; };
contextBridge.exposeInMainWorld('defaultPlebbitOptions', defaultPlebbitOptions); contextBridge.exposeInMainWorld('defaultPlebbitOptions', defaultPlebbitOptions);
contextBridge.exposeInMainWorld('defaultMediaIpfsGatewayUrl', 'http://localhost:6473');
// expose a flag to indicate that we are running in electron // receive plebbit rpc auth key from main
contextBridge.exposeInMainWorld('electron', { isElectron: true }); ipcRenderer.on('plebbit-rpc-auth-key', (event, plebbitRpcAuthKey) => contextBridge.exposeInMainWorld('plebbitRpcAuthKey', plebbitRpcAuthKey));
ipcRenderer.send('get-plebbit-rpc-auth-key');
// uncomment for logs // uncomment for logs
// localStorage.debug = 'plebbit-js:*,plebbit-react-hooks:*,plebchan:*' // localStorage.debug = 'plebbit-js:*,plebbit-react-hooks:*,plebchan:*'
+3 -3
View File
@@ -1,7 +1,7 @@
// use this proxy server to debug ipfs api requests made by electron // use this proxy server to debug ipfs api requests made by electron
const http = require('http'); import http from 'http';
const httpProxy = require('http-proxy'); import httpProxy from 'http-proxy';
// start proxy // start proxy
const proxy = httpProxy.createProxyServer({}); const proxy = httpProxy.createProxyServer({});
@@ -45,4 +45,4 @@ const start = ({ proxyPort, targetPort } = {}) => {
console.log(`proxy server listening on port ${proxyPort}`); console.log(`proxy server listening on port ${proxyPort}`);
}; };
module.exports = { start }; export default { start };
+19 -11
View File
@@ -1,11 +1,14 @@
const isDev = require('electron-is-dev'); import isDev from 'electron-is-dev';
const path = require('path'); import path from 'path';
const { spawn } = require('child_process'); import { spawn } from 'child_process';
const fs = require('fs-extra'); import fs from 'fs-extra';
const envPaths = require('env-paths').default('plebbit', { suffix: false }); import ps from 'node:process';
const ps = require('node:process'); import proxyServer from './proxy-server.js';
const proxyServer = require('./proxy-server'); import tcpPortUsed from 'tcp-port-used';
const tcpPortUsed = require('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 // use this custom function instead of spawnSync for better logging
// also spawnSync might have been causing crash on start on windows // also spawnSync might have been causing crash on start on windows
@@ -37,8 +40,8 @@ const startIpfs = async () => {
if (process.platform === 'darwin') { if (process.platform === 'darwin') {
binFolderName = 'mac'; binFolderName = 'mac';
} }
ipfsPath = path.join(__dirname, '..', 'bin', binFolderName, ipfsFileName); ipfsPath = path.join(dirname, '..', 'bin', binFolderName, ipfsFileName);
ipfsDataPath = path.join(__dirname, '..', '.plebbit', 'ipfs'); ipfsDataPath = path.join(dirname, '..', '.plebbit', 'ipfs');
} }
if (!fs.existsSync(ipfsPath)) { if (!fs.existsSync(ipfsPath)) {
@@ -104,6 +107,8 @@ const startIpfs = async () => {
}); });
}; };
const DefaultExport = {};
let pendingStart = false; let pendingStart = false;
const start = async () => { const start = async () => {
if (pendingStart) { if (pendingStart) {
@@ -120,7 +125,7 @@ const start = async () => {
console.log('failed starting ipfs', e); console.log('failed starting ipfs', e);
try { try {
// try to run exported onError callback, can be undefined // try to run exported onError callback, can be undefined
module.exports.onError(e)?.catch?.(console.log); DefaultExport.onError(e)?.catch?.(console.log);
} catch (e) {} } catch (e) {}
} }
pendingStart = false; pendingStart = false;
@@ -132,3 +137,6 @@ start();
setInterval(() => { setInterval(() => {
start(); start();
}, 1000); }, 1000);
DefaultExport.start = start;
export default DefaultExport;
+12 -13
View File
@@ -1,20 +1,19 @@
const tcpPortUsed = require('tcp-port-used'); import tcpPortUsed from 'tcp-port-used';
const { PlebbitWsServer } = require('@plebbit/plebbit-js/rpc'); import EnvPaths from 'env-paths';
const path = require('path'); import { randomBytes } from 'crypto';
const envPaths = require('env-paths').default('plebbit', { suffix: false }); import fs from 'fs-extra';
const { randomBytes } = require('crypto'); import PlebbitRpc from '@plebbit/plebbit-js/dist/node/rpc/src/index.js';
const fs = require('fs-extra'); import path from 'path';
import { fileURLToPath } from 'url';
let isDev = true; import isDev from 'electron-is-dev';
try { const dirname = path.join(path.dirname(fileURLToPath(import.meta.url)));
isDev = require('electron-is-dev'); const envPaths = EnvPaths('plebbit', { suffix: false });
} catch (e) {}
// PLEB, always run plebbit rpc on this port so all clients can use it // PLEB, always run plebbit rpc on this port so all clients can use it
const port = 9138; const port = 9138;
const defaultPlebbitOptions = { const defaultPlebbitOptions = {
// find the user's OS data path // 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'], ipfsHttpClientsOptions: ['http://localhost:5001/api/v0'],
// TODO: having to define pubsubHttpClientsOptions and ipfsHttpClientsOptions is a bug with plebbit-js // TODO: having to define pubsubHttpClientsOptions and ipfsHttpClientsOptions is a bug with plebbit-js
pubsubHttpClientsOptions: ['http://localhost:5001/api/v0'], pubsubHttpClientsOptions: ['http://localhost:5001/api/v0'],
@@ -42,7 +41,7 @@ const start = async () => {
if (started) { if (started) {
return; 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} (local connections only)`);
console.log(`plebbit rpc: listening on ws://localhost:${port}/${plebbitRpcAuthKey} (secret auth key for remote connections)`); console.log(`plebbit rpc: listening on ws://localhost:${port}/${plebbitRpcAuthKey} (secret auth key for remote connections)`);
+3 -2
View File
@@ -2,6 +2,7 @@
"name": "plebchan", "name": "plebchan",
"version": "0.2.0", "version": "0.2.0",
"description": "A GUI for plebbit similar to 4chan", "description": "A GUI for plebbit similar to 4chan",
"type": "module",
"author": "plebeius.eth", "author": "plebeius.eth",
"private": true, "private": true,
"dependencies": { "dependencies": {
@@ -93,8 +94,8 @@
"cross-env": "7.0.3", "cross-env": "7.0.3",
"cz-conventional-changelog": "3.3.0", "cz-conventional-changelog": "3.3.0",
"decompress": "4.2.1", "decompress": "4.2.1",
"electron": "19.1.8", "electron": "28.2.3",
"electron-builder": "23.0.9", "electron-builder": "24.13.2",
"husky": "4.3.8", "husky": "4.3.8",
"lint-staged": "12.3.8", "lint-staged": "12.3.8",
"wait-on": "7.0.1" "wait-on": "7.0.1"
+5 -3
View File
@@ -1,6 +1,8 @@
const {execSync} = require('child_process') import {execSync} from 'child_process'
const path = require('path') import path from 'path'
const conventionalChangelog = path.join('node_modules', '.bin', 'conventional-changelog') 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 // sometimes release-count 1 is empty
let releaseChangelog = let releaseChangelog =
+306 -595
View File
File diff suppressed because it is too large Load Diff