<commit_before>/*
 * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 * brackets-xunit - a brackets extension to run various unit test frameworks
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global brackets, define, $, window, Mustache */

define(function (require, exports, module) {
    'use strict';

    var AppInit             = brackets.getModule("utils/AppInit"),
        CommandManager      = brackets.getModule("command/CommandManager"),
        Dialogs             = brackets.getModule("widgets/Dialogs"),
        ExtensionUtils      = brackets.getModule("utils/ExtensionUtils"),
        FileUtils           = brackets.getModule("file/FileUtils"),
        Menus               = brackets.getModule("command/Menus"),
        NativeFileSystem    = brackets.getModule("file/NativeFileSystem").NativeFileSystem,
        NodeConnection      = brackets.getModule("utils/NodeConnection"),
        DocumentManager     = brackets.getModule("document/DocumentManager"),
        ProjectManager      = brackets.getModule("project/ProjectManager");

    var moduledir           = FileUtils.getNativeModuleDirectoryPath(module),
        jasmineReportEntry  = new NativeFileSystem.FileEntry(moduledir + '/generated/jasmineReport.html'),
        qunitReportEntry    = new NativeFileSystem.FileEntry(moduledir + '/generated/qUnitReport.html'),
        COMMAND_ID          = "BracketsXUnit.BracketsXUnit",
        YUITEST_CMD         = "yuitest_cmd",
        JASMINETEST_CMD     = "jasminetest_cmd",
        QUNITTEST_CMD       = "qunit_cmd",
        projectMenu         = Menus.getContextMenu(Menus.ContextMenuIds.PROJECT_MENU),
        workingsetMenu      = Menus.getContextMenu(Menus.ContextMenuIds.WORKING_SET_MENU),
        nodeConnection      = null;

    // Execute YUI test
    function runYUI() {
        var entry = ProjectManager.getSelectedItem();
        if (entry === undefined) {
            entry = DocumentManager.getCurrentDocument().file;
        }
        var data = { filename : entry.name,
                     title : 'YUI test - ' + entry.name,
                     templatedir : moduledir,
                     contents : DocumentManager.getCurrentDocument().getText()
                   };
        var template = require("text!templates/yui.html");
        var html = Mustache.render(template, data);
        var resultWindow = window.open('about:blank', null, 'width=600,height=200');
        resultWindow.document.write(html);
        resultWindow.focus();
    }

    // Execute Jasmine test
    function runJasmine() {
        var entry = ProjectManager.getSelectedItem();
        if (entry === undefined) {
            entry = DocumentManager.getCurrentDocument().file;
        }
        var dir = entry.fullPath.substring(0, entry.fullPath.lastIndexOf('/') + 1);
        var contents = DocumentManager.getCurrentDocument().getText(),
            includes = '';

        if (contents.match(/brackets-xunit:\s*includes=/)) {
            var includestr = contents.match(/brackets-xunit:\s*includes=[A-Za-z0-9,\._\-\/]*/)[0];
            includestr = includestr.substring(includestr.indexOf('=') + 1);
            var includedata = includestr.split(',');
            var i;
            for (i = 0; i < includedata.length; i++) {
                includes = includes + '<script src="' + dir + includedata[i] + '"></script>\n';
            }
        }
        var data = { filename : entry.name,
                     title : 'Jasmine test - ' + entry.name,
                     includes : includes,
                     contents : DocumentManager.getCurrentDocument().getText()
                   };
        var template = require("text!templates/jasmine.html");
        var html = Mustache.render(template, data);
        FileUtils.writeText(jasmineReportEntry, html).done(function () {
            var report = window.open(jasmineReportEntry.fullPath);
            report.focus();
        });
    }

    // Execute QUnit test
    function runQUnit() {
        var entry = ProjectManager.getSelectedItem();
        var f = entry.fullPath;
        if (entry === null) {
            entry = DocumentManager.getCurrentDocument();
            f = entry.fullPath;
        }
        var fname = DocumentManager.getCurrentDocument().filename;
        var data = { filename : entry.name,
                     title : 'QUnit test - ' + entry.name,
                     templatedir : moduledir,
                     contents : DocumentManager.getCurrentDocument().getText(),
                     testSrcURL: "file://localhost" + f
                   };
        var template = require("text!templates/qunit.html");
        var html = Mustache.render(template, data);
        // write generated test report to file on disk
        FileUtils.writeText(qunitReportEntry, html).done(function () {
            // launch new window with generated report
            var report = window.open(qunitReportEntry.fullPath);
            report.focus();
        });
    }

    // determine if a file is a known test type
    // first look for brackets-xunit: [type], takes precedence
    // next look for distinguishing clues in the file:
    //   YUI: 'YUI(' and 'Test.runner.test'
    //   jasmine: 'describe' and 'it'
    //   QUnit: 'test()' and 'it()'
    // todo: unit test this function
    function determineFileType(fileEntry) {
        if (fileEntry) {
            var text = DocumentManager.getCurrentDocument().getText();
            if (text.match(/brackets-xunit:\s*yui/i) !== null) {
                return "yui";
            } else if (text.match(/brackets-xunit:\s*jasmine/i) !== null) {
                return "jasmine";
            } else if (text.match(/brackets-xunit:\s*qunit/i) !== null) {
                return "qunit";
            } else if (text.match(/YUI\s*\(/) && text.match(/Test\.Runner\.run\s*\(/)) {
                return "yui";
            } else if (text.match(/describe\s*\(/) && text.match(/it\s*\(/)) {
                return "jasmine";
            } else if (text.match(/test\s*\(/) && text.match(/ok\s*\(/)) {
                return "qunit";
            }
        }
        return "unknown";
    }

    // Register commands as right click menu items
    CommandManager.register("Run YUI Unit Test", YUITEST_CMD, function () {
        runYUI();
    });
    CommandManager.register("Run Jasmine xUnit Test", JASMINETEST_CMD, function () {
        runJasmine();
    });
    CommandManager.register("Run QUnit xUnit Test", QUNITTEST_CMD, function () {
        runQUnit();
    });

    // Determine type of test for selected item in project
    $(projectMenu).on("beforeContextMenuOpen", function (evt) {
        var selectedEntry = ProjectManager.getSelectedItem();
        projectMenu.removeMenuItem(YUITEST_CMD);
        projectMenu.removeMenuItem(JASMINETEST_CMD);
        projectMenu.removeMenuItem(QUNITTEST_CMD);

        var type = determineFileType(selectedEntry);

        if (type === "yui") {
            projectMenu.addMenuItem(YUITEST_CMD, "", Menus.LAST);
        } else if (type === "jasmine") {
            projectMenu.addMenuItem(JASMINETEST_CMD, "", Menus.LAST);
        } else if (type === "qunit") {
            projectMenu.addMenuItem(QUNITTEST_CMD, "", Menus.LAST);
        }
    });

    // Determine type of test for selected item in working set
    $(workingsetMenu).on("beforeContextMenuOpen", function (evt) {
        var selectedEntry = DocumentManager.getCurrentDocument().file;
        workingsetMenu.removeMenuItem(YUITEST_CMD);
        workingsetMenu.removeMenuItem(JASMINETEST_CMD);
        workingsetMenu.removeMenuItem(QUNITTEST_CMD);

        var type = determineFileType(selectedEntry);

        if (type === "yui") {
            workingsetMenu.addMenuItem(YUITEST_CMD, "", Menus.LAST);
        } else if (type === "jasmine") {
            workingsetMenu.addMenuItem(JASMINETEST_CMD, "", Menus.LAST);
        } else if (type === "qunit") {
            workingsetMenu.addMenuItem(QUNITTEST_CMD, "", Menus.LAST);
        }
    });

});
<commit_msg>add detection and menu support for test262<commit_after>/*
 * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 * brackets-xunit - a brackets extension to run various unit test frameworks
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global brackets, define, $, window, Mustache */

define(function (require, exports, module) {
    'use strict';

    var AppInit             = brackets.getModule("utils/AppInit"),
        CommandManager      = brackets.getModule("command/CommandManager"),
        Dialogs             = brackets.getModule("widgets/Dialogs"),
        ExtensionUtils      = brackets.getModule("utils/ExtensionUtils"),
        FileUtils           = brackets.getModule("file/FileUtils"),
        Menus               = brackets.getModule("command/Menus"),
        NativeFileSystem    = brackets.getModule("file/NativeFileSystem").NativeFileSystem,
        NodeConnection      = brackets.getModule("utils/NodeConnection"),
        DocumentManager     = brackets.getModule("document/DocumentManager"),
        ProjectManager      = brackets.getModule("project/ProjectManager");

    var moduledir           = FileUtils.getNativeModuleDirectoryPath(module),
        jasmineReportEntry  = new NativeFileSystem.FileEntry(moduledir + '/generated/jasmineReport.html'),
        qunitReportEntry    = new NativeFileSystem.FileEntry(moduledir + '/generated/qUnitReport.html'),
        COMMAND_ID          = "BracketsXUnit.BracketsXUnit",
        YUITEST_CMD         = "yuitest_cmd",
        JASMINETEST_CMD     = "jasminetest_cmd",
        QUNITTEST_CMD       = "qunit_cmd",
        TEST262TEST_CMD     = "test262_cmd",
        projectMenu         = Menus.getContextMenu(Menus.ContextMenuIds.PROJECT_MENU),
        workingsetMenu      = Menus.getContextMenu(Menus.ContextMenuIds.WORKING_SET_MENU),
        nodeConnection      = null;

    // Execute YUI test
    function runYUI() {
        var entry = ProjectManager.getSelectedItem();
        if (entry === undefined) {
            entry = DocumentManager.getCurrentDocument().file;
        }
        var data = { filename : entry.name,
                     title : 'YUI test - ' + entry.name,
                     templatedir : moduledir,
                     contents : DocumentManager.getCurrentDocument().getText()
                   };
        var template = require("text!templates/yui.html");
        var html = Mustache.render(template, data);
        var resultWindow = window.open('about:blank', null, 'width=600,height=200');
        resultWindow.document.write(html);
        resultWindow.focus();
    }

    // Execute Jasmine test
    function runJasmine() {
        var entry = ProjectManager.getSelectedItem();
        if (entry === undefined) {
            entry = DocumentManager.getCurrentDocument().file;
        }
        var dir = entry.fullPath.substring(0, entry.fullPath.lastIndexOf('/') + 1);
        var contents = DocumentManager.getCurrentDocument().getText(),
            includes = '';

        if (contents.match(/brackets-xunit:\s*includes=/)) {
            var includestr = contents.match(/brackets-xunit:\s*includes=[A-Za-z0-9,\._\-\/]*/)[0];
            includestr = includestr.substring(includestr.indexOf('=') + 1);
            var includedata = includestr.split(',');
            var i;
            for (i = 0; i < includedata.length; i++) {
                includes = includes + '<script src="' + dir + includedata[i] + '"></script>\n';
            }
        }
        var data = { filename : entry.name,
                     title : 'Jasmine test - ' + entry.name,
                     includes : includes,
                     contents : DocumentManager.getCurrentDocument().getText()
                   };
        var template = require("text!templates/jasmine.html");
        var html = Mustache.render(template, data);
        FileUtils.writeText(jasmineReportEntry, html).done(function () {
            var report = window.open(jasmineReportEntry.fullPath);
            report.focus();
        });
    }

    // Execute QUnit test
    function runQUnit() {
        var entry = ProjectManager.getSelectedItem();
        var f = entry.fullPath;
        if (entry === null) {
            entry = DocumentManager.getCurrentDocument();
            f = entry.fullPath;
        }
        var fname = DocumentManager.getCurrentDocument().filename;
        var data = { filename : entry.name,
                     title : 'QUnit test - ' + entry.name,
                     templatedir : moduledir,
                     contents : DocumentManager.getCurrentDocument().getText(),
                     testSrcURL: "file://localhost" + f
                   };
        var template = require("text!templates/qunit.html");
        var html = Mustache.render(template, data);
        // write generated test report to file on disk
        FileUtils.writeText(qunitReportEntry, html).done(function () {
            // launch new window with generated report
            var report = window.open(qunitReportEntry.fullPath);
            report.focus();
        });
    }

    // Execute test262 test
    function runTest262() {
        var entry = ProjectManager.getSelectedItem();
        if (entry === null) {
            entry = DocumentManager.getCurrentDocument();
        }
        var path = entry.fullPath;
        console.log("running file: " + path);
    }

    // determine if file is test262
    // look at file path for a test directory
    // from the test directory go back one level and look
    // for existance of tools/packaging/test262.py
    // parameter: string of the test file name
    // returns: a deferred object, result will be the base directory from where
    //          tools/packaging/test262.py can be added to find the python test runner
    function determineTest262FileType(path) {
        if (path.indexOf('/test/') === -1) {
            return undefined;
        }
        var base = path.substring(0, path.lastIndexOf('/test/'));
        var deferred = $.Deferred();
        NativeFileSystem.resolveNativeFileSystemPath(base + '/tools/packaging/test262.py', function (entry) {
            deferred.resolve(base);
        }, function (err) {
            deferred.resolve();
        });
        return deferred.promise();
    }

    // determine if a file is a known test type
    // first look for brackets-xunit: [type], takes precedence
    // next look for distinguishing clues in the file:
    //   YUI: 'YUI(' and 'Test.runner.test'
    //   jasmine: 'describe' and 'it'
    //   QUnit: 'test()' and 'it()'
    //   test262: look at path for test directory then check for
    //           ../tools/packaging/test262.py
    // todo: unit test this function
    function determineFileType(fileEntry) {
        if (fileEntry) {
            var text = DocumentManager.getCurrentDocument().getText();
            if (text.match(/brackets-xunit:\s*yui/i) !== null) {
                return "yui";
            } else if (text.match(/brackets-xunit:\s*jasmine/i) !== null) {
                return "jasmine";
            } else if (text.match(/brackets-xunit:\s*qunit/i) !== null) {
                return "qunit";
            } else if (text.match(/brackets-xunit:\s*test262/i) !== null) {
                return "test262";
            } else if (text.match(/YUI\s*\(/) && text.match(/Test\.Runner\.run\s*\(/)) {
                return "yui";
            } else if (text.match(/describe\s*\(/) && text.match(/it\s*\(/)) {
                return "jasmine";
            } else if (text.match(/test\s*\(/) && text.match(/ok\s*\(/)) {
                return "qunit";
            }
        }
        return "unknown";
    }

    // Register commands as right click menu items
    CommandManager.register("Run YUI Unit Test", YUITEST_CMD, function () {
        runYUI();
    });
    CommandManager.register("Run Jasmine xUnit Test", JASMINETEST_CMD, function () {
        runJasmine();
    });
    CommandManager.register("Run QUnit xUnit Test", QUNITTEST_CMD, function () {
        runQUnit();
    });
    CommandManager.register("Run test262 xUnit Test", TEST262TEST_CMD, function () {
        runTest262();
    });

    // Determine type of test for selected item in project
    $(projectMenu).on("beforeContextMenuOpen", function (evt) {
        var selectedEntry = ProjectManager.getSelectedItem();
        projectMenu.removeMenuItem(YUITEST_CMD);
        projectMenu.removeMenuItem(JASMINETEST_CMD);
        projectMenu.removeMenuItem(QUNITTEST_CMD);
        projectMenu.removeMenuItem(TEST262TEST_CMD);

        var type = determineFileType(selectedEntry);
        if (type === "yui") {
            projectMenu.addMenuItem(YUITEST_CMD, "", Menus.LAST);
        } else if (type === "jasmine") {
            projectMenu.addMenuItem(JASMINETEST_CMD, "", Menus.LAST);
        } else if (type === "qunit") {
            projectMenu.addMenuItem(QUNITTEST_CMD, "", Menus.LAST);
        } else if (type === "test262") {
            projectMenu.addMenuItem(TEST262TEST_CMD, "", Menus.LAST);
        } else {
            var promise = determineTest262FileType(selectedEntry.fullPath);
            if ( promise != undefined ) {
                promise.done( function(path) {
                    if (path != undefined) {
                        projectMenu.addMenuItem(TEST262TEST_CMD, "", Menus.LAST);
                    }
                });
            }
        }
    });

    // Determine type of test for selected item in working set
    $(workingsetMenu).on("beforeContextMenuOpen", function (evt) {
        var selectedEntry = DocumentManager.getCurrentDocument().file;
        workingsetMenu.removeMenuItem(YUITEST_CMD);
        workingsetMenu.removeMenuItem(JASMINETEST_CMD);
        workingsetMenu.removeMenuItem(QUNITTEST_CMD);
        workingsetMenu.removeMenuItem(TEST262TEST_CMD);

        var type = determineFileType(selectedEntry);

        if (type === "yui") {
            workingsetMenu.addMenuItem(YUITEST_CMD, "", Menus.LAST);
        } else if (type === "jasmine") {
            workingsetMenu.addMenuItem(JASMINETEST_CMD, "", Menus.LAST);
        } else if (type === "qunit") {
            workingsetMenu.addMenuItem(QUNITTEST_CMD, "", Menus.LAST);
        } else if (type === "test262") {
            workingsetMenu.addMenuItem(TEST262TEST_CMD, "", Menus.LAST);
        } else {
            var promise = determineTest262FileType(selectedEntry.fullPath);
            if ( promise != undefined ) {
                promise.done( function(path) {
                    if (path != undefined) {
                        workingsetMenu.addMenuItem(TEST262TEST_CMD, "", Menus.LAST);
                    }
                });
            }
        }
    });

});
<|endoftext|>


<commit_before>"use strict";

// Check that the deps in node_modules match what's in package.json.
var safestart = require('safestart');
safestart(__dirname);

var fs = require('fs');
var path = require('path');
var argv = require('yargs').argv;

var app = require('app');  // Module to control application life.
var electron = require('electron');
var BrowserWindow = electron.BrowserWindow;  // Module to create native browser window.
var request = require('request');
var os = require('os');
var autoUpdater = require('auto-updater');
var menu = require('menu');
var tray = require('tray');
var ipcMain = require('ipc-main');
var ini = require('ini');
var dialog = require('electron').dialog;

var launched_from_installer = false;
var platform = os.platform();
switch(platform) {
  case "darwin":
    platform = "mac";
}
var version = app.getVersion();
var trayMenu = null;
var subpy = null;

var open_url = null; // This is for if someone opens a URL before the client is open

if (argv.userData) {
  try {
    app.setPath('userData', argv.userData);
  } catch (e) {
    throw new Error('The passed in userData directory does not appear to be valid: ' + e);
  }
}

var handleStartupEvent = function() {
  if (process.platform !== 'win32') {
    return false;
  }

  var squirrelCommand = process.argv[1];

  function exeSquirrelCommand(args, cb) {
    var updateDotExe = path.resolve(path.dirname(process.execPath), '..', 'update.exe');
    var child = require('child_process').spawn(updateDotExe, args, { detached: true });
    child.on('close', function() {
       cb();
    });
  };

  function install(cb) {
      var target = path.basename(process.execPath);
      exeSquirrelCommand(["--createShortcut", target], cb);
  };

  function uninstall(cb) {
      var target = path.basename(process.execPath);
      exeSquirrelCommand(["--removeShortcut", target], cb);
  };

  switch (squirrelCommand) {
    case '--squirrel-install':
          install(app.quit);

    case '--squirrel-updated':

      // Always quit when done
      app.quit();
      return true;

    case '--squirrel-uninstall':
      // Always quit when done
      uninstall(app.quit);

      return true;
    case '--squirrel-obsolete':
      // This is called on the outgoing version of your app before
      // we update to the new version - it's the opposite of
      // --squirrel-updated
      app.quit();
      return true;
  }
};

if (handleStartupEvent()) {
  console.log('Client started on Windows...');
}

// Set daemon binary name
var daemon = "openbazaard.exe";
if(platform == "mac" || platform == "linux") {
  daemon = "openbazaard";
}

var serverPath = __dirname + path.sep + '..' + path.sep + 'OpenBazaar-Server' + path.sep;
var serverOut = '';

var start_local_server = function() {
  if(fs.existsSync(serverPath)) {

    var random_port = Math.floor((Math.random() * 10000) + 30000);

    subpy = require('child_process').spawn(serverPath + daemon, ['start', '--testnet', '--loglevel', 'debug', '-p', random_port], {
      detach: false,
      cwd: __dirname + path.sep + '..' + path.sep + 'OpenBazaar-Server'
    });

    var stdout = '';
    var stderr = '';

    subpy.stdout.on('data', function (buf) {
      console.log('[STR] stdout "%s"', String(buf));
      stdout += buf;
      serverOut += buf;
    });
    subpy.stderr.on('data', function (buf) {
      console.log('[STR] stderr "%s"', String(buf));
      stderr += buf;
    });
    subpy.on('error', function (err) {
      console.log('Python error %s', String(err));
    });
    subpy.on('close', function (code) {
      console.log('exited with ' + code);
      console.log('[END] stdout "%s"', stdout);
      console.log('[END] stderr "%s"', stderr);
    });
    subpy.unref();
  }
  if (fs.existsSync(__dirname + path.sep + '..' + path.sep + 'gpg')) {
       process.env.PATH = __dirname + path.sep + '..' + path.sep + 'gpg' + path.sep + 'pub' + path.sep + ';' + process.env.PATH;
   }
};

// Check if we need to kick off the python server-daemon (Desktop app)
if(fs.existsSync(__dirname + path.sep + ".." + path.sep + "OpenBazaar-Server" + path.sep + daemon)) {
  launched_from_installer = true;
  console.log('Starting OpenBazaar Server');
  start_local_server();
}

// Report crashes to our server.
//require('crash-reporter').start();

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is GCed.
var mainWindow = null;

// Quit when all windows are closed.
app.on('window-all-closed', function() {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (platform != 'mac') {
    app.quit();
  }
});

// You can use 'before-quit' instead of (or with) the close event
app.on('before-quit', function (e) {
    // Handle menu-item or keyboard shortcut quit here
    console.log('Closing Application');
    if(launched_from_installer) {
      console.log('Shutting down server daemon');
      subpy.kill();
    }
});

app.commandLine.appendSwitch('ignore-certificate-errors', true);

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {

  // Application Menu
  var appMenu = menu.buildFromTemplate([
    {
      label: 'OpenBazaar',
      submenu: [
        {
          label: 'Quit OpenBazaar',
          accelerator: 'CmdOrCtrl+Q',
          click: function() {
            app.quit();
          }
        }
      ]
    },
    {
      label: 'Edit',
      submenu: [
        { label: "Undo", accelerator: "CmdOrCtrl+Z", selector: "undo:" },
        { label: "Redo", accelerator: "Shift+CmdOrCtrl+Z", selector: "redo:" },
        { type: "separator" },
        { label: "Cut", accelerator: "CmdOrCtrl+X", selector: "cut:" },
        { label: "Copy", accelerator: "CmdOrCtrl+C", selector: "copy:" },
        { label: "Paste", accelerator: "CmdOrCtrl+V", selector: "paste:" },
        { label: "Select All", accelerator: "CmdOrCtrl+A", selector: "selectAll:" }
      ]
    },
    {
      label: 'View',
      submenu: [
        {
          label: 'Reload',
          accelerator: 'CmdOrCtrl+R',
          click: function(item, focusedWindow) {
            if (focusedWindow) {
              focusedWindow.reload();
            }
          }
        },
        {
          label: 'Toggle Developer Tools',
          accelerator: (function() {
            if (platform == 'mac') {
              return 'Alt+Command+I';
            } else {
              return 'Ctrl+Shift+I';
            }
          })(),
          click: function(item, focusedWindow) {
            if (focusedWindow) {
              focusedWindow.toggleDevTools();
            }
          }
        },
        {
          label: 'Toggle Full Screen',
          accelerator: (function() {
            if (platform == 'mac') {
              return 'Ctrl+Command+F';
            } else {
              return 'Ctrl+Shift+F';
            }
          })(),
          click: function(item, focusedWindow) {
            var fullScreen;

            if (mainWindow) {
              fullScreen = !mainWindow.isFullScreen();
              mainWindow.setFullScreen(fullScreen);

              if (fullScreen) {
                mainWindow.webContents.send('fullscreen-enter');
              } else {
                mainWindow.webContents.send('fullscreen-exit');
              }
            }
          }
        },
      ]
    },
    {
    label: 'Window',
    submenu: [
      {
        label: 'Minimize',
        accelerator: 'Command+M',
        selector: 'performMiniaturize:'
      },
      {
        label: 'Close',
        accelerator: 'Command+W',
        selector: 'performClose:'
      },
      {
        type: 'separator'
      },
      {
        label: 'Bring All to Front',
        selector: 'arrangeInFront:'
      }
    ]
  }
  ]);
  menu.setApplicationMenu(appMenu);

  // put logic here to set tray icon based on OS
  var osTrayIcon = 'openbazaar-mac-system-tray.png';

  trayMenu = new tray(__dirname + '/imgs/' + osTrayIcon);
  var contextMenu = menu.buildFromTemplate([
    {
      label: 'Start Local Server', type: 'normal', click: function () {
      start_local_server();
    }
    },
    {
      label: 'Shutdown Local Server', type: 'normal', click: function () {
      request('http://localhost:18469/api/v1/shutdown', function (error, response, body) {
        if (!error && response.statusCode == 200) {
          console.log('Shutting down server');
        } else {
          console.log('Server does not seem to be running.');
        }
      });
    }
    },
    {type: 'separator'},
    {label: 'View Debug Log', type: 'normal', click: function() {
      var debugPath = serverPath + path.sep + 'debug.txt';

      fs.writeFile(debugPath, serverOut, (err) => {
        if (err) {
          dialog.showErrorBox('Unable To Open Debug Log',
            'There was an error and we are unable to open the server debug log at this time.\n\n' + err);
        }

        require('open')(debugPath);
      });
    }},
    {type: 'separator'},
    {
      label: 'Quit', type: 'normal', accelerator: 'Command+Q', click: function () {
      app.quit();
    }
    }
  ]);

  trayMenu.setContextMenu(contextMenu);

  // Create the browser window.
  mainWindow = new BrowserWindow({
    "width": 1200,
    "height": 720,
    "min-width": 1024,
    "min-height": 700,
    "center": true,
    "title": "OpenBazaar",
    "frame": false,
    "icon": "imgs/openbazaar-icon.png",
    "title-bar-style": "hidden"
  });

  // and load the index.html of the app.
  if(open_url) {
    mainWindow.loadURL('file://' + __dirname + '/index.html' + open_url);
  } else {
    mainWindow.loadURL('file://' + __dirname + '/index.html');
  }

  // Open the devtools.
  // Uncomment if you want tools to open on startup
  // mainWindow.openDevTools({detach: true});

  // 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;

    if(subpy) {
      subpy.kill('SIGHUP');
    }
  });

  mainWindow.on('close', function() {
    app.quit();
  });

  app.on('activate', function() {
    mainWindow.show();
  });

  autoUpdater.on("error", function(err, msg) {
    console.log(msg); //print msg , you can find the cash reason.
  });

  autoUpdater.on("update-not-available", function(msg) {
    mainWindow.webContents.executeJavaScript("console.log('Update not available! Your software is up to date.')");
  });

  autoUpdater.on("update-available", function() {
    mainWindow.webContents.executeJavaScript("console.log('Update available! Downloading now...')");
  });

  autoUpdater.on("update-downloaded", function(e, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
    mainWindow.webContents.executeJavaScript("console.log('Update downloaded." + updateUrl + "')");
    mainWindow.webContents.executeJavaScript('$(".js-softwareUpdate").removeClass("softwareUpdateHidden");');
  });

  ipcMain.on('installUpdate', function(event) {
    console.log('Installing Update');
    autoUpdater.quitAndInstall();
  });

  var feedURL = 'http://updates.openbazaar.org:5000/update/' + platform + '/' + version;
  autoUpdater.setFeedURL(feedURL);
  mainWindow.webContents.executeJavaScript("console.log('Checking for new versions at " + feedURL + " ...')");
  autoUpdater.checkForUpdates();

});

app.on('open-url', function(event, uri) {
  var split_uri = uri.split('://');
  uri = split_uri[1];

  global.externalRoute = uri;

  if (mainWindow) {
    // if our app router is fully loaded it will process the event sent below, otherwise
    // the global.externalRoute will be used
    mainWindow.webContents.send('external-route', uri);
  }

  event.preventDefault();
});<commit_msg>changing fullscreen shortcut to f11 on non-mac platforms<commit_after>"use strict";

// Check that the deps in node_modules match what's in package.json.
var safestart = require('safestart');
safestart(__dirname);

var fs = require('fs');
var path = require('path');
var argv = require('yargs').argv;

var app = require('app');  // Module to control application life.
var electron = require('electron');
var BrowserWindow = electron.BrowserWindow;  // Module to create native browser window.
var request = require('request');
var os = require('os');
var autoUpdater = require('auto-updater');
var menu = require('menu');
var tray = require('tray');
var ipcMain = require('ipc-main');
var ini = require('ini');
var dialog = require('electron').dialog;

var launched_from_installer = false;
var platform = os.platform();
switch(platform) {
  case "darwin":
    platform = "mac";
}
var version = app.getVersion();
var trayMenu = null;
var subpy = null;

var open_url = null; // This is for if someone opens a URL before the client is open

if (argv.userData) {
  try {
    app.setPath('userData', argv.userData);
  } catch (e) {
    throw new Error('The passed in userData directory does not appear to be valid: ' + e);
  }
}

var handleStartupEvent = function() {
  if (process.platform !== 'win32') {
    return false;
  }

  var squirrelCommand = process.argv[1];

  function exeSquirrelCommand(args, cb) {
    var updateDotExe = path.resolve(path.dirname(process.execPath), '..', 'update.exe');
    var child = require('child_process').spawn(updateDotExe, args, { detached: true });
    child.on('close', function() {
       cb();
    });
  };

  function install(cb) {
      var target = path.basename(process.execPath);
      exeSquirrelCommand(["--createShortcut", target], cb);
  };

  function uninstall(cb) {
      var target = path.basename(process.execPath);
      exeSquirrelCommand(["--removeShortcut", target], cb);
  };

  switch (squirrelCommand) {
    case '--squirrel-install':
          install(app.quit);

    case '--squirrel-updated':

      // Always quit when done
      app.quit();
      return true;

    case '--squirrel-uninstall':
      // Always quit when done
      uninstall(app.quit);

      return true;
    case '--squirrel-obsolete':
      // This is called on the outgoing version of your app before
      // we update to the new version - it's the opposite of
      // --squirrel-updated
      app.quit();
      return true;
  }
};

if (handleStartupEvent()) {
  console.log('Client started on Windows...');
}

// Set daemon binary name
var daemon = "openbazaard.exe";
if(platform == "mac" || platform == "linux") {
  daemon = "openbazaard";
}

var serverPath = __dirname + path.sep + '..' + path.sep + 'OpenBazaar-Server' + path.sep;
var serverOut = '';

var start_local_server = function() {
  if(fs.existsSync(serverPath)) {

    var random_port = Math.floor((Math.random() * 10000) + 30000);

    subpy = require('child_process').spawn(serverPath + daemon, ['start', '--testnet', '--loglevel', 'debug', '-p', random_port], {
      detach: false,
      cwd: __dirname + path.sep + '..' + path.sep + 'OpenBazaar-Server'
    });

    var stdout = '';
    var stderr = '';

    subpy.stdout.on('data', function (buf) {
      console.log('[STR] stdout "%s"', String(buf));
      stdout += buf;
      serverOut += buf;
    });
    subpy.stderr.on('data', function (buf) {
      console.log('[STR] stderr "%s"', String(buf));
      stderr += buf;
    });
    subpy.on('error', function (err) {
      console.log('Python error %s', String(err));
    });
    subpy.on('close', function (code) {
      console.log('exited with ' + code);
      console.log('[END] stdout "%s"', stdout);
      console.log('[END] stderr "%s"', stderr);
    });
    subpy.unref();
  }
  if (fs.existsSync(__dirname + path.sep + '..' + path.sep + 'gpg')) {
       process.env.PATH = __dirname + path.sep + '..' + path.sep + 'gpg' + path.sep + 'pub' + path.sep + ';' + process.env.PATH;
   }
};

// Check if we need to kick off the python server-daemon (Desktop app)
if(fs.existsSync(__dirname + path.sep + ".." + path.sep + "OpenBazaar-Server" + path.sep + daemon)) {
  launched_from_installer = true;
  console.log('Starting OpenBazaar Server');
  start_local_server();
}

// Report crashes to our server.
//require('crash-reporter').start();

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is GCed.
var mainWindow = null;

// Quit when all windows are closed.
app.on('window-all-closed', function() {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (platform != 'mac') {
    app.quit();
  }
});

// You can use 'before-quit' instead of (or with) the close event
app.on('before-quit', function (e) {
    // Handle menu-item or keyboard shortcut quit here
    console.log('Closing Application');
    if(launched_from_installer) {
      console.log('Shutting down server daemon');
      subpy.kill();
    }
});

app.commandLine.appendSwitch('ignore-certificate-errors', true);

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {

  // Application Menu
  var appMenu = menu.buildFromTemplate([
    {
      label: 'OpenBazaar',
      submenu: [
        {
          label: 'Quit OpenBazaar',
          accelerator: 'CmdOrCtrl+Q',
          click: function() {
            app.quit();
          }
        }
      ]
    },
    {
      label: 'Edit',
      submenu: [
        { label: "Undo", accelerator: "CmdOrCtrl+Z", selector: "undo:" },
        { label: "Redo", accelerator: "Shift+CmdOrCtrl+Z", selector: "redo:" },
        { type: "separator" },
        { label: "Cut", accelerator: "CmdOrCtrl+X", selector: "cut:" },
        { label: "Copy", accelerator: "CmdOrCtrl+C", selector: "copy:" },
        { label: "Paste", accelerator: "CmdOrCtrl+V", selector: "paste:" },
        { label: "Select All", accelerator: "CmdOrCtrl+A", selector: "selectAll:" }
      ]
    },
    {
      label: 'View',
      submenu: [
        {
          label: 'Reload',
          accelerator: 'CmdOrCtrl+R',
          click: function(item, focusedWindow) {
            if (focusedWindow) {
              focusedWindow.reload();
            }
          }
        },
        {
          label: 'Toggle Developer Tools',
          accelerator: (function() {
            if (platform == 'mac') {
              return 'Alt+Command+I';
            } else {
              return 'Ctrl+Shift+I';
            }
          })(),
          click: function(item, focusedWindow) {
            if (focusedWindow) {
              focusedWindow.toggleDevTools();
            }
          }
        },
        {
          label: 'Toggle Full Screen',
          accelerator: (function() {
            if (platform == 'mac') {
              return 'Ctrl+Command+F';
            } else {
              return 'F11';
            }
          })(),
          click: function(item, focusedWindow) {
            var fullScreen;

            if (mainWindow) {
              fullScreen = !mainWindow.isFullScreen();
              mainWindow.setFullScreen(fullScreen);

              if (fullScreen) {
                mainWindow.webContents.send('fullscreen-enter');
              } else {
                mainWindow.webContents.send('fullscreen-exit');
              }
            }
          }
        },
      ]
    },
    {
    label: 'Window',
    submenu: [
      {
        label: 'Minimize',
        accelerator: 'Command+M',
        selector: 'performMiniaturize:'
      },
      {
        label: 'Close',
        accelerator: 'Command+W',
        selector: 'performClose:'
      },
      {
        type: 'separator'
      },
      {
        label: 'Bring All to Front',
        selector: 'arrangeInFront:'
      }
    ]
  }
  ]);
  menu.setApplicationMenu(appMenu);

  // put logic here to set tray icon based on OS
  var osTrayIcon = 'openbazaar-mac-system-tray.png';

  trayMenu = new tray(__dirname + '/imgs/' + osTrayIcon);
  var contextMenu = menu.buildFromTemplate([
    {
      label: 'Start Local Server', type: 'normal', click: function () {
      start_local_server();
    }
    },
    {
      label: 'Shutdown Local Server', type: 'normal', click: function () {
      request('http://localhost:18469/api/v1/shutdown', function (error, response, body) {
        if (!error && response.statusCode == 200) {
          console.log('Shutting down server');
        } else {
          console.log('Server does not seem to be running.');
        }
      });
    }
    },
    {type: 'separator'},
    {label: 'View Debug Log', type: 'normal', click: function() {
      var debugPath = serverPath + path.sep + 'debug.txt';

      fs.writeFile(debugPath, serverOut, (err) => {
        if (err) {
          dialog.showErrorBox('Unable To Open Debug Log',
            'There was an error and we are unable to open the server debug log at this time.\n\n' + err);
        }

        require('open')(debugPath);
      });
    }},
    {type: 'separator'},
    {
      label: 'Quit', type: 'normal', accelerator: 'Command+Q', click: function () {
      app.quit();
    }
    }
  ]);

  trayMenu.setContextMenu(contextMenu);

  // Create the browser window.
  mainWindow = new BrowserWindow({
    "width": 1200,
    "height": 720,
    "min-width": 1024,
    "min-height": 700,
    "center": true,
    "title": "OpenBazaar",
    "frame": false,
    "icon": "imgs/openbazaar-icon.png",
    "title-bar-style": "hidden"
  });

  // and load the index.html of the app.
  if(open_url) {
    mainWindow.loadURL('file://' + __dirname + '/index.html' + open_url);
  } else {
    mainWindow.loadURL('file://' + __dirname + '/index.html');
  }

  // Open the devtools.
  // Uncomment if you want tools to open on startup
  // mainWindow.openDevTools({detach: true});

  // 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;

    if(subpy) {
      subpy.kill('SIGHUP');
    }
  });

  mainWindow.on('close', function() {
    app.quit();
  });

  app.on('activate', function() {
    mainWindow.show();
  });

  autoUpdater.on("error", function(err, msg) {
    console.log(msg); //print msg , you can find the cash reason.
  });

  autoUpdater.on("update-not-available", function(msg) {
    mainWindow.webContents.executeJavaScript("console.log('Update not available! Your software is up to date.')");
  });

  autoUpdater.on("update-available", function() {
    mainWindow.webContents.executeJavaScript("console.log('Update available! Downloading now...')");
  });

  autoUpdater.on("update-downloaded", function(e, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
    mainWindow.webContents.executeJavaScript("console.log('Update downloaded." + updateUrl + "')");
    mainWindow.webContents.executeJavaScript('$(".js-softwareUpdate").removeClass("softwareUpdateHidden");');
  });

  ipcMain.on('installUpdate', function(event) {
    console.log('Installing Update');
    autoUpdater.quitAndInstall();
  });

  var feedURL = 'http://updates.openbazaar.org:5000/update/' + platform + '/' + version;
  autoUpdater.setFeedURL(feedURL);
  mainWindow.webContents.executeJavaScript("console.log('Checking for new versions at " + feedURL + " ...')");
  autoUpdater.checkForUpdates();

});

app.on('open-url', function(event, uri) {
  var split_uri = uri.split('://');
  uri = split_uri[1];

  global.externalRoute = uri;

  if (mainWindow) {
    // if our app router is fully loaded it will process the event sent below, otherwise
    // the global.externalRoute will be used
    mainWindow.webContents.send('external-route', uri);
  }

  event.preventDefault();
});<|endoftext|>


<commit_before>/*global define, document, window */
/*jslint nomen: true */ // this causes JSLint to tolerate "_"
define(['codeMirror', 'inlet', 'd3', 'underscore', './dashboard'], function (CodeMirror, inlet, d3, _, Dashboard) {

    "use strict";

    return {
        /**
         * Initializes the dashboard configurator system.
         * Arguments:
         *
         *  * `editorId` The id of the textArea DOM element that should become the configuration editor.
         *  * `dashboardId` The id of the div DOM element that the dashboard will be injected into.
         */
        init: function (editorId, dashboardId) {
            var editor = document.getElementById(editorId),
                codeMirror = CodeMirror.fromTextArea(editor),
                dashboard = Dashboard.createDashboard(dashboardId),
                invalidJSONConfig = {
                    "layout": {
                        "orientation": "vertical",
                        "children": [ { "name": "vis", "size": 1 } ]
                    },
                    "visualizations": {
                        "vis": {
                            "module": "vis",
                            "bkgColor": "red",
                            "lineColor": "red",
                            "labelText": "Invalid JSON",
                            "labelSize": "41pt"
                        }
                    },
                    "visDivCSS": {
                        "border-style": "solid",
                        "border-width": "2px"
                    }
                };

            window.addEventListener('resize', _.debounce(function () {
                dashboard.update();
            }, 100));

            inlet(codeMirror);
            codeMirror.setOption('mode', 'javascript');
            codeMirror.setSize('100%', '100%');
            d3.text('dashboardConfig.json', function (configJSON) {
                // A flag to prevent redundantly resetting the
                // text every time the use changes it.
                var settingConfig = false;

                codeMirror.setOption('value', configJSON);
                dashboard.setConfig(JSON.parse(configJSON));

                codeMirror.on('change', function () {
                    settingConfig = true;
                    try {
                        // This line will throw if parsing fails
                        dashboard.setConfig(JSON.parse(codeMirror.getValue()));
                    } catch (e) {
                        dashboard.setConfig(invalidJSONConfig);
                    }
                    settingConfig = false;
                });
                dashboard.on('configChanged', function (config) {
                    if (!settingConfig) {
                        codeMirror.setOption('value', JSON.stringify(config, null, 2));
                    }
                });
            });
            return dashboard;
        }
    };
});
<commit_msg>Refactored initialization logic<commit_after>/*global define, document, window */
/*jslint nomen: true */ // this causes JSLint to tolerate "_"
define(['codeMirror', 'inlet', 'd3', 'underscore', './dashboard'], function (CodeMirror, inlet, d3, _, Dashboard) {

    "use strict";

    function init (config, dashboardId, editorId) {
        var dashboard = Dashboard.createDashboard(dashboardId),
            editor = document.getElementById(editorId);
        if (editor) { initEditor(config, dashboard, editor); }
        dashboard.setConfig(config);
        return dashboard;
    }

    function initEditor(config, dashboard, editor){
        var codeMirror = CodeMirror.fromTextArea(editor),
            settingConfig = false,
            invalidJSONConfig = {
                "layout": {
                    "orientation": "vertical",
                    "children": [ { "name": "vis", "size": 1 } ]
                },
                "visualizations": {
                    "vis": {
                        "module": "vis",
                        "bkgColor": "red",
                        "lineColor": "red",
                        "labelText": "Invalid JSON",
                        "labelSize": "41pt"
                    }
                },
                "visDivCSS": {
                    "border-style": "solid",
                    "border-width": "2px"
                }
            };
        inlet(codeMirror);
        codeMirror.setOption('mode', 'javascript');
        codeMirror.setSize('100%', '100%');
        codeMirror.setOption('value', JSON.stringify(config, null, 2));
        codeMirror.on('change', function () {
            settingConfig = true;
            try {
                // This line will throw if parsing fails
                dashboard.setConfig(JSON.parse(codeMirror.getValue()));
            } catch (e) {
                dashboard.setConfig(invalidJSONConfig);
            }
            settingConfig = false;
        });
        dashboard.on('configChanged', function (config) {
            if (!settingConfig) {
                codeMirror.setOption('value', JSON.stringify(config, null, 2));
            }
        });
    }

    return {
        /**
         * Initializes the dashboard configurator system.
         * Arguments:
         *
         *  * `config` The object parsed from the dashboard configuration JSON.
         *  * `editorId` The id of the textArea DOM element that should become the configuration editor.
         *  * `dashboardId` The id of the div DOM element that the dashboard will be injected into.
         */
        init: init
    };
});
<|endoftext|>


<commit_before>var sys     = require("sys"),
    http    = require("http"),
    port    = 8080,
    request = require("request"),
    fs      = require("fs"),
    url     = require("url"),
    $       = require("jquery"),
    uri;

function respond(response, logo) {
  if(logo !== undefined) {
    response.writeHead(302, {'Location': url.resolve(uri, logo)});
    console.log(url.resolve(uri, logo) + '\n');
  } else {
    response.writeHead(404, {"Content-Type": "text/plain"});
    console.log('Fail :(\n')
  }
  response.end();
}

http.createServer(function(webrequest, webresponse) {

uri = webrequest.url.replace(/^\/*/, '');

if (uri == '') {
  fs.readFile('index.html', 'binary', function(err, file) {
    webresponse.writeHead(200, {'Content-Type': 'text/html'});
    webresponse.end(file);
  });
} else if(uri == 'favicon.ico') {
  webresponse.writeHead(301, {'Location': 'http://www.stevelacey.net/favicon.ico'});
} else if(uri == 'robots.txt') {
  respond(webresponse);
} else {
  if(uri.substr(0,4) != 'http') {
    uri = 'http://' + uri;
  }

  console.log(uri);

  request({uri:uri}, function (error, response, html) {
    if(!error && response.statusCode == 200) {
      var imgs = ['#header img:first', '.header img:first', '#logo img', 'h1 img', '.logo img', 'img#logo', 'img.logo', '#banner img:first']; // css
      var inlines = ['#header', '.header', '#logo', '.logo', '#p-logo a', 'h1']; // css
      var divs = ['[#|.]header [#|.]logo', '[#|.][^\\s]*logo[^\\s&^{]*', 'h1', '#title']; // regex
      var stylesheets = ['main', 'style', 'screen', 'global']; // filenames

      // Try imgs
      var logo = $(imgs.join(','), html).attr('src');

      if(logo === undefined) {
        // Check for inline styles
        var inline = $(inlines.join('[style],') + '[style]', html).attr('style');

        if(inline !== undefined) {
          var matches = inline.match(new RegExp("background[^:]*:\\s*url\\s*\\(\\s*[\"|\']*([^\"&^\'&^)]+)"));
          if(matches !== null) {
            logo = matches[1];
          }
        }
      }

      if(logo === undefined) {
        // Check for an image filename similar to the title tag slugified
        var title =  $('title', html).text().toLowerCase().replace(/\s+/g,'-');
        logo = $('img[src$="' + title + '.png"], img[src$="' + title + '.jpg"], img[src$="' + title + '.jpeg"], img[src$="' + title + '.gif"]', html).attr('src');
      }

      if(logo === undefined && url.parse(uri).hostname !== undefined) {
        // Check for an image filename similar to the domain
        var hostname = url.parse(uri).hostname.replace('www.', '');
        var domain = hostname.substring(0,(hostname.indexOf('.')));
        logo = $('img[src$="' + domain + '.png"], img[src$="' + domain + '.jpg"], img[src$="' + domain + '.jpeg"], img[src$="' + domain + '.gif"]', html).attr('src');
      }

      if(logo === undefined) {
        // Try background-images
        if(stylesheet === undefined && $('link[rel="stylesheet"]', html).length == 1) {
          // If there's only one stylesheet assume it as master
          var stylesheet = $('link[rel="stylesheet"]', html).attr('href');
        } else {
          // Check for commonly used main stylesheet names
          for(var i in stylesheets) {
            stylesheets[i] = 'link[rel="stylesheet"][href*="' + stylesheets[i] + '.css"]';
          }

          var stylesheet = $(stylesheets.join(','), html).attr('href');
        }

        if(stylesheet !== undefined) {
          console.log(url.resolve(uri, stylesheet));
          request({uri:url.resolve(uri, stylesheet)}, function (error, response, css) {
            if(!error && response.statusCode == 200) {
              for(var i in divs) {
                var matches = css.match(new RegExp(divs[i] + "\\s*{[^}]*background[^:]*:\\s*url\\s*\\(\\s*[\"|\']*([^\"&^\'&^)&^}]+)"));
                if(matches !== null) {
                  logo = matches[1];
                  break;
                }
              }

              if(logo !== undefined) {
                // Found image in stylesheet
                stylesheet = stylesheet.substring(0,(stylesheet.lastIndexOf('/')) + 1);

                if(stylesheet.substr(0,4) == 'http') {
                  uri = stylesheet;
                } else {
                  uri = url.resolve(uri, stylesheet);
                }

                respond(webresponse, logo);
              } else {
                respond(webresponse);
              }
            }
          })
        } else {
          // Check for an OpenGraph image
          logo = $('meta[property="og:image"]', html).attr('content');

          if(logo === undefined) {
            // Check for an iOS icon
            logo = $('link[rel="apple-touch-icon-precomposed"], link[rel="apple-touch-icon"]', html).attr('href');
          }

          if(logo !== undefined) {
            respond(webresponse, logo);
          } else {
            respond(webresponse);
          }
        }
      } else {
        respond(webresponse, logo);
      }
    } else {
      respond(webresponse);
    }
  })

}

}).listen(port);

console.log('Server listening on port ' + port);
<commit_msg>Started modularising functionality.<commit_after>var sys     = require("sys"),
    http    = require("http"),
    port    = 8080,
    request = require("request"),
    fs      = require("fs"),
    url     = require("url"),
    $       = require("jquery"),
    uri;

http.createServer(function(webrequest, webresponse) {

uri = webrequest.url.replace(/^\/*/, '');

if (uri == '') {
  fs.readFile('index.html', 'binary', function(err, file) {
    webresponse.writeHead(200, {'Content-Type': 'text/html'});
    webresponse.end(file);
  });
} else if(uri == 'favicon.ico') {
  webresponse.writeHead(301, {'Location': 'http://www.stevelacey.net/favicon.ico'});
} else if(uri == 'robots.txt') {
  respond(webresponse);
} else {
  if(uri.substr(0,4) != 'http') {
    uri = 'http://' + uri;
  }

  console.log(uri);

  request({uri:uri}, function (error, response, html) {
    if(!error && response.statusCode == 200) {
      var imgs = ['#header img:first', '.header img:first', '#logo img', 'h1 img', '.logo img', 'img#logo', 'img.logo', '#banner img:first']; // css
      var inlines = ['#header', '.header', '#logo', '.logo', '#p-logo a', 'h1']; // css
      var divs = ['[#|.]header [#|.]logo', '[#|.][^\\s]*logo[^\\s&^{]*', 'h1', '#title']; // regex
      var stylesheets = ['main', 'style', 'screen', 'global']; // filenames

      // Try imgs
      var logo = getImage(html, imgs);

      if(logo === undefined) {
        logo = getInlineStyleImage(html, inlines);
      }

      if(logo === undefined) {
        logo = getImageFromTitle(html);
      }

      if(logo === undefined && url.parse(uri).hostname !== undefined) {
        logo = getImageFromDomain(html);
      }

      if(logo === undefined) {
        // Try background-images
        var stylesheet = getStylesheet(html, stylesheets);

        if(stylesheet !== undefined) {
          console.log(url.resolve(uri, stylesheet));
          request({uri:url.resolve(uri, stylesheet)}, function (error, response, css) {
            if(!error && response.statusCode == 200) {
              for(var i in divs) {
                var matches = css.match(new RegExp(divs[i] + "\\s*{[^}]*background[^:]*:\\s*url\\s*\\(\\s*[\"|\']*([^\"&^\'&^)&^}]+)"));
                if(matches !== null) {
                  logo = matches[1];
                  break;
                }
              }

              if(logo !== undefined) {
                // Found image in stylesheet
                stylesheet = stylesheet.substring(0,(stylesheet.lastIndexOf('/')) + 1);

                if(stylesheet.substr(0,4) == 'http') {
                  uri = stylesheet;
                } else {
                  uri = url.resolve(uri, stylesheet);
                }

                respond(webresponse, logo);
              } else {
                respond(webresponse);
              }
            }
          })
        } else {
          // Check for an OpenGraph image
          logo = $('meta[property="og:image"]', html).attr('content');

          if(logo === undefined) {
            // Check for an iOS icon
            logo = $('link[rel="apple-touch-icon-precomposed"], link[rel="apple-touch-icon"]', html).attr('href');
          }

          if(logo !== undefined) {
            respond(webresponse, logo);
          } else {
            respond(webresponse);
          }
        }
      } else {
        respond(webresponse, logo);
      }
    } else {
      respond(webresponse);
    }
  })

}

}).listen(port);

console.log('Server listening on port ' + port);

function getImage(html, selectors) {
  return $(selectors.join(','), html).attr('src');
}

function getInlineStyleImage(html, selectors) {
  // Check for inline styles
  for(var i in selectors) {
    selectors[i] += '[style]"]';
  }

  var inline = $(selectors, html).attr('style');

  if(inline !== undefined) {
    var matches = inline.match(new RegExp("background[^:]*:\\s*url\\s*\\(\\s*[\"|\']*([^\"&^\'&^)]+)"));
  }

  return matches != null && matches != undefined ? matches[1] : undefined;
}

function getImageFromTitle(html) {
  // Check for an image filename similar to the title tag slugified
  var title =  $('title', html).text().toLowerCase().replace(/\s+/g,'-');
  return $('img[src$="' + title + '.png"], img[src$="' + title + '.jpg"], img[src$="' + title + '.jpeg"], img[src$="' + title + '.gif"]', html).attr('src');
}

function getImageFromDomain(html) {
  // Check for an image filename similar to the domain
  var hostname = url.parse(uri).hostname.replace('www.', '');
  var domain = hostname.substring(0,(hostname.indexOf('.')));
  return $('img[src$="' + domain + '.png"], img[src$="' + domain + '.jpg"], img[src$="' + domain + '.jpeg"], img[src$="' + domain + '.gif"]', html).attr('src');
}

function getStylesheet(html, selectors) {
  if($('link[rel="stylesheet"]', html).length == 1) {
    // If there's only one stylesheet assume it as master
    return $('link[rel="stylesheet"]', html).attr('href');
  } else {
    // Check for commonly used main stylesheet names
    for(var i in selectors) {
      selectors[i] = 'link[rel="stylesheet"][href*="' + selectors[i] + '.css"]';
    }

    return $(selectors.join(','), html).attr('href');
  }
}

function respond(response, logo) {
  if(logo !== undefined) {
    response.writeHead(302, {'Location': url.resolve(uri, logo)});
    console.log(url.resolve(uri, logo) + '\n');
  } else {
    response.writeHead(404, {"Content-Type": "text/plain"});
    console.log('Fail :(\n')
  }
  response.end();
}<|endoftext|>


<commit_before>// @ts-check
const gulp = require("gulp");
const del = require("del");
const fs = require("fs");
const os = require("os");
const path = require("path");
const mkdirP = require("mkdirp");
const log = require("fancy-log");
const cmdLineOptions = require("./options");
const { CancellationToken } = require("prex");
const { exec } = require("./utils");
const { findUpFile } = require("./findUpDir");

const mochaJs = require.resolve("mocha/bin/_mocha");
exports.localBaseline = "tests/baselines/local/";
exports.refBaseline = "tests/baselines/reference/";
exports.localRwcBaseline = "internal/baselines/rwc/local";
exports.refRwcBaseline = "internal/baselines/rwc/reference";
exports.localTest262Baseline = "internal/baselines/test262/local";

/**
 * @param {string} runJs
 * @param {string} defaultReporter
 * @param {boolean} runInParallel
 * @param {boolean} watchMode
 * @param {import("prex").CancellationToken} [cancelToken]
 */
async function runConsoleTests(runJs, defaultReporter, runInParallel, watchMode, cancelToken = CancellationToken.none) {
    let testTimeout = cmdLineOptions.timeout;
    let tests = cmdLineOptions.tests;
    const inspect = cmdLineOptions.break || cmdLineOptions.inspect;
    const runners = cmdLineOptions.runners;
    const light = cmdLineOptions.light;
    const stackTraceLimit = cmdLineOptions.stackTraceLimit;
    const testConfigFile = "test.config";
    const failed = cmdLineOptions.failed;
    const keepFailed = cmdLineOptions.keepFailed;
    const shards = +cmdLineOptions.shards || undefined;
    const shardId = +cmdLineOptions.shardId || undefined;
    if (!cmdLineOptions.dirty) {
        await cleanTestDirs();
        cancelToken.throwIfCancellationRequested();
    }

    if (fs.existsSync(testConfigFile)) {
        fs.unlinkSync(testConfigFile);
    }

    let workerCount, taskConfigsFolder;
    if (runInParallel) {
        // generate name to store task configuration files
        const prefix = os.tmpdir() + "/ts-tests";
        let i = 1;
        do {
            taskConfigsFolder = prefix + i;
            i++;
        } while (fs.existsSync(taskConfigsFolder));
        fs.mkdirSync(taskConfigsFolder);

        workerCount = cmdLineOptions.workers;
    }

    if (tests && tests.toLocaleLowerCase() === "rwc") {
        testTimeout = 400000;
    }

    if (tests || runners || light || testTimeout || taskConfigsFolder || keepFailed || shards || shardId) {
        writeTestConfigFile(tests, runners, light, taskConfigsFolder, workerCount, stackTraceLimit, testTimeout, keepFailed, shards, shardId);
    }

    const colors = cmdLineOptions.colors;
    const reporter = cmdLineOptions.reporter || defaultReporter;

    /** @type {string[]} */
    let args = [];

    // timeout normally isn't necessary but Travis-CI has been timing out on compiler baselines occasionally
    // default timeout is 2sec which really should be enough, but maybe we just need a small amount longer
    if (!runInParallel) {
        args.push(mochaJs);
        args.push("-R", findUpFile("scripts/failed-tests.js"));
        args.push("-O", '"reporter=' + reporter + (keepFailed ? ",keepFailed=true" : "") + '"');
        if (tests) {
            args.push("-g", `"${tests}"`);
        }
        if (failed) {
            const grep = fs.readFileSync(".failed-tests", "utf8")
                .split(/\r?\n/g)
                .map(test => test.trim())
                .filter(test => test.length > 0)
                .map(regExpEscape)
                .join("|");
            const file = path.join(os.tmpdir(), ".failed-tests.json");
            fs.writeFileSync(file, JSON.stringify({ grep }), "utf8");
            args.push("--config", file);
        }
        if (colors) {
            args.push("--colors");
        }
        else {
            args.push("--no-colors");
        }
        if (inspect !== undefined) {
            args.unshift((inspect == "" || inspect === true) ? "--inspect-brk" : "--inspect-brk="+inspect);
            args.push("-t", "0");
        }
        else {
            args.push("-t", "" + testTimeout);
        }
        args.push(runJs);
    }
    else {
        // run task to load all tests and partition them between workers
        args.push(runJs);
    }

    /** @type {number | undefined} */
    let errorStatus;

    /** @type {Error | undefined} */
    let error;

    try {
        setNodeEnvToDevelopment();
        const { exitCode } = await exec("node", args, { cancelToken });
        if (exitCode !== 0) {
            errorStatus = exitCode;
            error = new Error(`Process exited with status code ${errorStatus}.`);
        }
        else if (process.env.CI === "true") {
            // finally, do a sanity check and build the compiler with the built version of itself
            log.info("Starting sanity check build...");
            // Cleanup everything except lint rules (we'll need those later and would rather not waste time rebuilding them)
            await exec("gulp", ["clean-tsc", "clean-services", "clean-tsserver", "clean-lssl", "clean-tests"], { cancelToken });
            const { exitCode } = await exec("gulp", ["local", "--lkg=false"], { cancelToken });
            if (exitCode !== 0) {
                errorStatus = exitCode;
                error = new Error(`Sanity check build process exited with status code ${errorStatus}.`);
            }
        }
    }
    catch (e) {
        errorStatus = undefined;
        error = e;
    }
    finally {
        restoreSavedNodeEnv();
    }

    await del("test.config");
    await deleteTemporaryProjectOutput();

    if (error !== undefined) {
        process.exitCode = typeof errorStatus === "number" ? errorStatus : 2;
        throw error;
    }
}
exports.runConsoleTests = runConsoleTests;

async function cleanTestDirs() {
    await del([exports.localBaseline, exports.localRwcBaseline])
    mkdirP.sync(exports.localRwcBaseline);
    mkdirP.sync(exports.localBaseline);
}
exports.cleanTestDirs = cleanTestDirs;

/**
 * used to pass data from gulp command line directly to run.js
 * @param {string} tests
 * @param {string} runners
 * @param {boolean} light
 * @param {string} [taskConfigsFolder]
 * @param {string | number} [workerCount]
 * @param {string} [stackTraceLimit]
 * @param {string | number} [timeout]
 * @param {boolean} [keepFailed]
 * @param {number | undefined} [shards]
 * @param {number | undefined} [shardId]
 */
function writeTestConfigFile(tests, runners, light, taskConfigsFolder, workerCount, stackTraceLimit, timeout, keepFailed, shards, shardId) {
    const testConfigContents = JSON.stringify({
        test: tests ? [tests] : undefined,
        runners: runners ? runners.split(",") : undefined,
        light,
        workerCount,
        stackTraceLimit,
        taskConfigsFolder,
        noColor: !cmdLineOptions.colors,
        timeout,
        keepFailed,
        shards,
        shardId
    });
    log.info("Running tests with config: " + testConfigContents);
    fs.writeFileSync("test.config", testConfigContents);
}
exports.writeTestConfigFile = writeTestConfigFile;

/** @type {string} */
let savedNodeEnv;
function setNodeEnvToDevelopment() {
    savedNodeEnv = process.env.NODE_ENV;
    process.env.NODE_ENV = "development";
}

function restoreSavedNodeEnv() {
    process.env.NODE_ENV = savedNodeEnv;
}

function deleteTemporaryProjectOutput() {
    return del(path.join(exports.localBaseline, "projectOutput/"));
}

function regExpEscape(text) {
    return text.replace(/[.*+?^${}()|\[\]\\]/g, '\\$&');
}
<commit_msg>Run `mocha` using `process.execPath` instead of harcoding `"node"` (#48797)<commit_after>// @ts-check
const gulp = require("gulp");
const del = require("del");
const fs = require("fs");
const os = require("os");
const path = require("path");
const mkdirP = require("mkdirp");
const log = require("fancy-log");
const cmdLineOptions = require("./options");
const { CancellationToken } = require("prex");
const { exec } = require("./utils");
const { findUpFile } = require("./findUpDir");

const mochaJs = require.resolve("mocha/bin/_mocha");
exports.localBaseline = "tests/baselines/local/";
exports.refBaseline = "tests/baselines/reference/";
exports.localRwcBaseline = "internal/baselines/rwc/local";
exports.refRwcBaseline = "internal/baselines/rwc/reference";
exports.localTest262Baseline = "internal/baselines/test262/local";

/**
 * @param {string} runJs
 * @param {string} defaultReporter
 * @param {boolean} runInParallel
 * @param {boolean} watchMode
 * @param {import("prex").CancellationToken} [cancelToken]
 */
async function runConsoleTests(runJs, defaultReporter, runInParallel, watchMode, cancelToken = CancellationToken.none) {
    let testTimeout = cmdLineOptions.timeout;
    let tests = cmdLineOptions.tests;
    const inspect = cmdLineOptions.break || cmdLineOptions.inspect;
    const runners = cmdLineOptions.runners;
    const light = cmdLineOptions.light;
    const stackTraceLimit = cmdLineOptions.stackTraceLimit;
    const testConfigFile = "test.config";
    const failed = cmdLineOptions.failed;
    const keepFailed = cmdLineOptions.keepFailed;
    const shards = +cmdLineOptions.shards || undefined;
    const shardId = +cmdLineOptions.shardId || undefined;
    if (!cmdLineOptions.dirty) {
        await cleanTestDirs();
        cancelToken.throwIfCancellationRequested();
    }

    if (fs.existsSync(testConfigFile)) {
        fs.unlinkSync(testConfigFile);
    }

    let workerCount, taskConfigsFolder;
    if (runInParallel) {
        // generate name to store task configuration files
        const prefix = os.tmpdir() + "/ts-tests";
        let i = 1;
        do {
            taskConfigsFolder = prefix + i;
            i++;
        } while (fs.existsSync(taskConfigsFolder));
        fs.mkdirSync(taskConfigsFolder);

        workerCount = cmdLineOptions.workers;
    }

    if (tests && tests.toLocaleLowerCase() === "rwc") {
        testTimeout = 400000;
    }

    if (tests || runners || light || testTimeout || taskConfigsFolder || keepFailed || shards || shardId) {
        writeTestConfigFile(tests, runners, light, taskConfigsFolder, workerCount, stackTraceLimit, testTimeout, keepFailed, shards, shardId);
    }

    const colors = cmdLineOptions.colors;
    const reporter = cmdLineOptions.reporter || defaultReporter;

    /** @type {string[]} */
    let args = [];

    // timeout normally isn't necessary but Travis-CI has been timing out on compiler baselines occasionally
    // default timeout is 2sec which really should be enough, but maybe we just need a small amount longer
    if (!runInParallel) {
        args.push(mochaJs);
        args.push("-R", findUpFile("scripts/failed-tests.js"));
        args.push("-O", '"reporter=' + reporter + (keepFailed ? ",keepFailed=true" : "") + '"');
        if (tests) {
            args.push("-g", `"${tests}"`);
        }
        if (failed) {
            const grep = fs.readFileSync(".failed-tests", "utf8")
                .split(/\r?\n/g)
                .map(test => test.trim())
                .filter(test => test.length > 0)
                .map(regExpEscape)
                .join("|");
            const file = path.join(os.tmpdir(), ".failed-tests.json");
            fs.writeFileSync(file, JSON.stringify({ grep }), "utf8");
            args.push("--config", file);
        }
        if (colors) {
            args.push("--colors");
        }
        else {
            args.push("--no-colors");
        }
        if (inspect !== undefined) {
            args.unshift((inspect == "" || inspect === true) ? "--inspect-brk" : "--inspect-brk="+inspect);
            args.push("-t", "0");
        }
        else {
            args.push("-t", "" + testTimeout);
        }
        args.push(runJs);
    }
    else {
        // run task to load all tests and partition them between workers
        args.push(runJs);
    }

    /** @type {number | undefined} */
    let errorStatus;

    /** @type {Error | undefined} */
    let error;

    try {
        setNodeEnvToDevelopment();
        const { exitCode } = await exec(process.execPath, args, {
            cancelToken,
        });
        if (exitCode !== 0) {
            errorStatus = exitCode;
            error = new Error(`Process exited with status code ${errorStatus}.`);
        }
        else if (process.env.CI === "true") {
            // finally, do a sanity check and build the compiler with the built version of itself
            log.info("Starting sanity check build...");
            // Cleanup everything except lint rules (we'll need those later and would rather not waste time rebuilding them)
            await exec("gulp", ["clean-tsc", "clean-services", "clean-tsserver", "clean-lssl", "clean-tests"], { cancelToken });
            const { exitCode } = await exec("gulp", ["local", "--lkg=false"], { cancelToken });
            if (exitCode !== 0) {
                errorStatus = exitCode;
                error = new Error(`Sanity check build process exited with status code ${errorStatus}.`);
            }
        }
    }
    catch (e) {
        errorStatus = undefined;
        error = e;
    }
    finally {
        restoreSavedNodeEnv();
    }

    await del("test.config");
    await deleteTemporaryProjectOutput();

    if (error !== undefined) {
        process.exitCode = typeof errorStatus === "number" ? errorStatus : 2;
        throw error;
    }
}
exports.runConsoleTests = runConsoleTests;

async function cleanTestDirs() {
    await del([exports.localBaseline, exports.localRwcBaseline])
    mkdirP.sync(exports.localRwcBaseline);
    mkdirP.sync(exports.localBaseline);
}
exports.cleanTestDirs = cleanTestDirs;

/**
 * used to pass data from gulp command line directly to run.js
 * @param {string} tests
 * @param {string} runners
 * @param {boolean} light
 * @param {string} [taskConfigsFolder]
 * @param {string | number} [workerCount]
 * @param {string} [stackTraceLimit]
 * @param {string | number} [timeout]
 * @param {boolean} [keepFailed]
 * @param {number | undefined} [shards]
 * @param {number | undefined} [shardId]
 */
function writeTestConfigFile(tests, runners, light, taskConfigsFolder, workerCount, stackTraceLimit, timeout, keepFailed, shards, shardId) {
    const testConfigContents = JSON.stringify({
        test: tests ? [tests] : undefined,
        runners: runners ? runners.split(",") : undefined,
        light,
        workerCount,
        stackTraceLimit,
        taskConfigsFolder,
        noColor: !cmdLineOptions.colors,
        timeout,
        keepFailed,
        shards,
        shardId
    });
    log.info("Running tests with config: " + testConfigContents);
    fs.writeFileSync("test.config", testConfigContents);
}
exports.writeTestConfigFile = writeTestConfigFile;

/** @type {string} */
let savedNodeEnv;
function setNodeEnvToDevelopment() {
    savedNodeEnv = process.env.NODE_ENV;
    process.env.NODE_ENV = "development";
}

function restoreSavedNodeEnv() {
    process.env.NODE_ENV = savedNodeEnv;
}

function deleteTemporaryProjectOutput() {
    return del(path.join(exports.localBaseline, "projectOutput/"));
}

function regExpEscape(text) {
    return text.replace(/[.*+?^${}()|\[\]\\]/g, '\\$&');
}
<|endoftext|>


<commit_before>(function () {
  var output = document.getElementById('output');
  // For future translation
  var messages = [
    'Incompatible browser, loading fallback',
    'No file defined :/',
    'After the download starts you can now close this window.',
    'Unknown error, loading fallback',
    'Try MEGA directly',
    'Report issue',
    'Download fishished',
    'Unknown error'
  ];

  var href = 'https://mega.nz' + (location.hash.length > 2 ? location.hash : ('#' + (location.search || '').substr(1)));

  if (!navigator.serviceWorker) {
    showMessage(messages[0], true);
    loadFallback();
    return;
  }

  navigator.serviceWorker.register('sw.min.js', {scope: '.'})
  .then(navigator.serviceWorker.ready)
  .then(function afterReady(instance){
    if (!instance.active || location.search.length > 2) {
      location.reload();
      return;
    }

    if (location.hash.length <= 1) {
      showMessage(messages[1], true);
      return;
    }

    sendMessage(instance.active, href).then(function (data) {
      location.href = './?' + data.identifier;
      showMessage(messages[2], true);
    });
  }, function (error) {
    console.error(error);
    showMessage(messages[3], true);
    loadFallback();
  });

  function loadFallback() {
    var script = document.createElement('script');
    var file;
    script.src = 'mega.js';
    script.onload = function() {
      file = mega.file(href);
      file.loadAttributes(afterLoadAttributes);
    };

    function afterLoadAttributes(err, data) {
      if (err) {
        showMessage(messages[7]);
        throw err;
      }
      file.download(afterDownload);
    }

    function afterDownload(err, data) {
      if (err) {
        showMessage(messages[7]);
        throw err;
      }
      var anchor = document.createElement('a');
      anchor.textContent = messages[6];
      anchor.href = URL.createObjectURL(new Blob(data));
      showMessage('', true);
      output.appendChild(anchor);
    }

    document.head.appendChild(script)
  }

  function showMessage(message, noError) {
    output.textContent = message;
    output.appendChild(document.createElement('br'));

    if (noError) return;

    var anchor = document.createElement('a');
    anchor.textContent = messages[4];
    anchor.href = href;
    output.appendChild(anchor);
    output.appendChild(document.createElement('br'));

    anchor = document.createElement('a');
    anchor.textContent = messages[5];
    anchor.href = 'https://github.com/qgustavor/direct-mega/issues/new';
    output.appendChild(anchor);
  }

  // https://googlechrome.github.io/samples/service-worker/post-message/
  function sendMessage(instance, message) {
    return new Promise(function(resolve, reject) {
      var messageChannel = new MessageChannel();
      messageChannel.port1.onmessage = function(event) {
        if (event.data.error) {
          reject(event.data.error);
        } else {
          resolve(event.data);
        }
      };

      instance.postMessage(message, [messageChannel.port2]);
    });
  }
}());<commit_msg>Show messages while downloading<commit_after>(function () {
  var output = document.getElementById('output');
  // For future translation
  var messages = [
    'Incompatible browser, loading fallback',
    'No file defined :/',
    'After the download starts you can now close this window.',
    'Unknown error, loading fallback',
    'Try MEGA directly',
    'Report issue',
    'Click here to finish download if it not starts automatically',
    'Unknown error',
    'Downloading $1 ($2 bytes)',
  ];

  var href = 'https://mega.nz' + (location.hash.length > 2 ? location.hash : ('#' + (location.search || '').substr(1)));

  if (!navigator.serviceWorker) {
    showMessage(messages[0], true);
    loadFallback();
    return;
  }

  navigator.serviceWorker.register('sw.min.js', {scope: '.'})
  .then(navigator.serviceWorker.ready)
  .then(function afterReady(instance){
    if (!instance.active || location.search.length > 2) {
      location.reload();
      return;
    }

    if (location.hash.length <= 1) {
      showMessage(messages[1], true);
      return;
    }

    sendMessage(instance.active, href).then(function (data) {
      location.href = './?' + data.identifier;
      showMessage(messages[2], true);
    });
  }, function (error) {
    console.error(error);
    showMessage(messages[3], true);
    loadFallback();
  });

  function loadFallback() {
    var script = document.createElement('script');
    var file;
    var attributes;
    script.src = 'mega.js';
    script.onload = function() {
      file = mega.file(href);
      file.loadAttributes(afterLoadAttributes);
    };

    function afterLoadAttributes(err, data) {
      attributes = data;
      if (err) {
        showMessage(messages[7]);
        throw err;
      }
      showMessage(messages[8]
        .replace('$1', attributes.name)
        .replace('$2', attributes.size), true);
      file.download(afterDownload);
    }

    function afterDownload(err, data) {
      if (err) {
        showMessage(messages[7]);
        throw err;
      }
      var anchor = document.createElement('a');
      anchor.textContent = messages[6];
      anchor.href = URL.createObjectURL(new Blob(data));
      anchor.download = attributes.name;
      showMessage('', true);
      output.appendChild(anchor);
      anchor.click();
    }

    document.head.appendChild(script)
  }

  function showMessage(message, noError) {
    output.textContent = message;
    output.appendChild(document.createElement('br'));

    if (noError) return;

    var anchor = document.createElement('a');
    anchor.textContent = messages[4];
    anchor.href = href;
    output.appendChild(anchor);
    output.appendChild(document.createElement('br'));

    anchor = document.createElement('a');
    anchor.textContent = messages[5];
    anchor.href = 'https://github.com/qgustavor/direct-mega/issues/new';
    output.appendChild(anchor);
  }

  // https://googlechrome.github.io/samples/service-worker/post-message/
  function sendMessage(instance, message) {
    return new Promise(function(resolve, reject) {
      var messageChannel = new MessageChannel();
      messageChannel.port1.onmessage = function(event) {
        if (event.data.error) {
          reject(event.data.error);
        } else {
          resolve(event.data);
        }
      };

      instance.postMessage(message, [messageChannel.port2]);
    });
  }
}());<|endoftext|>


<commit_before>$(document).ready(function() {

  var disqus_shortname = 'foliea'; // required: replace example with your forum shortname

  var dsq = document.createElement('script');
      dsq.type = 'text/javascript';
      dsq.async = true;
      dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);

});
<commit_msg>remove useless file<commit_after><|endoftext|>


<commit_before>$(document).ready(function(){
  //Detect browser type and revision
  navigator.sayswho = (function(){
    var browser = document.querySelector('.alert_browser');
    var N= navigator.appName, ua= navigator.userAgent, tem;
    var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
    if(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
    M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
    var version = parseFloat(M[1]);
    var browserName = M[0];

    if(browserName == 'Firefox' && version >= 23){
      browser.innerHTML = '
  Thanks For Using Quickbits
';
    }

    if(browserName == 'Firefox' && version < 23){
      browser.innerHTML = '
 To use this service please upgrade your version of Firefox  Here
';
    }

    if(browserName == 'Chrome' && version >= 31){
      browser.innerHTML = '
 If file does not transfer confirm you are using the same browser type as the sender.
';
    }
   })();
});

function Receiver(){
  var thisReceiver = this;
  thisReceiver.peer = new Peer({ host: "ec2-54-201-154-161.us-west-2.compute.amazonaws.com", port: 9000 });
}

Receiver.prototype.establishConnection = function(senderPeerId){
  var thisReceiver = this;
  thisReceiver.connection = thisReceiver.peer.connect(senderPeerId);

  setTimeout(function(){
    var isDone = ($.trim($('.percent').get()[0].innerHTML) == "100%");
    if((thisReceiver.connection.open !== true) && (!isDone)){
      $("#error_message").append("Unable to connect to sender! Connection timed out after 10 sec.");
      return;
    }
  }, 10000);
}

Receiver.prototype.handleConnection = function(){
  var thisReceiver = this;
  thisReceiver.connection.on("open", function(){
    thisReceiver.getData();
  });
}

Receiver.prototype.getData = function(){
  var fileArray = [];
  var thisReceiver = this;
  var chunk_count = 0;
  var progress = document.querySelector('.percent');
  var userFileName = document.querySelector('.file_name');
  var userFileSize = document.querySelector('.file_size');
  var alert_browser = document.querySelector('.alert_browser');
  var errorElement = $("#error_message");
  var upload_button = document.querySelector('.button_upload');
  thisReceiver.connection.on("data", function(data){
  alert_browser.innerHTML = "
Your File is Being Transferred
";
  alert_browser.style.display = "inline";

    if(data.isFileMetaData){
      // GLOBAL, COME BACK TO THIS
      file_size = data.fileSize;
      fileName = data.fileName;
      userFileName.textContent = data.fileName;
      size = byteConverter(data.fileSize);
      userFileSize.textContent = size;
    }
    else if(data.isFile){
      chunk_count += 1;

      thisReceiver.connection.send({ isChunkCount: true, chunksReceived: chunk_count });
      var file = new Blob([data.arrayBufferFileData], { type: data.fileType });
      thisReceiver.file = file;
      fileArray.push(data.arrayBufferFileData);

      var percentLoaded = Math.round((chunk_count / (file_size / 1000) ) * 100);

      progress.style.width = percentLoaded + '%';
      progress.textContent = percentLoaded + '%';

      if(percentLoaded >= 100){
        progress.style.width = '100%';
        progress.textContent = '100%';
        alert_browser.innerHTML = "
File Successfully Transferred
";
        upload_button.style.display = "block";
      }

      // Communication heartbeat check
      if(percentLoaded < 100){
        clearTimeout(thisReceiver.timeout);
        thisReceiver.timeout = setTimeout(function(){
          errorElement.text("Connection may have failed. File transfer may have aborted.");
        }, 5000);
      }
      else if(percentLoaded >= 100){
        clearTimeout(thisReceiver.timeout);
      }

      if(data.isLast == 1){
        setTimeout(function(){
        var fileConstruct = new Blob(fileArray);
        saveAs(fileConstruct, fileName);}, 500);
      }
    }
  });
}

function byteConverter(bytes){
  var kilobyte = 1024;
  var megabyte = kilobyte * 1024;
  var gigabyte = megabyte * 1024;

  if (Math.floor(bytes/gigabyte) > 0){
    return (bytes/gigabyte).toFixed(2) + " GB";
  }
  else if (Math.floor(bytes/megabyte) > 0){
    return (bytes/megabyte).toFixed(2) + " MB";
  }
  else if (Math.floor(bytes/kilobyte) > 0){
    return (bytes/kilobyte).toFixed(2) + " kB";
  }
  else {
    return bytes + " B";
  }
}

$(function(){
  var splitUrl = window.location.href.split("/");
  var phoneticUrl = splitUrl[splitUrl.length-1];
  var urlStore = new Firebase('https://quickbits.firebaseio.com/' + phoneticUrl);
  var receiver = new Receiver();

  urlStore.on('value', function(snapshot) {
    var senderPeerId = snapshot.val();
    receiver.establishConnection(senderPeerId);
    receiver.handleConnection();
  });

  window.onunload = function(){
    receiver.peer.destroy();
  }
});
<commit_msg>Changed append to innerHTML to fix error message overfill<commit_after>$(document).ready(function(){
  //Detect browser type and revision
  navigator.sayswho = (function(){
    var browser = document.querySelector('.alert_browser');
    var N= navigator.appName, ua= navigator.userAgent, tem;
    var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
    if(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
    M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
    var version = parseFloat(M[1]);
    var browserName = M[0];

    if(browserName == 'Firefox' && version >= 23){
      browser.innerHTML = '
  Thanks For Using Quickbits
';
    }

    if(browserName == 'Firefox' && version < 23){
      browser.innerHTML = '
 To use this service please upgrade your version of Firefox  Here
';
    }

    if(browserName == 'Chrome' && version >= 31){
      browser.innerHTML = '
 If file does not transfer confirm you are using the same browser type as the sender.
';
    }
   })();
});

function Receiver(){
  var thisReceiver = this;
  thisReceiver.peer = new Peer({ host: "ec2-54-201-154-161.us-west-2.compute.amazonaws.com", port: 9000 });
}

Receiver.prototype.establishConnection = function(senderPeerId){
  var thisReceiver = this;
  thisReceiver.connection = thisReceiver.peer.connect(senderPeerId);

  setTimeout(function(){
    var isDone = ($.trim($('.percent').get()[0].innerHTML) == "100%");
    if((thisReceiver.connection.open !== true) && (!isDone)){
      $("#error_message").innerHTML("Unable to connect to sender! Connection timed out after 10 sec.");
      return;
    }
  }, 10000);
}

Receiver.prototype.handleConnection = function(){
  var thisReceiver = this;
  thisReceiver.connection.on("open", function(){
    thisReceiver.getData();
  });
}

Receiver.prototype.getData = function(){
  var fileArray = [];
  var thisReceiver = this;
  var chunk_count = 0;
  var progress = document.querySelector('.percent');
  var userFileName = document.querySelector('.file_name');
  var userFileSize = document.querySelector('.file_size');
  var alert_browser = document.querySelector('.alert_browser');
  var errorElement = $("#error_message");
  var upload_button = document.querySelector('.button_upload');
  thisReceiver.connection.on("data", function(data){
  alert_browser.innerHTML = "
Your File is Being Transferred
";
  alert_browser.style.display = "inline";

    if(data.isFileMetaData){
      // GLOBAL, COME BACK TO THIS
      file_size = data.fileSize;
      fileName = data.fileName;
      userFileName.textContent = data.fileName;
      size = byteConverter(data.fileSize);
      userFileSize.textContent = size;
    }
    else if(data.isFile){
      chunk_count += 1;

      thisReceiver.connection.send({ isChunkCount: true, chunksReceived: chunk_count });
      var file = new Blob([data.arrayBufferFileData], { type: data.fileType });
      thisReceiver.file = file;
      fileArray.push(data.arrayBufferFileData);

      var percentLoaded = Math.round((chunk_count / (file_size / 1000) ) * 100);

      progress.style.width = percentLoaded + '%';
      progress.textContent = percentLoaded + '%';

      if(percentLoaded >= 100){
        progress.style.width = '100%';
        progress.textContent = '100%';
        alert_browser.innerHTML = "
File Successfully Transferred
";
        upload_button.style.display = "block";
      }

      // Communication heartbeat check
      if(percentLoaded < 100){
        clearTimeout(thisReceiver.timeout);
        thisReceiver.timeout = setTimeout(function(){
          errorElement.text("Connection may have failed. File transfer may have aborted.");
        }, 5000);
      }
      else if(percentLoaded >= 100){
        clearTimeout(thisReceiver.timeout);
      }

      if(data.isLast == 1){
        setTimeout(function(){
        var fileConstruct = new Blob(fileArray);
        saveAs(fileConstruct, fileName);}, 500);
      }
    }
  });
}

function byteConverter(bytes){
  var kilobyte = 1024;
  var megabyte = kilobyte * 1024;
  var gigabyte = megabyte * 1024;

  if (Math.floor(bytes/gigabyte) > 0){
    return (bytes/gigabyte).toFixed(2) + " GB";
  }
  else if (Math.floor(bytes/megabyte) > 0){
    return (bytes/megabyte).toFixed(2) + " MB";
  }
  else if (Math.floor(bytes/kilobyte) > 0){
    return (bytes/kilobyte).toFixed(2) + " kB";
  }
  else {
    return bytes + " B";
  }
}

$(function(){
  var splitUrl = window.location.href.split("/");
  var phoneticUrl = splitUrl[splitUrl.length-1];
  var urlStore = new Firebase('https://quickbits.firebaseio.com/' + phoneticUrl);
  var receiver = new Receiver();

  urlStore.on('value', function(snapshot) {
    var senderPeerId = snapshot.val();
    receiver.establishConnection(senderPeerId);
    receiver.handleConnection();
  });

  window.onunload = function(){
    receiver.peer.destroy();
  }
});
<|endoftext|>