Exemplo n.º 1
1
export function setup () {
  // generate a secret nonce
  requestNonce = crypto.randomBytes(4).readUInt32LE(0)

  // setup the network & db
  dat.setup()

  // wire up RPC
  rpc.exportAPI('datInternalAPI', datInternalAPIManifest, dat, internalOnly)
  rpc.exportAPI('dat', datExternalAPIManifest, datWebAPI)

  // setup the protocol handler
  protocol.registerHttpProtocol('dat',
    (request, cb) => {
      // send requests to the protocol server
      cb({
        method: request.method,
        url: 'http://localhost:' + serverPort + '/?url=' + encodeURIComponent(request.url) + '&nonce=' + requestNonce
      })
    }, err => {
      if (err) throw ProtocolSetupError(err, 'Failed to create protocol: dat')
    }
  )

  // configure chromium's permissions for the protocol
  protocol.registerServiceWorkerSchemes(['dat'])

  // create the internal dat HTTP server
  var server = http.createServer(datServer)
  listenRandomPort(server, { host: '127.0.0.1' }, (_, port) => { serverPort = port })
}
Exemplo n.º 2
0
  http.createServer(httpServer).listen(9999, function () {
    // register core services
    appsManager.registerService({
      title: 'Ultra Launcher',
      appname: 'launch',
      port: 9999,
      protocols: ['http'],
      interfaces: ['page']
    })

    // start applications
    var appsDirectory = require('./apps-directory')(config.getAppsPath())
    appsDirectory.getAppFolders().forEach(app => {
      // spawn each app
      appsManager.spawn(path.join(app.folderPath, 'index.js'))
    })
    // TODO listen for new apps

    // register app: protocol
    electron.protocol.registerHttpProtocol('app', appsManager.protocolHandler, function (err) {
      if (err)
        throw err

      // DEBUG wait a second to open the window, so hello-world can register
      setTimeout(() => {
        var mainWindow = windows.create()
        mainWindow.loadURL('app:launch')
      }, 1e3)
    })
  })
Exemplo n.º 3
0
let hackFirstPage = () => {
    protocol.interceptHttpProtocol('http', (request, callback) => {
        request.session = null;
        callback(request);
        protocol.uninterceptProtocol('http');
    });
};
Exemplo n.º 4
0
  app.on('ready', function() {
    log('ready');
    log('intercepting protocol http');
    protocol.interceptHttpProtocol('http', function(request, callback) {
      if (request.url.indexOf(global.manifest.virtualUrl) === 0) {
        const newPath = request.url.replace(global.manifest.virtualUrl, 'file://' + app.getAppPath());
        const newPathShort = request.url.replace(global.manifest.virtualUrl, 'file://<app>');
        log('intercepted http', request.method, request.url, '=>', newPathShort);
        request.url = newPath;
        callback(request);
      }
    }, function(err) {
      if (err) {
        logFatal(err);
        log('intercepting protocol http failed, not going to launch the app anymore');
        return;
      }

      log('launching app');
      const Application = require('browser/application').default;
      global.application = new Application();
      global.application.init();
      global.ready = true;
    });
  });
Exemplo n.º 5
0
 // In most environments, loadURL handles this logic for us, but in some
 // it just hangs for unhandled protocols. Mitigate by checking ourselves.
 function canLoadProtocol(protocol, callback) {
   protocol = (protocol || '').replace(/:$/, '')
   if (!protocol || KNOWN_PROTOCOLS.includes(protocol)) {
     return callback(true)
   }
   electron.protocol.isProtocolHandled(protocol, callback)
 }
