Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Refactor ctx #2114

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,6 @@ assets/webui
*.nupkg
*.bak
assets/build/snap-hooks
.envrc
.tool-versions
.vscode
4 changes: 4 additions & 0 deletions src/analytics.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ const { join } = require('path')
const { app } = require('electron')
const { existsSync, mkdirSync } = require('fs')

/**
*
* @param {Awaited<import('./context')>} ctx
*/
module.exports = async function (ctx) {
// workaround: recursive mkdir https://github.com/Countly/countly-sdk-nodejs/pull/14
const countlyDataDir = join(app.getPath('userData'), 'countly-data')
Expand Down
8 changes: 8 additions & 0 deletions src/argv-files-handler.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
const fs = require('fs-extra')
const addToIpfs = require('./add-to-ipfs')

/**
*
* @param {Awaited<import('./context')>} ctx
*/
async function argvHandler (argv, ctx) {
let handled = false

Expand All @@ -25,6 +29,10 @@ async function argvHandler (argv, ctx) {
return handled
}

/**
*
* @param {Awaited<import('./context')>} ctx
*/
module.exports = async function (ctx) {
// Checks current proccess
await argvHandler(process.argv, ctx)
Expand Down
8 changes: 8 additions & 0 deletions src/auto-updater/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ function isAutoUpdateSupported () {
let updateNotification = null // must be a global to avoid gc
let feedback = false

/**
*
* @param {Awaited<import('../context')>} ctx
*/
function setup (ctx) {
// we download manually in 'update-available'
autoUpdater.autoDownload = false
Expand Down Expand Up @@ -149,6 +153,10 @@ async function checkForUpdates () {
ipcMain.emit('updatingEnded')
}

/**
*
* @param {Awaited<import('../context')>} ctx
*/
module.exports = async function (ctx) {
if (['test', 'development'].includes(process.env.NODE_ENV)) {
ctx.manualCheckForUpdates = () => {
Expand Down
71 changes: 71 additions & 0 deletions src/context.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// @ts-check
const setupI18n = require('./i18n')
const setupDaemon = require('./daemon')
const setupWebUI = require('./webui')
const setupAppMenu = require('./app-menu')
const setupAutoUpdater = require('./auto-updater')
const setupTray = require('./tray')
const setupAnalytics = require('./analytics')
const handleError = require('./handleError')

/**
* @typedef createDaemonResponse
* @type {ReturnType<import('./daemon/daemon')>}
*/
/**
* @typedef IpfsdController
* @type {(Awaited<createDaemonResponse>)['ipfsd']}
*/
/**
* @typedef AppContext
* @property {null|string} countlyDeviceId
* @property {null|((optional: boolean) => Promise<IpfsdController>)} getIpfsd
* @property {null|((path: string, options?: { focus?: boolean, forceRefresh?: boolean }) => Promise<void>)} launchWebUI
* @property {null|(() => Promise<void>)} manualCheckForUpdates
* @property {() => Promise<any>} restartIpfs
* @property {() => Promise<any>} startIpfs
* @property {() => Promise<any>} stopIpfs
* @property {null|import('electron').Tray} tray
* @property {import('electron').BrowserWindow} webui
*/

/**
* @type {AppContext}
*/
const context = {
countlyDeviceId: null,
getIpfsd: null,
launchWebUI: null,
manualCheckForUpdates: async () => {},
startIpfs: async () => {},
stopIpfs: async () => {},
restartIpfs: async () => {},
tray: null,
webui: null

}

/**
* @type {Promise<AppContext>}
*/
const ctx = (async () => {
try {
await setupAnalytics(context) // ctx.countlyDeviceId
await setupI18n()
await setupAppMenu()

await setupWebUI(context) // ctx.webui, launchWebUI
await setupAutoUpdater(context) // ctx.manualCheckForUpdates
await setupTray(context) // ctx.tray
await setupDaemon(context) // ctx.getIpfsd, startIpfs, stopIpfs, restartIpfs
} catch (err) {
handleError(err)
}

return context
})()

/**
* @type {Promise<AppContext>}
*/
module.exports = ctx
8 changes: 8 additions & 0 deletions src/custom-ipfs-binary.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ const dock = require('./utils/dock')

const SETTINGS_KEY = 'binaryPath'

/**
*
* @param {Awaited<import('./context')>} ctx
*/
async function setCustomBinary (ctx) {
await dock.run(async () => {
logger.info('[custom binary] request to change')
Expand Down Expand Up @@ -57,6 +61,10 @@ async function setCustomBinary (ctx) {
})
}

/**
*
* @param {Awaited<import('./context')>} ctx
*/
function clearCustomBinary (ctx) {
store.delete(SETTINGS_KEY)
logger.info('[custom binary] cleared')
Expand Down
4 changes: 4 additions & 0 deletions src/daemon/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ const logger = require('../common/logger')
const { STATUS } = require('./consts')
const createDaemon = require('./daemon')

/**
*
* @param {Awaited<import('../context')>} ctx
*/
module.exports = async function (ctx) {
let ipfsd = null
let status = null
Expand Down
20 changes: 20 additions & 0 deletions src/handleError.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const logger = require('./common/logger')
const { criticalErrorDialog } = require('./dialogs')

/**
*
* @param {Error} err
* @returns
*/
function handleError (err) {
// Ignore network errors that might happen during the
// execution.
if (err.stack.includes('net::')) {
return
}

logger.error(err)
criticalErrorDialog(err)
}

module.exports = handleError
38 changes: 5 additions & 33 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,18 @@ if (process.env.NODE_ENV === 'test') {
}

const fixPath = require('fix-path')
const { criticalErrorDialog } = require('./dialogs')
const logger = require('./common/logger')
const setupProtocolHandlers = require('./protocol-handlers')
const setupI18n = require('./i18n')
const setupNpmOnIpfs = require('./npm-on-ipfs')
const setupDaemon = require('./daemon')
const setupWebUI = require('./webui')
const setupAutoLaunch = require('./auto-launch')
const setupAutoGc = require('./automatic-gc')
const setupPubsub = require('./enable-pubsub')
const setupNamesysPubsub = require('./enable-namesys-pubsub')
const setupTakeScreenshot = require('./take-screenshot')
const setupAppMenu = require('./app-menu')
const setupArgvFilesHandler = require('./argv-files-handler')
const setupAutoUpdater = require('./auto-updater')
const setupTray = require('./tray')
const setupIpfsOnPath = require('./ipfs-on-path')
const setupAnalytics = require('./analytics')
const setupSecondInstance = require('./second-instance')
const appContext = require('./context')
const handleError = require('./handleError')

// Hide Dock
if (app.dock) app.dock.hide()
Expand All @@ -42,24 +35,10 @@ fixPath()
if (!app.requestSingleInstanceLock()) {
process.exit(0)
}

const ctx = {}

app.on('will-finish-launching', () => {
setupProtocolHandlers(ctx)
app.on('will-finish-launching', async () => {
setupProtocolHandlers(await appContext)
})

function handleError (err) {
// Ignore network errors that might happen during the
// execution.
if (err.stack.includes('net::')) {
return
}

logger.error(err)
criticalErrorDialog(err)
}

process.on('uncaughtException', handleError)
process.on('unhandledRejection', handleError)

Expand All @@ -72,14 +51,7 @@ async function run () {
}

try {
await setupAnalytics(ctx) // ctx.countlyDeviceId
await setupI18n(ctx)
await setupAppMenu(ctx)

await setupWebUI(ctx) // ctx.webui, launchWebUI
await setupAutoUpdater(ctx) // ctx.manualCheckForUpdates
await setupTray(ctx) // ctx.tray
await setupDaemon(ctx) // ctx.getIpfsd, startIpfs, stopIpfs, restartIpfs
const ctx = await appContext

await Promise.all([
setupArgvFilesHandler(ctx),
Expand Down
7 changes: 6 additions & 1 deletion src/npm-on-ipfs/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,12 @@ const npmBin = IS_WIN ? 'npm.cmd' : 'npm'

const CONFIG_KEY = 'experiments.npmOnIpfs'

// Deprecated in February 2021. Remove soon.
/**
* Deprecated in February 2021. Remove soon.
*
* @deprecated
* @param {Awaited<import('../context')>} ctx
*/
module.exports = function (ctx) {
if (store.get(CONFIG_KEY, null) === true) {
logger.info('[npm on ipfs] deprecated, removing')
Expand Down
8 changes: 8 additions & 0 deletions src/protocol-handlers.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ function parseAddr (addr) {
return toUri(addr.toString().includes('/http') ? addr : addr.encapsulate('/http'))
}

/**
*
* @param {Awaited<import('./context')>} ctx
*/
async function parseUrl (url, ctx) {
const ipfsd = ctx.getIpfsd ? await ctx.getIpfsd(true) : null
let base = 'https://ipfs.io'
Expand Down Expand Up @@ -43,6 +47,10 @@ async function argvHandler (argv, ctx) {
return handled
}

/**
*
* @param {Awaited<import('./context')>} ctx
*/
module.exports = function (ctx) {
// Handle if the app started running now, and a link
// was sent to be handled.
Expand Down
4 changes: 4 additions & 0 deletions src/second-instance.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ const { app } = require('electron')
const { argvHandler: protocolHandler } = require('./protocol-handlers')
const { argvHandler: filesHandler } = require('./argv-files-handler')

/**
*
* @param {Awaited<import('./context')>} ctx
*/
module.exports = async function (ctx) {
app.on('second-instance', async (_, argv) => {
if (await protocolHandler(argv, ctx)) {
Expand Down
12 changes: 12 additions & 0 deletions src/take-screenshot.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ function onError (e) {
})
}

/**
*
* @param {Awaited<import('./context')>} ctx
*/
function handleScreenshot (ctx) {
const { getIpfsd, launchWebUI } = ctx

Expand Down Expand Up @@ -99,12 +103,20 @@ function handleScreenshot (ctx) {
}
}

/**
*
* @param {Awaited<import('./context')>} ctx
*/
function takeScreenshot (ctx) {
const { webui } = ctx
logger.info('[screenshot] taking screenshot')
webui.webContents.send('screenshot')
}

/**
*
* @param {Awaited<import('./context')>} ctx
*/
module.exports = function (ctx) {
setupGlobalShortcut({
confirmationDialog: {
Expand Down
20 changes: 15 additions & 5 deletions src/tray.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,16 @@ function buildCheckbox (key, label) {
}
}

// Notes on this: we are only supporting accelerators on macOS for now because
// they natively work as soon as the menu opens. They don't work like that on Windows
// or other OSes and must be registered globally. They still collide with global
// accelerator. Please see ../utils/setup-global-shortcut.js for more info.
/**
* Notes on this: we are only supporting accelerators on macOS for now because
* they natively work as soon as the menu opens. They don't work like that on Windows
* or other OSes and must be registered globally. They still collide with global
* accelerator. Please see ../utils/setup-global-shortcut.js for more info.
*
* @param {Awaited<import('./context')>} ctx
*
* @returns {import('electron').Menu} Electron.CrossProcessExports.Menu
*/
function buildMenu (ctx) {
return Menu.buildFromTemplate([
...[
Expand Down Expand Up @@ -234,7 +240,11 @@ function icon (color) {
// https://www.electronjs.org/docs/faq#my-apps-tray-disappeared-after-a-few-minutes
let tray = null

module.exports = function (ctx) {
/**
*
* @param {Awaited<import('./context')>} ctx
*/
module.exports = async function (ctx) {
logger.info('[tray] starting')
tray = new Tray(icon(off))
let menu = null
Expand Down
Loading