Exemplo n.º 6
0
export function setup () {
  protocol.registerBufferProtocol('dat', (request, cb) => {
    cb = once(cb) // just to be safe

    // validate request
    var urlp = url.parse(request.url)
    var archiveKey = urlp.host
    if (dat.LINK_REGEX.test(archiveKey) == false)
      return cb(INVALID_URL)
    if (request.method != 'GET')
      return cb(METHOD_NOT_SUPPORTED)

    // start searching the network
    var archive = dat.getArchive(archiveKey)
    dat.swarm(archiveKey)

    // setup a timeout
    var timeout = setTimeout(() => {
      log('[DAT] Timed out searching for', archiveKey)
      cb(TIMED_OUT)
    }, REQUEST_TIMEOUT_MS)

    // list archive contents
    log('[DAT] attempting to list archive', archiveKey)
    archive.list((err, entries) => {
      clearTimeout(timeout)

      if (err) {
        // QUESTION: should there be a more specific error response?
        // not sure what kind of failures can occur here (other than broken pipe)
        // -prf
        log('[DAT] Archive listing errored', err)
        return cb(FAILED)
      }
      
      // lookup the entry
      log('[DAT] Archive listing for', archiveKey, entries)
      var entry = dat.lookupEntry(entries, urlp.path)
      if (!entry) {
        log('[DAT] Entry not found:', urlp.path)
        return cb(FILE_NOT_FOUND)
      }

      // fetch the entry
      // TODO handle stream errors
      log('[DAT] Entry found:', urlp.path)
      dat.getEntry(archive, entry, (err, entryInfo) => {
        // respond
        cb({
          mimeType: entryInfo.mimeType,
          data: entryInfo.data
        })
      })         
    })
  }, e => {
    if (e)
      console.error('Failed to register dat protocol', e)
  });
}
Exemplo n.º 7
0
elc.app.on('will-finish-launching', function () {
    // Register Aether's aether:// as a standard (http-like) protocol
    elc.protocol.registerStandardSchemes(['aether']);
    elc.app.on('open-url', function (e, url) {
        e.preventDefault();
        linkToLoadAtBoot = url.substring(8);
    });
});
Exemplo n.º 8
0
app.on('ready', () => {
  protocol.registerFileProtocol('silex', (request, callback) => {
    // TODO Remove this hack
    const pathname = url.parse(request.url).pathname.replace('home/home', 'home');
    callback({path: pathname});
  }, (error) => {
    if (error) console.error('Failed to register protocol')
  });
});
Exemplo n.º 9
0
Arquivo: main.js Projeto: umd-mith/sga
app.on('ready', () => {
  protocol.interceptFileProtocol('file', (request, callback) => {
    let url = request.url.substr(7)    /* all urls start with 'file://' */
    callback({ path: path.normalize(`${__dirname}/${url}`)})
  }, (err) => {
    if (err) console.error('Failed to register protocol')
  })
  createWindow()
})
Exemplo n.º 10
0
function enableSwarmProtocol() {
  protocol.registerHttpProtocol(
    'bzz',
    (request, callback) => {
      if (
        [SwarmState.Disabling, SwarmState.Disabled].includes(
          store.getState().settings.swarmState
        )
      ) {
        const error = global.i18n.t('mist.errors.swarm.notEnabled');
        dialog.showErrorBox('Note', error);
        callback({ error });
        store.dispatch({
          type: '[MAIN]:PROTOCOL:ERROR',
          payload: { protocol: 'bzz', error }
        });
        return;
      }

      const redirectPath = `${Settings.swarmURL}/${request.url.replace(
        'bzz:/',
        'bzz://'
      )}`;

      if (store.getState().settings.swarmState === SwarmState.Enabling) {
        swarmNode.on('started', () => {
          callback({
            method: request.method,
            referrer: request.referrer,
            url: redirectPath
          });
        });
      } else {
        // Swarm enabled
        callback({
          method: request.method,
          referrer: request.referrer,
          url: redirectPath
        });
      }

      store.dispatch({
        type: '[MAIN]:PROTOCOL:REQUEST',
        payload: { protocol: 'bzz' }
      });
    },
    error => {
      if (error) {
        log.error(error);
      }
    }
  );
}
Exemplo n.º 11
0
const registerProtocol = () =>
  electron.protocol.registerFileProtocol('asset', (request, callback) => {
    const file = request.url.substr(8);
    const decodedPath = decodeURIComponent(file);
    const appFilePath = path.normalize(path.join(appPath, 'protocols', decodedPath));
    const userDataFilePath = path.normalize(path.join(userDataPath, 'protocols', decodedPath));

    // eslint-disable-next-line
    fs.access(appFilePath, fs.constants.R_OK, (err) => {
      const filePath = err ? userDataFilePath : appFilePath;
      callback({ path: filePath });
    });
  }, (error) => {
    if (error) {
      console.error('Failed to register protocol');
    }
  });
Exemplo n.º 12
0
Arquivo: main.js Projeto: 7696122/vmd
function registerEmojiProtocol () {
  const protocol = require('electron').protocol
  const emojiPath = path.resolve(path.dirname(require.resolve('emojify.js')), '..', 'images', 'basic')

  protocol.registerFileProtocol(
    'emoji',
    function (req, callback) {
      var emoji = url.parse(req.url).hostname
      callback({
        path: path.join(emojiPath, emoji + '.png')
      })
    },
    function (err) {
      if (err) {
        console.error('failed to register protocol')
      }
    }
  )
}
Exemplo n.º 13
0
  function temporarilyInterceptFileProtocol () {
    // very hacky way to dynamically create vmd.html
    const protocol = require('electron').protocol
    const template = require('lodash.template')
    const indexHtml = template(fs.readFileSync(path.join(__dirname, '..', 'renderer', 'vmd.html'), { encoding: 'utf-8' }))

    protocol.interceptStringProtocol(
      'file',
      function (req, callback) {
        var mainStyle = options.mainStylesheet
          ? styles.getStylesheet(options.mainStylesheet)
          : styles.getStylesheet(path.resolve(__dirname, '../node_modules/github-markdown-css/github-markdown.css'))

        var extraStyle = options.extraStylesheet
          ? styles.getStylesheet(options.extraStylesheet)
          : ''

        var highlightStyle = options.highlightStylesheet
          ? styles.getStylesheet(options.highlightStylesheet)
          : styles.getHighlightTheme('default') + '\n' + styles.getHighlightTheme(options.highlightTheme)

        var data = {
          mainStyle: mainStyle,
          extraStyle: extraStyle,
          highlightStyle: highlightStyle
        }
        callback({
          mimeType: 'text/html',
          data: indexHtml(data)
        })

        process.nextTick(function () {
          protocol.uninterceptProtocol('file')
        })
      },
      function (err, scheme) {
        if (err) {
          console.error('failed to register', scheme, 'protocol')
        }
      }
    )
  }
Exemplo n.º 14
0
export function setup () {
  protocol.registerFileProtocol('beaker', (request, cb) => {
    // FIXME
    // if-casing every possible asset is pretty dumb
    // generalize this
    // -prf

    // browser ui
    if (request.url == 'beaker:shell-window')
      return cb(path.join(__dirname, 'shell-window.html'))
    if (request.url == 'beaker:shell-window.js')
      return cb(path.join(__dirname, 'shell-window.build.js'))
    if (request.url == 'beaker:shell-window.css')
      return cb(path.join(__dirname, 'stylesheets/shell-window.css'))

    // builtin pages
    for (let slug of ['start', 'favorites', 'archives', 'history', 'downloads', 'settings']) {
      if (request.url == `beaker:${slug}`)
        return cb(path.join(__dirname, 'builtin-pages.html'))
    }
    if (request.url.startsWith('beaker:site/'))
      return cb(path.join(__dirname, 'builtin-pages.html'))
    if (request.url == 'beaker:builtin-pages.js')
      return cb(path.join(__dirname, 'builtin-pages.build.js'))
    if (request.url == 'beaker:builtin-pages.css')
      return cb(path.join(__dirname, 'stylesheets/builtin-pages.css'))

    // common assets
    if (request.url == 'beaker:font')
      return cb(path.join(__dirname, 'fonts/photon-entypo.woff'))
    if (request.url.startsWith('beaker:logo'))
      return cb(path.join(__dirname, 'img/logo.png'))

    return cb(-6)
  }, e => {
    if (e)
      console.error('Failed to register beaker protocol', e)
  });
}
Exemplo n.º 15
0
export default mainWindow => {
    // Can't be `require`d before the app is ready
    const protocol = require("electron").protocol;
    protocol.registerStringProtocol("khan", (request, callback) => {
        const data = parseNativeRequest(request);
        mainWindow.webContents.send(
            consts.ipcKhanProtocolEvent, data);
        callback("This response is completely ignored");
    });

    mainWindow.loadURL("file://" + __dirname + "/../static/index.html");

    ipcMain.on("log", (event, args) => {
        console.log(...args);
    });
    ipcMain.on("log:warn", (event, args) => {
        console.warn(...args);
    });
    ipcMain.on("log:error", (event, args) => {
        console.error(...args);
    });
};
Exemplo n.º 16
0
export function setup () {
  // generate a secret nonce
  requestNonce = '' + crypto.randomBytes(4).readUInt32LE(0)

  // setup the protocol handler
  protocol.registerHttpProtocol('beaker',
    (request, cb) => {
      // send requests to the protocol server
      cb({
        method: request.method,
        url: `http://localhost:${serverPort}/?url=${encodeURIComponent(request.url)}&nonce=${requestNonce}`
      })
    }, err => {
      if (err) {
        throw new Error('Failed to create protocol: beaker. ' + err)
      }
    }
  )

  // create the internal beaker HTTP server
  var server = http.createServer(beakerServer)
  listenRandomPort(server, { host: '127.0.0.1' }, (err, port) => serverPort = port)
}
Exemplo n.º 17
0
exports.registerResourceProtocol = () => {
	const basePath = path.resolve(__dirname, '../');

	protocol.registerFileProtocol(
		'res',
		(req, callback) => {
			var target;
			var parsed = url.parse(req.url);

			if (parsed.hostname === 'doc') {
				target = path.join(basePath, 'doc', parsed.pathname + '.txt');
			}
			else if (parsed.hostname === 'demo') {
				target = path.join(basePath, 'demosongs', parsed.pathname + '.json');
			}

			callback({ path: target });
		},
		(err) => {
			if (err) throw err;
		}
	);
};
Exemplo n.º 18
0
const { protocol } = require('electron');


protocol.registerHttpProtocol('mist', (request, callback) => {
    // callback({mimeType: 'text/html', data: new Buffer('<h5>Response</h5>')});

    console.log((request.url.indexOf('mist://interface') !== -1) ? global.interfaceAppUrl + request.url.replace('mist://interface', '') : '');

    const call = {
        url: (request.url.indexOf('mist://interface') !== -1) ? global.interfaceAppUrl + request.url.replace('mist://interface', '') : '', // 'http://localhost:3050/' + request.url.replace('mist://',''),
        method: request.method,
        referrer: request.referrer,
    };

    console.log(call);
    // console.log(call);

    callback(call);
}, (error) => {
    if (error) {
        console.error('Failed to register protocol');
    }
});


// protocol.registerProtocol('ele', function(request) {
//     var url = request.url.substr(7)
//     return new protocol.RequestStringJob({data: 'Hello'});
// });

// protocol.registerProtocol('bzz', function(request) {
Exemplo n.º 19
0
  function fullInit(storeFile) {
    if (app.dock) app.dock.hide();
    protocol.interceptHttpProtocol('http', (request, callback) => {
      shell.openExternal(request.url);
    }, (error) => {
      if (error) console.error('Failed to register http protocol');
    });
    protocol.interceptHttpProtocol('https', (request, callback) => {
      shell.openExternal(request.url);
    }, (error) => {
      if (error) console.error('Failed to register https protocol');
    });
    const view = 'file://' + path.join(__dirname, '..', '..', 'static', 'index.html');
    const iconPath = path.join(__dirname, '..', '..', 'static', 'notepad.png');
    const tray =  new Tray(iconPath);
    tray.setToolTip('Just some nice markdown notes ...');

    const win = new BrowserWindow({ width: 600, height: 800, show: false, frame: false });
    win.on('blur', () => hideWindow());
    win.setVisibleOnAllWorkspaces(true);
    win.loadURL(view);
    win.webContents.on('did-finish-load', () => {
      readFile(storeFile, data => {
        win.webContents.send('lifecycle-event', { event: 'init', initalText: data });
      })
    });

    const positioner = new Positioner(win);
    const contextMenu = Menu.buildFromTemplate([
      {
        label: 'Reload',
        accelerator: 'CmdOrCtrl+R',
        click(item, focusedWindow) {
          if (focusedWindow) focusedWindow.reload();
        }
      },
      {
        label: 'Toogle DevTools',
        accelerator: 'CmdOrCtrl+D',
        click(item, focusedWindow) {
          if (focusedWindow) focusedWindow.toggleDevTools();
        }
      },
      {
        type: 'separator'
      },
      {
        label: 'Quit',
        accelerator: 'CmdOrCtrl+Q',
        click(item, focusedWindow) {
          app.quit();
        }
      }
    ]);

    function hideWindow() {
      win.hide();
    }

    function showWindow(trayPos) {
      let noBoundsPosition = (process.platform === 'win32') ? 'bottomRight' : 'trayCenter';
      let position = positioner.calculate(noBoundsPosition, trayPos);
      win.setPosition(position.x, position.y);
      win.show();
    }

    function clicked(e, bounds) {
      if (e.altKey || e.shiftKey || e.ctrlKey || e.metaKey) return hideWindow();
      if (win && win.isVisible()) return hideWindow();
      showWindow(bounds);
    }

    function logAllArgs(evt, ...params) {
      console.log(...params);
    }

    tray.on('click', (e, bounds) => {
      clicked(e, bounds);
    });
    tray.on('right-click', (e, bounds) => {
      tray.popUpContextMenu(contextMenu);
    });
    tray.on('double-click', clicked);

    ipcMain.on('console.log', logAllArgs);
    ipcMain.on('save-content-to-file', (evt, payload) => {
      writeFile(storeFile, payload.text, () => '');
    });
  }
Exemplo n.º 20
0
app.on("ready", function() {
  /*protocol.interceptHttpProtocol('http', function(req, callback) {
      console.log(req);
      callback(null);
      return null;
    }
  );*/

  // Fake http server for epub files
  protocol.registerBufferProtocol("epub", function(request, callback) {
    var epubPath = request.url.substring(7);
    epubPath = path.normalize(epubPath);
    console.log("epub: serve file", epubPath);

    if (epubPath.indexOf(".epub/") > 0 ||
        epubPath.indexOf(".epub\\") > 0 ) {
      // Read zipped epub
      var epubPathEndIndex = epubPath.indexOf(".epub") + 5;
      var epubFilePath = epubPath.substr(0, epubPathEndIndex);
      var epubContentPath = epubPath.substr(epubPathEndIndex + 1);

      // Fix windows path
      if (os.platform() == "win32" && epubFilePath.indexOf("C\\") == 0) {
        epubFilePath = epubFilePath.replace("C\\", "C:\\");
      }

      // Replace back slash by slash
      epubContentPath = epubContentPath.replace(/\\/g, "/");

      readZipContent(epubFilePath, epubContentPath, function(data) {
          callback(data);
      });
    } else {
      fs.readFile(epubPath, function (err, data ) {
        callback(data);
      });

    }
  }, function (error) {
      if (error)
          console.error("Failed to register protocol");
  });
  /*
  protocol.registerStringProtocol("epub-exploded", function(request, callback) {
      var epubFullPath = request.url.substr(15);
      var epubPathEndIndex = epubFullPath.indexOf(".epub") + 5;
      var epubPath = epubFullPath.substr(0, epubPathEndIndex);
      var epubContentPath = epubFullPath.substr(epubPathEndIndex + 1);
      console.log("epub-exploded:", epubPath, epubContentPath);

      readZipContent(epubPath, epubContentPath, function(data) {
        callback(data);
      });
  }, function (error) {
      if (error)
          console.error("Failed to register protocol");
  });*/


  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 1000, height: 600,
    webPreferences: {
      webSecurity: false
    }
  });

  // Hide menu
  mainWindow.setMenu(null);

  // and load the entry html page
  console.log(process.env.APP_ENTRY_RELATIVE_URL);
  mainWindow.loadURL("epub://" + path.normalize(__dirname + process.env.APP_ENTRY_RELATIVE_URL));

  /*session.defaultSession.webRequest.onBeforeRequest((details, callback) => {
    var url = details.url;

    if (url.startsWith("http://epub.local")) {
      var url = "epub://" + url.substr(17);
      return callback({cancel: false, redirectURL: url});
    }

    return callback({cancel: false});
  });*/

  // Only open dev tools in dev environment
  if(process.env.ENVIRONMENT === "DEV") {
    // Open the DevTools.
    mainWindow.openDevTools();
  }

  // Emitted when the window is closed.
  mainWindow.on("closed", function() {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
});
Exemplo n.º 21
0
export function setup () {
  // setup the protocol handler
  protocol.registerStreamProtocol('beaker', beakerProtocol, err => {
    if (err) throw new Error('Failed to create protocol: beaker. ' + err)
  })
}
Exemplo n.º 22
0
app.on('ready', function () {
  // Test if using protocol module would crash.
  electron.protocol.registerStringProtocol('test-if-crashes', function () {})

  // Send auto updater errors to window to be verified in specs
  electron.autoUpdater.on('error', function (error) {
    window.send('auto-updater-error', error.message)
  })

  window = new BrowserWindow({
    title: 'Electron Tests',
    show: !global.isCi,
    width: 800,
    height: 600,
    webPreferences: {
      backgroundThrottling: false
    }
  })
  window.loadURL(url.format({
    pathname: path.join(__dirname, '/index.html'),
    protocol: 'file',
    query: {
      grep: argv.grep,
      invert: argv.invert ? 'true' : ''
    }
  }))
  window.on('unresponsive', function () {
    var chosen = dialog.showMessageBox(window, {
      type: 'warning',
      buttons: ['Close', 'Keep Waiting'],
      message: 'Window is not responsing',
      detail: 'The window is not responding. Would you like to force close it or just keep waiting?'
    })
    if (chosen === 0) window.destroy()
  })
  window.webContents.on('crashed', function () {
    console.error('Renderer process crashed')
    process.exit(1)
  })

  // For session's download test, listen 'will-download' event in browser, and
  // reply the result to renderer for verifying
  var downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf')
  ipcMain.on('set-download-option', function (event, needCancel, preventDefault, filePath = downloadFilePath) {
    window.webContents.session.once('will-download', function (e, item) {
      window.webContents.send('download-created',
        item.getState(),
        item.getURLChain(),
        item.getMimeType(),
        item.getReceivedBytes(),
        item.getTotalBytes(),
        item.getFilename(),
        item.getSavePath())
      if (preventDefault) {
        e.preventDefault()
        const url = item.getURL()
        const filename = item.getFilename()
        setImmediate(function () {
          try {
            item.getURL()
          } catch (err) {
            window.webContents.send('download-error', url, filename, err.message)
          }
        })
      } else {
        if (item.getState() === 'interrupted' && !needCancel) {
          item.resume()
        } else {
          item.setSavePath(filePath)
        }
        item.on('done', function (e, state) {
          window.webContents.send('download-done',
            state,
            item.getURL(),
            item.getMimeType(),
            item.getReceivedBytes(),
            item.getTotalBytes(),
            item.getContentDisposition(),
            item.getFilename(),
            item.getSavePath(),
            item.getURLChain(),
            item.getLastModifiedTime(),
            item.getETag())
        })
        if (needCancel) item.cancel()
      }
    })
    event.returnValue = 'done'
  })

  ipcMain.on('prevent-next-input-event', (event, key, id) => {
    webContents.fromId(id).once('before-input-event', (event, input) => {
      if (key === input.key) event.preventDefault()
    })
  })

  ipcMain.on('executeJavaScript', function (event, code, hasCallback) {
    let promise

    if (hasCallback) {
      promise = window.webContents.executeJavaScript(code, (result) => {
        window.webContents.send('executeJavaScript-response', result)
      })
    } else {
      promise = window.webContents.executeJavaScript(code)
    }

    promise.then((result) => {
      window.webContents.send('executeJavaScript-promise-response', result)
    }).catch((error) => {
      window.webContents.send('executeJavaScript-promise-error', error)

      if (error && error.name) {
        window.webContents.send('executeJavaScript-promise-error-name', error.name)
      }
    })

    if (!hasCallback) {
      event.returnValue = 'success'
    }
  })
})
Exemplo n.º 23
0
/* eslint-env node */

const { app, BrowserWindow, ipcMain, Menu, protocol } = require('electron');
const { dirname, join, resolve, sep } = require('path');
const protocolServe = require('electron-protocol-serve');
const mainMenu = require('./app/menu');

let mainWindow = null;

// Registering a protocol & schema to serve our Ember application
protocol.registerStandardSchemes(['serve'], { secure: true });
protocolServe({
  cwd: join(__dirname || resolve(dirname('')), '..', 'ember'),
  app,
  protocol,
});

// Uncomment the lines below to enable Electron's crash reporter
// For more information, see http://electron.atom.io/docs/api/crash-reporter/
// electron.crashReporter.start({
//  productName: 'YourName',
//  companyName: 'YourCompany',
//  submitURL: 'https://your-domain.com/url-to-submit',
//  autoSubmit: true
// });

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});
Exemplo n.º 24
0
app.on('ready', function() {
  // Test if using protocol module would crash.
  electron.protocol.registerStringProtocol('test-if-crashes', function() {});

  // Send auto updater errors to window to be verified in specs
  electron.autoUpdater.on('error', function (error) {
    window.send('auto-updater-error', error.message);
  });

  window = new BrowserWindow({
    title: 'Electron Tests',
    show: false,
    width: 800,
    height: 600,
    webPreferences: {
      javascript: true  // Test whether web preferences crashes.
    },
  });
  window.loadURL(url.format({
    pathname: __dirname + '/index.html',
    protocol: 'file',
    query: {
      grep: argv.grep,
      invert: argv.invert ? 'true': ''
    }
  }));
  window.on('unresponsive', function() {
    var chosen = dialog.showMessageBox(window, {
      type: 'warning',
      buttons: ['Close', 'Keep Waiting'],
      message: 'Window is not responsing',
      detail: 'The window is not responding. Would you like to force close it or just keep waiting?'
    });
    if (chosen === 0) window.destroy();
  });

  // For session's download test, listen 'will-download' event in browser, and
  // reply the result to renderer for verifying
  var downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf');
  ipcMain.on('set-download-option', function(event, need_cancel, prevent_default) {
    window.webContents.session.once('will-download', function(e, item) {
      if (prevent_default) {
        e.preventDefault();
        const url = item.getURL();
        const filename = item.getFilename();
        setImmediate(function() {
          try {
            item.getURL();
          } catch(err) {
            window.webContents.send('download-error', url, filename, err.message);
          }
        });
      } else {
        item.setSavePath(downloadFilePath);
        item.on('done', function(e, state) {
          window.webContents.send('download-done',
                                  state,
                                  item.getURL(),
                                  item.getMimeType(),
                                  item.getReceivedBytes(),
                                  item.getTotalBytes(),
                                  item.getContentDisposition(),
                                  item.getFilename());
        });
        if (need_cancel)
          item.cancel();
      }
    });
    event.returnValue = "done";
  });

  ipcMain.on('executeJavaScript', function(event, code, hasCallback) {
    if (hasCallback) {
      window.webContents.executeJavaScript(code, (result) => {
        window.webContents.send('executeJavaScript-response', result);
      });
    } else {
      window.webContents.executeJavaScript(code);
      event.returnValue = "success";
    }
  });
});
Exemplo n.º 25
0
 process.nextTick(function () {
   protocol.uninterceptProtocol('file')
 })
Exemplo n.º 26
0
onReady = () => {
    global.config = db.getCollection('SYS_config');

    // setup DB sync to backend
    dbSync.backendSyncInit();

    // Initialise window mgr
    Windows.init();

    // Enable the Swarm protocol
    protocol.registerHttpProtocol('bzz', (request, callback) => {
        const redirectPath = `${Settings.swarmURL}/${request.url.replace('bzz:/', 'bzz://')}`;
        callback({ method: request.method, referrer: request.referrer, url: redirectPath });
    }, (error) => {
        if (error) {
            log.error(error);
        }
    });

    // check for update
    if (!Settings.inAutoTestMode) UpdateChecker.run();

    // initialize the web3 IPC provider backend
    ipcProviderBackend.init();

    // instantiate custom protocols
    // require('./customProtocols.js');

    // change to user language now that global.config object is ready
    i18n.changeLanguage(Settings.language);

    // add menu already here, so we have copy and past functionality
    appMenu();

    // Create the browser window.

    const defaultWindow = windowStateKeeper({
        defaultWidth: 1024 + 208,
        defaultHeight: 720
    });

    // MIST
    if (Settings.uiMode === 'mist') {
        mainWindow = Windows.create('main', {
            primary: true,
            electronOptions: {
                width: Math.max(defaultWindow.width, 500),
                height: Math.max(defaultWindow.height, 440),
                x: defaultWindow.x,
                y: defaultWindow.y,
                webPreferences: {
                    nodeIntegration: true, /* necessary for webviews;
                        require will be removed through preloader */
                    preload: `${__dirname}/modules/preloader/mistUI.js`,
                    'overlay-fullscreen-video': true,
                    'overlay-scrollbars': true,
                    experimentalFeatures: true,
                },
            },
        });

    // WALLET
    } else {
        mainWindow = Windows.create('main', {
            primary: true,
            electronOptions: {
                width: Math.max(defaultWindow.width, 500),
                height: Math.max(defaultWindow.height, 440),
                x: defaultWindow.x,
                y: defaultWindow.y,
                webPreferences: {
                    preload: `${__dirname}/modules/preloader/walletMain.js`,
                    'overlay-fullscreen-video': true,
                    'overlay-scrollbars': true,
                },
            },
        });
    }

    // Delegating events to save window bounds on windowStateKeeper
    defaultWindow.manage(mainWindow.window);

    if (!Settings.inAutoTestMode) {
        splashWindow = Windows.create('splash', {
            primary: true,
            url: `${global.interfacePopupsUrl}#splashScreen_${Settings.uiMode}`,
            show: true,
            electronOptions: {
                width: 400,
                height: 230,
                resizable: false,
                backgroundColor: '#F6F6F6',
                useContentSize: true,
                frame: false,
                webPreferences: {
                    preload: `${__dirname}/modules/preloader/splashScreen.js`,
                },
            },
        });
    }

    // Checks time sync
    if (!Settings.skiptimesynccheck) {
        timesync.checkEnabled((err, enabled) => {
            if (err) {
                log.error('Couldn\'t infer if computer automatically syncs time.', err);
                return;
            }

            if (!enabled) {
                dialog.showMessageBox({
                    type: 'warning',
                    buttons: ['OK'],
                    message: global.i18n.t('mist.errors.timeSync.title'),
                    detail: `${global.i18n.t('mist.errors.timeSync.description')}\n\n${global.i18n.t(`mist.errors.timeSync.${process.platform}`)}`,
                }, () => {
                });
            }
        });
    }

    const kickStart = () => {
        // client binary stuff
        ClientBinaryManager.on('status', (status, data) => {
            Windows.broadcast('uiAction_clientBinaryStatus', status, data);
        });

        // node connection stuff
        ethereumNode.on('nodeConnectionTimeout', () => {
            Windows.broadcast('uiAction_nodeStatus', 'connectionTimeout');
        });

        ethereumNode.on('nodeLog', (data) => {
            Windows.broadcast('uiAction_nodeLogText', data.replace(/^.*[0-9]]/, ''));
        });

        // state change
        ethereumNode.on('state', (state, stateAsText) => {
            Windows.broadcast('uiAction_nodeStatus', stateAsText,
                ethereumNode.STATES.ERROR === state ? ethereumNode.lastError : null
            );
        });

        // starting swarm
        swarmNode.on('starting', () => {
            Windows.broadcast('uiAction_swarmStatus', 'starting');
        });

        // swarm download progress
        swarmNode.on('downloadProgress', (progress) => {
            Windows.broadcast('uiAction_swarmStatus', 'downloadProgress', progress);
        });

        // started swarm
        swarmNode.on('started', (isLocal) => {
            Windows.broadcast('uiAction_swarmStatus', 'started', isLocal);
        });


        // capture sync results
        const syncResultPromise = new Q((resolve, reject) => {
            nodeSync.on('nodeSyncing', (result) => {
                Windows.broadcast('uiAction_nodeSyncStatus', 'inProgress', result);
            });

            nodeSync.on('stopped', () => {
                Windows.broadcast('uiAction_nodeSyncStatus', 'stopped');
            });

            nodeSync.on('error', (err) => {
                log.error('Error syncing node', err);

                reject(err);
            });

            nodeSync.on('finished', () => {
                nodeSync.removeAllListeners('error');
                nodeSync.removeAllListeners('finished');

                resolve();
            });
        });

        // check legacy chain
        // CHECK for legacy chain (FORK RELATED)
        Q.try(() => {
            // open the legacy chain message
            if ((Settings.loadUserData('daoFork') || '').trim() === 'false') {
                dialog.showMessageBox({
                    type: 'warning',
                    buttons: ['OK'],
                    message: global.i18n.t('mist.errors.legacyChain.title'),
                    detail: global.i18n.t('mist.errors.legacyChain.description')
                }, () => {
                    shell.openExternal('https://github.com/ethereum/mist/releases');
                    app.quit();
                });

                throw new Error('Cant start client due to legacy non-Fork setting.');
            }
        })
        .then(() => {
            return ClientBinaryManager.init();
        })
        .then(() => {
            return ethereumNode.init();
        })
        .then(() => {
            // Wallet shouldn't start Swarm
            if (Settings.uiMode === 'wallet') {
                return Promise.resolve();
            }
            return swarmNode.init();
        })
        .then(function sanityCheck() {
            if (!ethereumNode.isIpcConnected) {
                throw new Error('Either the node didn\'t start or IPC socket failed to connect.');
            }

            /* At this point Geth is running and the socket is connected. */
            log.info('Connected via IPC to node.');

            // update menu, to show node switching possibilities
            appMenu();
        })
        .then(function getAccounts() {
            return ethereumNode.send('eth_accounts', []);
        })
        .then(function onboarding(resultData) {

            if (ethereumNode.isGeth && (resultData.result === null || (_.isArray(resultData.result) && resultData.result.length === 0))) {
                log.info('No accounts setup yet, lets do onboarding first.');

                return new Q((resolve, reject) => {
                    const onboardingWindow = Windows.createPopup('onboardingScreen', {
                        primary: true,
                        electronOptions: {
                            width: 576,
                            height: 442,
                        },
                    });

                    onboardingWindow.on('closed', () => {
                        app.quit();
                    });

                    // change network types (mainnet, testnet)
                    ipcMain.on('onBoarding_changeNet', (e, testnet) => {
                        const newType = ethereumNode.type;
                        const newNetwork = testnet ? 'rinkeby' : 'main';

                        log.debug('Onboarding change network', newType, newNetwork);

                        ethereumNode.restart(newType, newNetwork)
                            .then(function nodeRestarted() {
                                appMenu();
                            })
                            .catch((err) => {
                                log.error('Error restarting node', err);

                                reject(err);
                            });
                    });

                    // launch app
                    ipcMain.on('onBoarding_launchApp', () => {
                        // prevent that it closes the app
                        onboardingWindow.removeAllListeners('closed');
                        onboardingWindow.close();

                        ipcMain.removeAllListeners('onBoarding_changeNet');
                        ipcMain.removeAllListeners('onBoarding_launchApp');

                        resolve();
                    });

                    if (splashWindow) {
                        splashWindow.hide();
                    }
                });
            }

            return;
        })
        .then(function doSync() {
            // we're going to do the sync - so show splash
            if (splashWindow) {
                splashWindow.show();
            }

            if (!Settings.inAutoTestMode) {
                return syncResultPromise;
            }

            return;
        })
        .then(function allDone() {
            startMainWindow();
        })
        .catch((err) => {
            log.error('Error starting up node and/or syncing', err);
        }); /* socket connected to geth */
    }; /* kick start */

    if (splashWindow) {
        splashWindow.on('ready', kickStart);
    } else {
        kickStart();
    }
}; /* onReady() */
Exemplo n.º 27
0
This is less secure than using local IPC - your passwords will be sent over the wire in plaintext.

Only do this if you have secured your HTTP connection or you know what you are doing.
`);
    }

    // initialise the db
    global.db.init().then(onReady).catch((err) => {
        log.error(err);
        app.quit();
    });
});

// Allows the Swarm protocol to behave like http
protocol.registerStandardSchemes(['bzz']);

onReady = () => {
    global.config = db.getCollection('SYS_config');

    // setup DB sync to backend
    dbSync.backendSyncInit();

    // Initialise window mgr
    Windows.init();

    // Enable the Swarm protocol
    protocol.registerHttpProtocol('bzz', (request, callback) => {
        const redirectPath = `${Settings.swarmURL}/${request.url.replace('bzz:/', 'bzz://')}`;
        callback({ method: request.method, referrer: request.referrer, url: redirectPath });
    }, (error) => {
Exemplo n.º 28
0
app.on('ready', function () {
  electron.protocol.registerServiceWorkerSchemes(['file:']);

  // Get starting HTML file
  var htmlFile = path.resolve(__dirname, 'lib', 'index.html');
  var customHtml = false; // if we should watch it as well
  if (argv.index) {
    customHtml = true;
    htmlFile = path.isAbsolute(argv.index) ? argv.index : path.resolve(cwd, argv.index);
  }

  var mainIndexURL = 'file://' + __dirname + '/index.html';

  // Replace index.html with custom one
  electron.protocol.interceptBufferProtocol('file', function (request, callback) {
    // We can't just spin up a local server for this, see here:
    // https://github.com/atom/electron/issues/2414

    var file = request.url;
    if (file === mainIndexURL) {
      file = htmlFile;
    } else if (file.indexOf('file://') === 0) {
      // All other assets should be relative to the user's cwd
      file = file.substring(7);
      file = path.resolve(cwd, path.relative(__dirname, file));
    }

    fs.readFile(file, function (err, data) {
      // Could convert Node error codes to Chromium for better reporting
      if (err) return callback(-6);
      callback({
        data: data,
        mimeType: mime.lookup(file)
      });
    });
  }, function (err) {
    if (err) fatal(err);
  });

  // Setup the BrowserWindow
  mainWindow = createMainWindow(entryFile, mainIndexURL, argv, function () {
    // When we first launch, ensure the quit flag is set to the user args
    globals.quit = argv.quit;

    // Focus the devtools.
    app.focus();
  });

  // De-reference for GC
  mainWindow.on('closed', function () {
    mainWindow = null;
  });

  // Setup the file watcher
  if (argv.watch) {
    var globs = [].concat(argv.watch).filter(function (f) {
      return typeof f === 'string';
    });
    if (globs.length === 0) globs = [ '**/*.{js,json}' ];
    if (customHtml && globs.indexOf(htmlFile) === -1) {
      // also watch the specified --index HTML file
      globs.push(htmlFile);
    }
    watcher = createWatch(globs, argv);
    watcher.on('change', function (file) {
      if (mainWindow) mainWindow.reload();
    });
  }

  // Fatal error in renderer
  ipc.on('error', function (event, errObj) {
    var err = JSON.parse(errObj);
    bail(err.stack);
  });

  function bail (err) {
    console.error(err.stack ? err.stack : err);
    if (globals.quit) {
      exitWithCode1 = true;
      if (mainWindow) mainWindow.close();
    }
  }

  function fatal (err) {
    globals.quit = true;
    bail(err);
  }
});
Exemplo n.º 29
0
app.once('ready', function () {
  // The chrome-extension: can map a extension URL request to real file path.
  const chromeExtensionHandler = function (request, callback) {
    const parsed = url.parse(request.url)
    if (!parsed.hostname || !parsed.path) return callback()

    const manifest = manifestMap[parsed.hostname]
    if (!manifest) return callback()

    if (parsed.path === '/_generated_background_page.html' &&
        backgroundPages[parsed.hostname]) {
      return callback({
        mimeType: 'text/html',
        data: backgroundPages[parsed.hostname].html
      })
    }

    fs.readFile(path.join(manifest.srcDirectory, parsed.path), function (err, content) {
      if (err) {
        return callback(-6)  // FILE_NOT_FOUND
      } else {
        return callback(content)
      }
    })
  }
  protocol.registerBufferProtocol('chrome-extension', chromeExtensionHandler, function (error) {
    if (error) {
      console.error(`Unable to register chrome-extension protocol: ${error}`)
    }
  })

  // Load persisted extensions.
  loadedExtensionsPath = path.join(app.getPath('userData'), 'DevTools Extensions')
  try {
    const loadedExtensions = JSON.parse(fs.readFileSync(loadedExtensionsPath))
    if (Array.isArray(loadedExtensions)) {
      for (const srcDirectory of loadedExtensions) {
        // Start background pages and set content scripts.
        const manifest = getManifestFromPath(srcDirectory)
        loadExtension(manifest)
      }
    }
  } catch (error) {
    // Ignore error
  }

  // The public API to add/remove extensions.
  BrowserWindow.addDevToolsExtension = function (srcDirectory) {
    const manifest = getManifestFromPath(srcDirectory)
    if (manifest) {
      for (const win of BrowserWindow.getAllWindows()) {
        loadDevToolsExtensions(win, [manifest])
      }
      return manifest.name
    }
  }
  BrowserWindow.removeDevToolsExtension = function (name) {
    const manifest = manifestNameMap[name]
    if (!manifest) return

    removeBackgroundPages(manifest)
    removeContentScripts(manifest)
    delete manifestMap[manifest.extensionId]
    delete manifestNameMap[name]
  }

  // Load extensions automatically when devtools is opened.
  const init = BrowserWindow.prototype._init
  BrowserWindow.prototype._init = function () {
    init.call(this)
    hookWindowForTabEvents(this)
    this.webContents.on('devtools-opened', () => {
      loadDevToolsExtensions(this, objectValues(manifestMap))
    })
  }
})
Exemplo n.º 30
0
const { protocol } = require('electron');

protocol.registerHttpProtocol(
  'mist',
  (request, callback) => {
    console.log(
      request.url.indexOf('mist://interface') !== -1
        ? global.interfaceAppUrl + request.url.replace('mist://interface', '')
        : ''
    );

    const call = {
      url:
        request.url.indexOf('mist://interface') !== -1
          ? global.interfaceAppUrl + request.url.replace('mist://interface', '')
          : '',
      method: request.method,
      referrer: request.referrer
    };

    callback(call);
  },
  error => {
    if (error) {
      console.error('Failed to register protocol');
    }
  }
);