<commit_before>const electron = require('electron')
const app = electron.app
const globalShortcut = electron.globalShortcut
const ipcMain = electron.ipcMain
const nativeImage = electron.nativeImage
const BrowserWindow = electron.BrowserWindow

app.setName("Requesto");

if (app.dock) {
    app.dock.setIcon(nativeImage.createFromPath("resources/icon.png"));
    // app.dock.setBadge("1");
}

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

function createWindow() {
    mainWindow = new BrowserWindow({
        background: "#1d1e26",
        title: "Requesto",
        center: true,
    })
    // mainWindow.webContents.openDevTools()
    mainWindow.maximize()
    mainWindow.loadURL(`file://${__dirname}/dist/index.html`)
    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
    })

    // Shortcuts
    //globalShortcut.register('Command+W', () => {});
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// 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 (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', function() {
    // On OS X it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (mainWindow === null) {
        createWindow()
    }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
<commit_msg>fix background ghost :D<commit_after>const electron = require('electron')
const app = electron.app
const globalShortcut = electron.globalShortcut
const ipcMain = electron.ipcMain
const nativeImage = electron.nativeImage
const BrowserWindow = electron.BrowserWindow

app.setName("Requesto");

if (app.dock) {
    app.dock.setIcon(nativeImage.createFromPath("resources/icon.png"));
    // app.dock.setBadge("1");
}

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

function createWindow() {
    mainWindow = new BrowserWindow({
        show: true,
        backgroundColor: "#1d1e26",
        title: "Requesto",
        center: true
    })

    //mainWindow.webContents.openDevTools()
    mainWindow.maximize()
    mainWindow.loadURL(`file://${__dirname}/dist/index.html`)
    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
    })

    // Shortcuts
    //globalShortcut.register('Command+W', () => {});

    // Showing window gracefully
    // mainWindow.once('ready-to-show', () => {
    //   mainWindow.show()
    // })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// 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 (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', function() {
    // On OS X it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (mainWindow === null) {
        createWindow()
    }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
<|endoftext|>


<commit_before>// GENERAL SETTINGS

var debug = true;
var bombsite = 'B';
var roundLength = 1.5 * 60;
var bombTimer = 30;
var codeLength = 4; // chars
var armingSteps = 3;
var disarmingSteps = 2;

// Game variables
var armed, disarmed;
var armingProgress, disarmingProgress;
var locked = true;
var winner = NaN;

// Start round
function initGame(site) {
    bombsite = site;

    // Set bombsite characters
    $('.sitename').text(site);

    // Set main image
    $('body').removeClass('site-a site-b');
    $('body').addClass('site-' + site.toLowerCase());

    // Load sounds
    initSounds(site);
}

function startGame() {
    winner = NaN
    clearOverlay();
    bombProgress(0, 'neutral');
    $('#timer-text').text('ROUND TIMER');

    // Start clock
    maxTime = roundLength;
    timerValue = maxTime + 1;
    startTimer();

    armed = false;
    disarmed = false;
    armingProgress = 0;
    disarmingProgress = 0;

    // Lock keypad
    lock();

    // Start music
    play('wind');
}

function keypadFinished() {
    if (!armed) {
        // Arming
        armingProgress += 1;
        progress = armingProgress / armingSteps;
        if (progress > 0.99) {
            bombProgress(progress, 'armed');
            armingComplete();
        } else {
            bombProgress(progress, 'arming');
            delayLock();
        }
    } else {
        // Disarming
        disarmingProgress += 1;
        progress = disarmingProgress / disarmingSteps;
        if (progress > 0.99) {
            bombProgress(progress, 'disarmed');
            disarmingComplete();
        } else {
            bombProgress(progress, 'disarming');
            delayLock();
        }
    }
}

function armingComplete() {
    console.log('Arming complete');
    delayLock();
    armed = true;

    // Set timer to bomb timer
    $('#timer-text').text('BOMB TIMER');
    maxTime = bombTimer;
    timerValue = maxTime + 1;

    // TODO Send "Bomb has been planted" messages
    play('planted');
}

function disarmingComplete() {
    console.log('Disarming complete');
    play('defused');

    winner = 'CT';
    endGame();
}

function kaboom() {
    console.log('Kaboom');

    bombProgress(1, 'exploded');
    play('explosion');

    play('win-ct');
    winner = 'TR';
    endGame();
}

function timerReached() {
    console.log('Timer reached');
    winner = 'CT';
    play('win-ct');

    endGame();
}

function endGame() {
    stopTimer();
    locked = true;

    showOverlay(winner + ' won', '');
    stop('wind');
    play('background');
}

// Timer
var maxTime = roundLength;
var timerValue = maxTime + 1;
var beepTimer;
var odd = true;

function startTimer() {
    beepTimer = setInterval(timer, 500);
    odd = false;
    timer();
}

function stopTimer() {
    clearInterval(beepTimer);
}

function timer() {
    odd = !odd;
    console.log(odd);

    if (odd) {
        // Every second time do not run full timer.
        if (armed && timerValue <= 10)
            play('beep');
        return;
    }
    else {
        if (armed) play('beep');
    }

    // Change time
    timerValue -= 1;
    advanceClock();

    // Kaboom
    if (timerValue == 0) {
        if (armed)
            kaboom();
        else
            timerReached();
        clearInterval(beepTimer);
    }

    // Blinking LED
    if (armed) {
        // Show LED
        $('#led').removeClass('hidden');
        // Hide LED
        window.setTimeout(function() {
            $('#led').addClass('hidden');
        }, 200);
    }
}

function advanceClock() {
    // Set countdown clock
    var minutes = Math.floor(timerValue / 60);
    var seconds = timerValue - (minutes * 60);
    if (seconds < 10) seconds = '0' + seconds;
    $('#timer-minutes').text(minutes);
    $('#timer-seconds').text(seconds);
    // Set progress bar
    var width = 100 * ((maxTime - timerValue) / maxTime);
    $('#progressbar').css('width', width + '%');
}

var bombTexts = {
    'neutral': 'Not armed',
    'arming': 'Arming',
    'armed': 'Armed',
    'disarming': 'Disarming',
    'disarmed': 'Disarmed',
    'exploded': 'Exploded'
}

// Bomb bar
function bombProgress(progress, state) {
    // Act on completed stage.
    $('#bomb-progress-container').removeClass('neutral arming armed disarming disarmed');
    $('#bomb-progress-container').addClass(state);
    $('#message').text(bombTexts[state]);
    $('#bomb-progress').css('width', (progress * 100) + '%');
}

// Overlay messages
function showOverlay(message) {
    $('#overlay-message').text(message);
    $('#overlay').removeClass('notvisible');
}

function clearOverlay() {
    $('#overlay').addClass('notvisible');
}

// Keypad
var code = '';
var guessed = '';
var next = '';

function initCodepad(len) {
    code = randomCode(len);
    guessed = '';
    next = nextNumber();
    highlight(next);
    var d = '';
    for (var i = 0; i < len; i++) d += '-';
    $('#display').text(d);
    $('#display').removeClass('correct');
}

function randomCode(len) {
    var min = 10 ** (len - 1);
    var max = 10 ** len - 1;
    return '' + Math.floor(Math.random()*(max-min+1)+min);
}

function nextNumber() {
    for (var i = 0; i < code.length; i++) {
        if (i == guessed.length) {
            return code[i];
        }
    }
}

function highlight(number) {
    // First remove highlight
    $('.cp').removeClass('highlight');

    // Wait a little and mark a new key
    window.setTimeout(function() {
        $('#code'+number).addClass('highlight');
    }, 500);
}

function numberPressed(number) {
    if (locked) {
        flashLock();
        play('beep');
        return;
    }
    if (!armed) {
        progress = armingProgress / armingSteps;
        bombProgress(progress, 'arming');
    }
    if (armed) {
        progress = disarmingProgress / disarmingSteps;
        bombProgress(progress, 'disarming');
    }

    if (number == next) {
        guessed += number;

        // Set display
        var d = guessed;
        for (var i = d.length; i < code.length; i++) d += '-';
        $('#display').text(d);

        // Get next number
        next = nextNumber();
        highlight(next);

        if (guessed == code) {
            // Guessed full code
            d += '-OK'
            $('#display').text(d);
            $('#display').addClass('correct');

            keypadFinished();
            play('done');
        }
        else {
            play('press');
        }
    } else {
        // Wrong keypress
        play('beep');

        // Lock it again
        lock();

        // Flash display
        //$('#display').addClass('wrong');
        //window.setTimeout(function () {
        //    $('#display').removeClass('wrong');
        //}, 200);
    }
}

function lock() {
    // TODO get right QR code and regular code
    //
    locked = true;
    $('#lock').removeClass('notvisible');
}

function delayLock() {
    window.setTimeout(lock, 1000);
}

function unlock() {
    locked = false;
    initCodepad(codeLength);
    $('#lock').addClass('notvisible');
}

function flashLock() {
    $('#lock-image').addClass('shake');
    window.setTimeout(function () {
        $('#lock-image').removeClass('shake');
    }, 500);
}

// Sound bank
var sounds = {};

function initSounds(bombsite) {
    var folder = 'static/bombsite/'
    var suffix = bombsite + '.mp3'
    var s = sounds
    s['background'] = new Audio(folder + 'background1.mp3');
    s['beep'] = new Audio(folder + 'beep.mp3');
    s['beep'].volume = 0.15;
    s['defused'] = new Audio(folder + 'defused.mp3');
    s['done'] = new Audio(folder + 'done.mp3');
    s['done'].volume = 0.5;
    s['explosion'] = new Audio(folder + 'explosion' + suffix);
    s['planted'] = new Audio(folder + 'planted.mp3');
    s['press'] = new Audio(folder + 'press.mp3');
    s['press'].volume = 0.6;
    s['win-ct'] = new Audio(folder + 'win-ct.mp3');
    s['win-tr'] = new Audio(folder + 'win-tr.mp3');
    s['wind'] = new Audio(folder + 'wind' + suffix);
    s['wind'].loop = true;
}

function play(sound) {
    // Pause and time reset is to make sure
    // it restarts when still playing.
    sounds[sound].pause();
    sounds[sound].currentTime = 0;
    sounds[sound].play();
}

function stop(sound) {
    sounds[sound].pause();
    sounds[sound].currentTime = 0;
}

// Act on keypress
function keypress(e) {
    var key = e.which || e.keyCode;
    // Enter was pressed
    if (debug && key == 13) {
        unlock();
        return;
    }

    // Ensure entered key is a number
    if(48 <= key && key <=57) {
        var number = parseInt(String.fromCharCode(key));
        numberPressed(number);
        return;
    }

    if (locked) flashLock();
    play('beep');
}

// Finally start game
window.onload = function() {
    // Setup game
    initGame(bombsite);
    startGame();

    // Register keypress listener
    window.addEventListener("keypress", keypress);
}
<commit_msg>Make disarming appear as soon as unlocked, remove cruft from console log<commit_after>// GENERAL SETTINGS

var debug = true;
var bombsite = 'B';
var roundLength = 1.5 * 60;
var bombTimer = 30;
var codeLength = 4; // chars
var armingSteps = 3;
var disarmingSteps = 2;

// Game variables
var armed, disarmed;
var armingProgress, disarmingProgress;
var locked = true;
var winner = NaN;

// Start round
function initGame(site) {
    bombsite = site;

    // Set bombsite characters
    $('.sitename').text(site);

    // Set main image
    $('body').removeClass('site-a site-b');
    $('body').addClass('site-' + site.toLowerCase());

    // Load sounds
    initSounds(site);
}

function startGame() {
    winner = NaN
    clearOverlay();
    bombProgress(0, 'neutral');
    $('#timer-text').text('ROUND TIMER');

    // Start clock
    maxTime = roundLength;
    timerValue = maxTime + 1;
    startTimer();

    armed = false;
    disarmed = false;
    armingProgress = 0;
    disarmingProgress = 0;

    // Lock keypad
    lock();

    // Start music
    play('wind');
}

function keypadFinished() {
    if (!armed) {
        // Arming
        armingProgress += 1;
        progress = armingProgress / armingSteps;
        if (progress > 0.99) {
            bombProgress(progress, 'armed');
            armingComplete();
        } else {
            bombProgress(progress, 'arming');
            delayLock();
        }
    } else {
        // Disarming
        disarmingProgress += 1;
        progress = disarmingProgress / disarmingSteps;
        if (progress > 0.99) {
            bombProgress(progress, 'disarmed');
            disarmingComplete();
        } else {
            bombProgress(progress, 'disarming');
            delayLock();
        }
    }
}

function armingComplete() {
    console.log('Arming complete');
    delayLock();
    armed = true;

    // Set timer to bomb timer
    $('#timer-text').text('BOMB TIMER');
    maxTime = bombTimer;
    timerValue = maxTime + 1;

    // TODO Send "Bomb has been planted" messages
    play('planted');
}

function disarmingComplete() {
    console.log('Disarming complete');
    play('defused');

    winner = 'CT';
    endGame();
}

function kaboom() {
    console.log('Kaboom');

    bombProgress(1, 'exploded');
    play('explosion');

    play('win-ct');
    winner = 'TR';
    endGame();
}

function timerReached() {
    console.log('Timer reached');
    winner = 'CT';
    play('win-ct');

    endGame();
}

function endGame() {
    stopTimer();
    locked = true;

    showOverlay(winner + ' won', '');
    stop('wind');
    play('background');
}

// Timer
var maxTime = roundLength;
var timerValue = maxTime + 1;
var beepTimer;
var odd = true;

function startTimer() {
    beepTimer = setInterval(timer, 500);
    odd = false;
    timer();
}

function stopTimer() {
    clearInterval(beepTimer);
}

function timer() {
    odd = !odd;

    if (odd) {
        // Every second time do not run full timer.
        if (armed && timerValue <= 10)
            play('beep');
        return;
    }
    else {
        if (armed) play('beep');
    }

    // Change time
    timerValue -= 1;
    advanceClock();

    // Kaboom
    if (timerValue == 0) {
        if (armed)
            kaboom();
        else
            timerReached();
        clearInterval(beepTimer);
    }

    // Blinking LED
    if (armed) {
        // Show LED
        $('#led').removeClass('hidden');
        // Hide LED
        window.setTimeout(function() {
            $('#led').addClass('hidden');
        }, 200);
    }
}

function advanceClock() {
    // Set countdown clock
    var minutes = Math.floor(timerValue / 60);
    var seconds = timerValue - (minutes * 60);
    if (seconds < 10) seconds = '0' + seconds;
    $('#timer-minutes').text(minutes);
    $('#timer-seconds').text(seconds);
    // Set progress bar
    var width = 100 * ((maxTime - timerValue) / maxTime);
    $('#progressbar').css('width', width + '%');
}

var bombTexts = {
    'neutral': 'Not armed',
    'arming': 'Arming',
    'armed': 'Armed',
    'disarming': 'Disarming',
    'disarmed': 'Disarmed',
    'exploded': 'Exploded'
}

// Bomb bar
function bombProgress(progress, state) {
    // Act on completed stage.
    $('#bomb-progress-container').removeClass('neutral arming armed disarming disarmed');
    $('#bomb-progress-container').addClass(state);
    $('#message').text(bombTexts[state]);
    $('#bomb-progress').css('width', (progress * 100) + '%');
}

// Overlay messages
function showOverlay(message) {
    $('#overlay-message').text(message);
    $('#overlay').removeClass('notvisible');
}

function clearOverlay() {
    $('#overlay').addClass('notvisible');
}

// Keypad
var code = '';
var guessed = '';
var next = '';

function initCodepad(len) {
    code = randomCode(len);
    guessed = '';
    next = nextNumber();
    highlight(next);
    var d = '';
    for (var i = 0; i < len; i++) d += '-';
    $('#display').text(d);
    $('#display').removeClass('correct');
}

function randomCode(len) {
    var min = 10 ** (len - 1);
    var max = 10 ** len - 1;
    return '' + Math.floor(Math.random()*(max-min+1)+min);
}

function nextNumber() {
    for (var i = 0; i < code.length; i++) {
        if (i == guessed.length) {
            return code[i];
        }
    }
}

function highlight(number) {
    // First remove highlight
    $('.cp').removeClass('highlight');

    // Wait a little and mark a new key
    window.setTimeout(function() {
        $('#code'+number).addClass('highlight');
    }, 500);
}

function numberPressed(number) {
    if (locked) {
        flashLock();
        play('beep');
        return;
    }
    if (!armed) {
        progress = armingProgress / armingSteps;
        bombProgress(progress, 'arming');
    }
    if (armed) {
        progress = disarmingProgress / disarmingSteps;
        bombProgress(progress, 'disarming');
    }

    if (number == next) {
        guessed += number;

        // Set display
        var d = guessed;
        for (var i = d.length; i < code.length; i++) d += '-';
        $('#display').text(d);

        // Get next number
        next = nextNumber();
        highlight(next);

        if (guessed == code) {
            // Guessed full code
            d += '-OK'
            $('#display').text(d);
            $('#display').addClass('correct');

            keypadFinished();
            play('done');
        }
        else {
            play('press');
        }
    } else {
        // Wrong keypress
        play('beep');

        // Lock it again
        lock();

        // Flash display
        //$('#display').addClass('wrong');
        //window.setTimeout(function () {
        //    $('#display').removeClass('wrong');
        //}, 200);
    }
}

function lock() {
    // TODO get right QR code and regular code
    //
    locked = true;
    $('#lock').removeClass('notvisible');
}

function delayLock() {
    window.setTimeout(lock, 1000);
}

function unlock() {
    locked = false;
    initCodepad(codeLength);
    $('#lock').addClass('notvisible');

    if (armed) bombProgress(0, 'disarming');
}

function flashLock() {
    $('#lock-image').addClass('shake');
    window.setTimeout(function () {
        $('#lock-image').removeClass('shake');
    }, 500);
}

// Sound bank
var sounds = {};

function initSounds(bombsite) {
    var folder = 'static/bombsite/'
    var suffix = bombsite + '.mp3'
    var s = sounds
    s['background'] = new Audio(folder + 'background1.mp3');
    s['beep'] = new Audio(folder + 'beep.mp3');
    s['beep'].volume = 0.15;
    s['defused'] = new Audio(folder + 'defused.mp3');
    s['done'] = new Audio(folder + 'done.mp3');
    s['done'].volume = 0.5;
    s['explosion'] = new Audio(folder + 'explosion' + suffix);
    s['planted'] = new Audio(folder + 'planted.mp3');
    s['press'] = new Audio(folder + 'press.mp3');
    s['press'].volume = 0.6;
    s['win-ct'] = new Audio(folder + 'win-ct.mp3');
    s['win-tr'] = new Audio(folder + 'win-tr.mp3');
    s['wind'] = new Audio(folder + 'wind' + suffix);
    s['wind'].loop = true;
}

function play(sound) {
    // Pause and time reset is to make sure
    // it restarts when still playing.
    sounds[sound].pause();
    sounds[sound].currentTime = 0;
    sounds[sound].play();
}

function stop(sound) {
    sounds[sound].pause();
    sounds[sound].currentTime = 0;
}

// Act on keypress
function keypress(e) {
    var key = e.which || e.keyCode;
    // Enter was pressed
    if (debug && key == 13) {
        unlock();
        return;
    }

    // Ensure entered key is a number
    if(48 <= key && key <=57) {
        var number = parseInt(String.fromCharCode(key));
        numberPressed(number);
        return;
    }

    if (locked) flashLock();
    play('beep');
}

// Finally start game
window.onload = function() {
    // Setup game
    initGame(bombsite);
    startGame();

    // Register keypress listener
    window.addEventListener("keypress", keypress);
}
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

const electron             = require('electron');
const path                 = require('path');
const storage              = require('electron-json-storage');
const app                  = electron.app;
const BrowserWindow        = electron.BrowserWindow;
const dirname              = __dirname || path.resolve(path.dirname());
const emberAppLocation     = `file://${dirname}/dist/index.html`;

let mainWindow = null;

// Uncomment the lines below to enable Electron's crash reporter
// For more information, see http://electron.atom.io/docs/api/crash-reporter/

// electron.crashReporter.start({
//     productName: 'YourName',
//     companyName: 'YourCompany',
//     submitURL: 'https://your-domain.com/url-to-submit',
//     autoSubmit: true
// });

app.on('window-all-closed', function onWindowAllClosed() {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

app.on('ready', function onReady() {
    mainWindow = new BrowserWindow({
        height: 600,
        width: 800,
        titleBarStyle: 'hidden-inset',
       'web-preferences': {
         'web-security': false
       }
    });

    delete mainWindow.module;

    // If you want to open up dev tools programmatically, call
    // mainWindow.openDevTools();

    // By default, we'll open the Ember App by directly going to the
    // file system.
    //
    // Please ensure that you have set the locationType option in the
    // config/environment.js file to 'hash'. For more information,
    // please consult the ember-electron readme.
    mainWindow.loadURL(emberAppLocation);

    // If a loading operation goes wrong, we'll send Electron back to
    // Ember App entry point
    mainWindow.webContents.on('did-fail-load', () => {
        mainWindow.loadURL(emberAppLocation);
    });

    mainWindow.webContents.on('crashed', () => {
        console.log('Your Ember app (or other code) in the main window has crashed.');
        console.log('This is a serious issue that needs to be handled and/or debugged.');
    });

    mainWindow.on('unresponsive', () => {
        console.log('Your Ember app (or other code) has made the window unresponsive.');
    });

    mainWindow.on('responsive', () => {
        console.log('The main window has become responsive again.');
    });

    mainWindow.on('closed', () => {
        mainWindow = null;
    });

    // Figure out better way to filter out the urls
    electron.session.defaultSession.webRequest.onHeadersReceived(
      { urls: ['http://localhost:4000/*', 'https://pro.usecanvas.com/*'] }, (details, cb) => {
      if (details.url.includes(`oauth/slack/callback`)) {
        const cookies = details.responseHeaders['set-cookie'][0].split('; ');
        const [, ...rest] = cookies[0].split('=');
        storage.set('csrf', rest.join('='));
      }
      cb({ cancel: false });
    });

    // Handle an unhandled error in the main thread
    //
    // Note that 'uncaughtException' is a crude mechanism for exception handling intended to
    // be used only as a last resort. The event should not be used as an equivalent to
    // "On Error Resume Next". Unhandled exceptions inherently mean that an application is in
    // an undefined state. Attempting to resume application code without properly recovering
    // from the exception can cause additional unforeseen and unpredictable issues.
    //
    // Attempting to resume normally after an uncaught exception can be similar to pulling out
    // of the power cord when upgrading a computer -- nine out of ten times nothing happens -
    // but the 10th time, the system becomes corrupted.
    //
    // The correct use of 'uncaughtException' is to perform synchronous cleanup of allocated
    // resources (e.g. file descriptors, handles, etc) before shutting down the process. It is
    // not safe to resume normal operation after 'uncaughtException'.
    process.on('uncaughtException', (err) => {
        console.log('An exception in the main thread was not handled.');
        console.log('This is a serious issue that needs to be handled and/or debugged.');
        console.log(`Exception: ${err}`);
    });
});
<commit_msg>s/4 spaces/2 spaces<commit_after>/* jshint node: true */
'use strict';

const electron             = require('electron');
const path                 = require('path');
const storage              = require('electron-json-storage');
const app                  = electron.app;
const BrowserWindow        = electron.BrowserWindow;
const dirname              = __dirname || path.resolve(path.dirname());
const emberAppLocation     = `file://${dirname}/dist/index.html`;

let mainWindow = null;

// Uncomment the lines below to enable Electron's crash reporter
// For more information, see http://electron.atom.io/docs/api/crash-reporter/

// electron.crashReporter.start({
//     productName: 'YourName',
//     companyName: 'YourCompany',
//     submitURL: 'https://your-domain.com/url-to-submit',
//     autoSubmit: true
// });

app.on('window-all-closed', function onWindowAllClosed() {
  if (process.platform !== 'darwin') {
      app.quit();
  }
});

app.on('ready', function onReady() {
  mainWindow = new BrowserWindow({
    height: 600,
    width: 800,
    titleBarStyle: 'hidden-inset',
   'web-preferences': {
     'web-security': false
   }
  });

  delete mainWindow.module;

  // If you want to open up dev tools programmatically, call
  // mainWindow.openDevTools();

  // By default, we'll open the Ember App by directly going to the
  // file system.
  //
  // Please ensure that you have set the locationType option in the
  // config/environment.js file to 'hash'. For more information,
  // please consult the ember-electron readme.
  mainWindow.loadURL(emberAppLocation);

  // If a loading operation goes wrong, we'll send Electron back to
  // Ember App entry point
  mainWindow.webContents.on('did-fail-load', () => {
    mainWindow.loadURL(emberAppLocation);
  });

  mainWindow.webContents.on('crashed', () => {
    console.log('Your Ember app (or other code) in the main window has crashed.');
    console.log('This is a serious issue that needs to be handled and/or debugged.');
  });

  mainWindow.on('unresponsive', () => {
    console.log('Your Ember app (or other code) has made the window unresponsive.');
  });

  mainWindow.on('responsive', () => {
    console.log('The main window has become responsive again.');
  });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  // Figure out better way to filter out the urls
  electron.session.defaultSession.webRequest.onHeadersReceived(
    { urls: ['http://localhost:4000/*', 'https://pro.usecanvas.com/*'] }, (details, cb) => {
    if (details.url.includes(`oauth/slack/callback`)) {
      const cookies = details.responseHeaders['set-cookie'][0].split('; ');
      const [, ...rest] = cookies[0].split('=');
      storage.set('csrf', rest.join('='));
    }
    cb({ cancel: false });
  });

  // Handle an unhandled error in the main thread
  //
  // Note that 'uncaughtException' is a crude mechanism for exception handling intended to
  // be used only as a last resort. The event should not be used as an equivalent to
  // "On Error Resume Next". Unhandled exceptions inherently mean that an application is in
  // an undefined state. Attempting to resume application code without properly recovering
  // from the exception can cause additional unforeseen and unpredictable issues.
  //
  // Attempting to resume normally after an uncaught exception can be similar to pulling out
  // of the power cord when upgrading a computer -- nine out of ten times nothing happens -
  // but the 10th time, the system becomes corrupted.
  //
  // The correct use of 'uncaughtException' is to perform synchronous cleanup of allocated
  // resources (e.g. file descriptors, handles, etc) before shutting down the process. It is
  // not safe to resume normal operation after 'uncaughtException'.
  process.on('uncaughtException', (err) => {
    console.log('An exception in the main thread was not handled.');
    console.log('This is a serious issue that needs to be handled and/or debugged.');
    console.log(`Exception: ${err}`);
  });
});
<|endoftext|>


<commit_before>export default function CustomersResource({apiHandler}) {
    return {
        async getAll({limit = null, offset = null, sort = null, expand = '', filter = '', q = '', criteria = ''}) {
            const params = {
                limit,
                offset,
                sort,
                expand,
                filter,
                q,
                criteria
            };
            return await apiHandler.getAll(`customers`, params);
        },

        async get({id}) {
            return await apiHandler.get(`customers/${id}`);
        },

        async create({id = '', data}) {
            return await apiHandler.create(`customers/${id}`, data);
        },

        async update({id, data}) {
            return await apiHandler.put(`customers/${id}`, data);
        },

        async getLeadSource({id}) {
            return await apiHandler.get(`customers/${id}/lead-source`);
        },

        async createLeadSource({id, data}) {
            return await apiHandler.put(`customers/${id}/lead-source`, data);
        },

        async deleteLeadSource({id}) {
            return await apiHandler.delete(`customers/${id}/lead-source`);
        }
    };
};
<commit_msg>Add default value for customer getAll<commit_after>export default function CustomersResource({apiHandler}) {
    return {
        async getAll({limit = null, offset = null, sort = null, expand = '', filter = '', q = '', criteria = ''} = {}) {
            const params = {
                limit,
                offset,
                sort,
                expand,
                filter,
                q,
                criteria
            };
            return await apiHandler.getAll(`customers`, params);
        },

        async get({id}) {
            return await apiHandler.get(`customers/${id}`);
        },

        async create({id = '', data}) {
            return await apiHandler.create(`customers/${id}`, data);
        },

        async update({id, data}) {
            return await apiHandler.put(`customers/${id}`, data);
        },

        async getLeadSource({id}) {
            return await apiHandler.get(`customers/${id}/lead-source`);
        },

        async createLeadSource({id, data}) {
            return await apiHandler.put(`customers/${id}/lead-source`, data);
        },

        async deleteLeadSource({id}) {
            return await apiHandler.delete(`customers/${id}/lead-source`);
        }
    };
};
<|endoftext|>


<commit_before>/**
* @title Progressive Consent Capture
* @overview Uses a widget to capture missing consents and preferences at login to boost engagement and support compliance
* @gallery true
* @category marketplace
*
* Consentric provides an integration to extend Auth0's universal login to include collection of consent as part of the authentication and sign up flows.
*
*/
function consentricIntegration(user, context, callback) {
    const axios = require('axios@0.19.2');
    const moment = require('moment@2.11.2');

    const asMilliSeconds = (seconds) => seconds * 1000;

    const {
        CONSENTRIC_AUTH_HOST,
        CONSENTRIC_API_HOST,
        CONSENTRIC_AUDIENCE,
        CONSENTRIC_CLIENT_ID,
        CONSENTRIC_CLIENT_SECRET,
        CONSENTRIC_APPLICATION_ID,
        CONSENTRIC_REDIRECT_URL
    } = configuration;

    const consentricAuth = axios.create({
        baseURL: CONSENTRIC_AUTH_HOST,
        timeout: 1000,
    });

    const consentricApi = axios.create({
        baseURL: CONSENTRIC_API_HOST,
        timeout: 1000,
    });

    // Returns Consentric API Access Token (JWT) from either the global cache or generates it anew from clientId and secret
    const getConsentricApiAccessToken = async () => {
        const consentricApiTokenExists = (!global.consentricApiToken) ||
            global.consentricApiToken.expires < new Date().getTime();

        if (consentricApiTokenExists) {
            try {
                // Exchange Credentials for Consentric Api Access token
                const { data: { expires_in, access_token } } = await consentricAuth
                    .post('/oauth/token', {
                        grant_type: 'client_credentials',
                        client_id: CONSENTRIC_CLIENT_ID,
                        client_secret: CONSENTRIC_CLIENT_SECRET,
                        audience: CONSENTRIC_AUDIENCE,
                        applicationId: CONSENTRIC_APPLICATION_ID,
                    });

                const expiryInMs = new Date().getTime() + asMilliSeconds(expires_in);
                const auth = {
                    jwt: access_token,
                    exp: expiryInMs
                };

                //Persist API Access token in global properties
                global.consentricApiToken = auth;

            } catch (error) {
                console.error(error);
            }
        }

        return global.consentricApiToken;
    };

    //Creates Citizen Record in Consentric with Auth0 Id
    const createCitizen = ({ userRef, apiAccessToken }) => {
        console.log(`Upserting Consentric Citizen record for ${userRef}`);
        const data = {
            applicationId: CONSENTRIC_APPLICATION_ID,
            externalRef: userRef,
        };

        return consentricApi
            .post('/v1/citizens', data, {
                headers: {
                    Authorization: 'Bearer ' + apiAccessToken
                },
            })
            .catch(err => {
                if (err.response.status !== 409) { // 409 indicates Citizen with given reference already exists in Consentric
                    console.error(err);
                }
            });
    };

    // Function to retrieve Consentric User Token from User Metadata
    const getConsentricUserTokenFromMetadata = user => user.app_metadata && user.app_metadata.consentric;

    // Generates On Demand Consentric User Token for the given User using the API Access Token
    const generateConsentricUserAccessToken = async ({ userRef, apiAccessToken }) => {
        try {
            console.log(`Attempting to generate access token API for ${userRef} with jwt [${apiAccessToken.substring(0, 10)}]`);

            const { data: { token, expiryDate: exp } } = await consentricApi
                .post('/v1/access-tokens/tokens',
                    {
                        applicationId: CONSENTRIC_APPLICATION_ID,
                        externalRef: userRef,
                        expiryDate: moment().add(3, 'months').toISOString()
                    },
                    {
                        headers: {
                            Authorization: 'Bearer ' + apiAccessToken
                        }
                    }
                );

            return {
                token,
                exp
            };

        } catch (err) {
            console.error(err);
        }
    };

    const loadConsentricUserAccessToken = async ({ user }) => {
        try {
            const metadataUserToken = getConsentricUserTokenFromMetadata(user);
            if ((metadataUserToken) && moment(metadataUserToken.expires).isAfter(moment())) return metadataUserToken;

            const { jwt: apiAccessToken } = await getConsentricApiAccessToken();
            const delimIdx = user.user_id.indexOf('|');
            const userRef = user.user_id.substring(delimIdx + 1);

            const apiCredentials = {
                userRef,
                apiAccessToken,
            };

            //Create Citizen with Auth0 UserId
            await createCitizen(apiCredentials);

            //Generate an On Demand Access Token for the created citizen
            const generatedToken = await generateConsentricUserAccessToken(apiCredentials);

            // Persist the app_metadata update
            await auth0.users.updateAppMetadata(user.user_id, { ...user.app_metadata, consentric: generatedToken });

            return generatedToken;

        } catch (err) {
            console.error(`Issue Loading Consentric User Access Token for user ${user.user_id} - ${err}`);
        }
    };

    const initConsentricFlow = async () => {

        const { token } = await loadConsentricUserAccessToken({ user });
        const urlConnector = CONSENTRIC_REDIRECT_URL.includes('?') ? '&' : '?';
        const redirectUrl = CONSENTRIC_REDIRECT_URL + urlConnector + 'token=' + token;

        context.redirect = {
            url: redirectUrl
        };

        return callback(null, user, context);
    };

    if (context.protocol !== "redirect-callback") {
        return initConsentricFlow();
    } else {
        // Run after Redirect
        return callback(null, user, context);
    }
}<commit_msg>Added check to ignore consent edirect on silent authentication.<commit_after>/**
* @title Progressive Consent Capture
* @overview Uses a widget to capture missing consents and preferences at login to boost engagement and support compliance
* @gallery true
* @category marketplace
*
* Consentric provides an integration to extend Auth0's universal login to include collection of consent as part of the authentication and sign up flows.
*
*/
function consentricIntegration(user, context, callback) {
    const axios = require('axios@0.19.2');
    const moment = require('moment@2.11.2');

    const asMilliSeconds = (seconds) => seconds * 1000;

    const {
        CONSENTRIC_AUTH_HOST,
        CONSENTRIC_API_HOST,
        CONSENTRIC_AUDIENCE,
        CONSENTRIC_CLIENT_ID,
        CONSENTRIC_CLIENT_SECRET,
        CONSENTRIC_APPLICATION_ID,
        CONSENTRIC_REDIRECT_URL
    } = configuration;

    const consentricAuth = axios.create({
        baseURL: CONSENTRIC_AUTH_HOST,
        timeout: 1000,
    });

    const consentricApi = axios.create({
        baseURL: CONSENTRIC_API_HOST,
        timeout: 1000,
    });

    // Returns Consentric API Access Token (JWT) from either the global cache or generates it anew from clientId and secret
    const getConsentricApiAccessToken = async () => {
        const consentricApiTokenExists = (!global.consentricApiToken) ||
            global.consentricApiToken.expires < new Date().getTime();

        if (consentricApiTokenExists) {
            try {
                // Exchange Credentials for Consentric Api Access token
                const { data: { expires_in, access_token } } = await consentricAuth
                    .post('/oauth/token', {
                        grant_type: 'client_credentials',
                        client_id: CONSENTRIC_CLIENT_ID,
                        client_secret: CONSENTRIC_CLIENT_SECRET,
                        audience: CONSENTRIC_AUDIENCE,
                        applicationId: CONSENTRIC_APPLICATION_ID,
                    });

                const expiryInMs = new Date().getTime() + asMilliSeconds(expires_in);
                const auth = {
                    jwt: access_token,
                    exp: expiryInMs
                };

                //Persist API Access token in global properties
                global.consentricApiToken = auth;

            } catch (error) {
                console.error(error);
            }
        }

        return global.consentricApiToken;
    };

    //Creates Citizen Record in Consentric with Auth0 Id
    const createCitizen = ({ userRef, apiAccessToken }) => {
        console.log(`Upserting Consentric Citizen record for ${userRef}`);
        const data = {
            applicationId: CONSENTRIC_APPLICATION_ID,
            externalRef: userRef,
        };

        return consentricApi
            .post('/v1/citizens', data, {
                headers: {
                    Authorization: 'Bearer ' + apiAccessToken
                },
            })
            .catch(err => {
                if (err.response.status !== 409) { // 409 indicates Citizen with given reference already exists in Consentric
                    console.error(err);
                }
            });
    };

    // Function to retrieve Consentric User Token from User Metadata
    const getConsentricUserTokenFromMetadata = user => user.app_metadata && user.app_metadata.consentric;

    // Generates On Demand Consentric User Token for the given User using the API Access Token
    const generateConsentricUserAccessToken = async ({ userRef, apiAccessToken }) => {
        try {
            console.log(`Attempting to generate access token API for ${userRef} with jwt [${apiAccessToken.substring(0, 10)}]`);

            const { data: { token, expiryDate: exp } } = await consentricApi
                .post('/v1/access-tokens/tokens',
                    {
                        applicationId: CONSENTRIC_APPLICATION_ID,
                        externalRef: userRef,
                        expiryDate: moment().add(3, 'months').toISOString()
                    },
                    {
                        headers: {
                            Authorization: 'Bearer ' + apiAccessToken
                        }
                    }
                );

            return {
                token,
                exp
            };

        } catch (err) {
            console.error(err);
        }
    };

    const loadConsentricUserAccessToken = async ({ user }) => {
        try {
            const metadataUserToken = getConsentricUserTokenFromMetadata(user);
            if ((metadataUserToken) && moment(metadataUserToken.expires).isAfter(moment())) return metadataUserToken;

            const { jwt: apiAccessToken } = await getConsentricApiAccessToken();
            const delimIdx = user.user_id.indexOf('|');
            const userRef = user.user_id.substring(delimIdx + 1);

            const apiCredentials = {
                userRef,
                apiAccessToken,
            };

            //Create Citizen with Auth0 UserId
            await createCitizen(apiCredentials);

            //Generate an On Demand Access Token for the created citizen
            const generatedToken = await generateConsentricUserAccessToken(apiCredentials);

            // Persist the app_metadata update
            await auth0.users.updateAppMetadata(user.user_id, { ...user.app_metadata, consentric: generatedToken });

            return generatedToken;

        } catch (err) {
            console.error(`Issue Loading Consentric User Access Token for user ${user.user_id} - ${err}`);
        }
    };

    const initConsentricFlow = async () => {

        const { token } = await loadConsentricUserAccessToken({ user });
        const urlConnector = CONSENTRIC_REDIRECT_URL.includes('?') ? '&' : '?';
        const redirectUrl = CONSENTRIC_REDIRECT_URL + urlConnector + 'token=' + token;

        context.redirect = {
            url: redirectUrl
        };

        return callback(null, user, context);
    };

    if (context.protocol !== "redirect-callback" && context.request.query.prompt !== 'none') {
        return initConsentricFlow();
    } else {
        // Run after Redirect
        return callback(null, user, context);
    }
}<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */

sap.ui.define(['jquery.sap.global', 'sap/m/PageAccessibleLandmarkInfo'],
	function(jQuery, PageAccessibleLandmarkInfo) {
	"use strict";

	/**
	 * Page renderer.
	 * @namespace
	 */
	var PageRenderer = {};

	/**
	 * Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
	 *
	 * @param {sap.ui.core.RenderManager} rm the RenderManager that can be used for writing to the Render-Output-Buffer
	 * @param {sap.ui.core.Control} oPage an object representation of the control that should be rendered
	 */
	PageRenderer.render = function(rm, oPage) {
		var oHeader = null,
			oFooter = null,
			oSubHeader = null,
			sEnableScrolling = oPage.getEnableScrolling() ? " sapMPageScrollEnabled" : "";

		if (oPage.getShowHeader()) {
			oHeader = oPage._getAnyHeader();
		}

		if (oPage.getShowSubHeader()) {
			oSubHeader = oPage.getSubHeader();
		}

		if (oPage.getShowFooter()) {
			oFooter = oPage.getFooter();
		}
		rm.write("<div");
		rm.writeControlData(oPage);
		rm.addClass("sapMPage");

		rm.addClass("sapMPageBg" + oPage.getBackgroundDesign());

		if (oHeader) {
			rm.addClass("sapMPageWithHeader");
		}

		if (oSubHeader) {
			rm.addClass("sapMPageWithSubHeader");
		}

		if (oFooter) {
			// it is used in the PopOver to remove additional margin bottom for page with footer
			rm.addClass("sapMPageWithFooter");
		}

		if (!oPage.getContentOnlyBusy()) {
			rm.addClass("sapMPageBusyCoversAll");
		}

		rm.writeClasses();

		var sTooltip = oPage.getTooltip_AsString();

		if (sTooltip) {
			rm.writeAttributeEscaped("title", sTooltip);
		}

		PageAccessibleLandmarkInfo._writeLandmarkInfo(rm, oPage, "root");

		rm.write(">");

		//render headers
		this.renderBarControl(rm, oPage, oHeader, {
			context : "header",
			styleClass : "sapMPageHeader"
		});

		this.renderBarControl(rm, oPage, oSubHeader, {
			context : "subHeader",
			styleClass : "sapMPageSubHeader"
		});

		// render child controls
		rm.write('
');

		if (oPage._bUseScrollDiv) { // fallback to old rendering
			rm.write('
');
		}

		var aContent = oPage.getContent();
		var l = aContent.length;

		for (var i = 0; i < l; i++) {
			rm.renderControl(aContent[i]);
		}

		if (oPage._bUseScrollDiv) { // fallback to old rendering
			rm.write("
");
		}

		rm.write("
");

		// render footer Element
		this.renderBarControl(rm, oPage, oFooter, {
			context : "footer",
			styleClass : "sapMPageFooter"
		});

		rm.write("
");
	};

	/**
	 * Renders the bar control if it is defined. Also adds classes to it.
	 *
	 * @param {sap.ui.core.RenderManager} rm the RenderManager that can be used for writing to the Render-Output-Buffer
	 * @param {sap.m.IBar} oBarControl the RenderManager that can be used for writing to the Render-Output-Buffer
	 * @param {object} oOptions object containing the tag, contextClass and styleClass added to the bar
	 */
	PageRenderer.renderBarControl = function (rm, oPage, oBarControl, oOptions) {
		if (!oBarControl) {
			return;
		}

		oBarControl.applyTagAndContextClassFor(oOptions.context.toLowerCase());

		oBarControl._setLandmarkInfo(oPage.getLandmarkInfo(), oOptions.context);

		oBarControl.addStyleClass(oOptions.styleClass);

		rm.renderControl(oBarControl);
	};

	return PageRenderer;

}, /* bExport= */ true);
<commit_msg>[INTERNAL] sap.m.Page: use hungarian notation in the renderer<commit_after>/*!
 * ${copyright}
 */

sap.ui.define(['jquery.sap.global', 'sap/m/PageAccessibleLandmarkInfo'],
	function(jQuery, PageAccessibleLandmarkInfo) {
	"use strict";

	/**
	 * Page renderer.
	 * @namespace
	 */
	var PageRenderer = {};

	/**
	 * Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the Render-Output-Buffer
	 * @param {sap.ui.core.Control} oPage an object representation of the control that should be rendered
	 */
	PageRenderer.render = function(oRm, oPage) {
		var oHeader = null,
			oFooter = null,
			oSubHeader = null,
			sEnableScrolling = oPage.getEnableScrolling() ? " sapMPageScrollEnabled" : "";

		if (oPage.getShowHeader()) {
			oHeader = oPage._getAnyHeader();
		}

		if (oPage.getShowSubHeader()) {
			oSubHeader = oPage.getSubHeader();
		}

		if (oPage.getShowFooter()) {
			oFooter = oPage.getFooter();
		}
		oRm.write("<div");
		oRm.writeControlData(oPage);
		oRm.addClass("sapMPage");

		oRm.addClass("sapMPageBg" + oPage.getBackgroundDesign());

		if (oHeader) {
			oRm.addClass("sapMPageWithHeader");
		}

		if (oSubHeader) {
			oRm.addClass("sapMPageWithSubHeader");
		}

		if (oFooter) {
			// it is used in the PopOver to remove additional margin bottom for page with footer
			oRm.addClass("sapMPageWithFooter");
		}

		if (!oPage.getContentOnlyBusy()) {
			oRm.addClass("sapMPageBusyCoversAll");
		}

		oRm.writeClasses();

		var sTooltip = oPage.getTooltip_AsString();

		if (sTooltip) {
			oRm.writeAttributeEscaped("title", sTooltip);
		}

		PageAccessibleLandmarkInfo._writeLandmarkInfo(oRm, oPage, "root");

		oRm.write(">");

		//render headers
		this.renderBarControl(oRm, oPage, oHeader, {
			context : "header",
			styleClass : "sapMPageHeader"
		});

		this.renderBarControl(oRm, oPage, oSubHeader, {
			context : "subHeader",
			styleClass : "sapMPageSubHeader"
		});

		// render child controls
		oRm.write('
');

		if (oPage._bUseScrollDiv) { // fallback to old rendering
			oRm.write('
');
		}

		var aContent = oPage.getContent();
		var l = aContent.length;

		for (var i = 0; i < l; i++) {
			oRm.renderControl(aContent[i]);
		}

		if (oPage._bUseScrollDiv) { // fallback to old rendering
			oRm.write("
");
		}

		oRm.write("
");

		// render footer Element
		this.renderBarControl(oRm, oPage, oFooter, {
			context : "footer",
			styleClass : "sapMPageFooter"
		});

		oRm.write("
");
	};

	/**
	 * Renders the bar control if it is defined. Also adds classes to it.
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the Render-Output-Buffer
	 * @param {sap.m.IBar} oBarControl the RenderManager that can be used for writing to the Render-Output-Buffer
	 * @param {object} oOptions object containing the tag, contextClass and styleClass added to the bar
	 */
	PageRenderer.renderBarControl = function (oRm, oPage, oBarControl, oOptions) {
		if (!oBarControl) {
			return;
		}

		oBarControl.applyTagAndContextClassFor(oOptions.context.toLowerCase());

		oBarControl._setLandmarkInfo(oPage.getLandmarkInfo(), oOptions.context);

		oBarControl.addStyleClass(oOptions.styleClass);

		oRm.renderControl(oBarControl);
	};

	return PageRenderer;

}, /* bExport= */ true);
<|endoftext|>


<commit_before>(function () {
    "use strict";

    var argv, express, corser, mongo, app, url;

    argv = require("optimist")
             .options("port", {
                 default: 1337,
                 describe: "Port"
             })
             .options("connection-string", {
                 default: "mongodb://localhost/ming",
                 describe: "MongoDB Connection String for the default deployment."
             })
             .options("enable-proxying", {
                 default: false,
                 describe: "Allow connections to other MongoDB deployments."
             })
             .argv;
    express = require("express");
    url = require("url");
    corser = require("corser");
    mongo = require("mongodb");

    app = express();

 // Handle CORS.
    app.use(corser.create({
        methods: corser.simpleMethods.concat(["DELETE"]),
        requestHeaders: corser.simpleRequestHeaders.concat(["Authorization", "X-Connection-String"]),
        responseHeaders: corser.simpleResponseHeaders.concat(["Location"])
    }));
    app.use(function (req, res, next) {
        if (req.method === "OPTIONS") {
            res.writeHead(204);
            res.end();
        } else {
            next();
        }
    });

 // Prepare MongoDB client.
    app.use(function (req, res, next) {
        var connectionString;
        if (argv["enable-proxying"] === true && req.headers.hasOwnProperty("x-connection-string") === true) {
            connectionString = req.headers["x-connection-string"];
        } else {
            connectionString = argv["connection-string"];
        }
        req.connectionString = url.parse(connectionString);
        mongo.MongoClient.connect(connectionString, function (err, db) {
            if (err !== null) {
                next(err);
            } else {
                req.db = db;
                next();
            }
        });
    });

 // Basic auth.
    app.use(function (req, res, next) {
        var basicAuth;
        basicAuth = express.basicAuth(function (username, password, callback) {
            req.db.authenticate(username, password, function (err) {
                if (err !== null) {
                 // Close database if authentication fails.
                    req.db.close();
                    callback(err, null);
                } else {
                    callback(null, username);
                }
            });
        }, "MongoDB");
        basicAuth(req, res, next);
    });

    app.get("/", function (req, res) {
        req.db.collectionNames({
            namesOnly: true
        }, function (err, collections) {
            var names;
            names = collections.map(function (collection) {
             // Strip database name.
                return collection.substring(req.connectionString.path.length);
            });
            res.send({
                collections: names
            });
            req.db.close();
        });
    });

    app.get("/:collection", function (req, res) {
        var collectionParam;
        collectionParam = req.params.collection;
        req.db.collection(collectionParam, function (err, collection) {
            collection.find().count(function (err, count) {
                res.send({count: count});
                req.db.close();
            });
        });
    });

    app.get("/:prefix.files/:file", function (req, res, next) {
        var prefixParam, fileParam;
        prefixParam = req.params.prefix;
        fileParam = req.params.file;
        req.db.collection(prefixParam + ".files", function (err, collection) {
            var id;
            try {
                id = new mongo.ObjectID(fileParam);
             // Get metadata first.
                collection.findOne({
                    _id: id
                }, function (err, document) {
                    var grid;
                    if (document === null) {
                     // Route to catch-all.
                        next();
                    } else {
                        if (req.query.hasOwnProperty("binary") === true && req.query.binary === "true") {
                            grid = new mongo.Grid(req.db, prefixParam);
                            grid.get(id, function (err, file) {
                                var fileType;
                             // Guess file type from file extension.
                                fileType = document.filename.match(/(\.\w+)$/)[1];
                                res.type(fileType);
                                res.send(file);
                                req.db.close();
                            });
                        } else {
                            res.send(document);
                            req.db.close();
                        }
                    }
                });
            } catch (e) {
             // Route to catch-all.
                next();
            }
        });
    });

    app.get("/:collection/:document", function (req, res, next) {
        var collectionParam, documentParam;
        collectionParam = req.params.collection;
        documentParam = req.params.document;
        req.db.collection(collectionParam, function (err, collection) {
            var id;
            try {
                id = new mongo.ObjectID(documentParam);
                collection.findOne({
                    _id: id
                }, function (err, document) {
                    if (document === null) {
                     // Route to catch-all.
                        next();
                    } else {
                        res.send(document);
                    }
                    req.db.close();
                });
            } catch (e) {
             // Route to catch-all.
                next();
            }
        });
    });

    app.get("/:collection/:document/:field", function (req, res, next) {
        var collectionParam, documentParam, fieldParam;
        collectionParam = req.params.collection;
        documentParam = req.params.document;
        fieldParam = req.params.field;
        req.db.collection(collectionParam, function (err, collection) {
            var id, fields;
            try {
                id = new mongo.ObjectID(documentParam);
                fields = {};
                fields[fieldParam] = 1;
                collection.findOne({
                    _id: id
                }, {
                    fields: fields
                }, function (err, document) {
                    if (document === null || document.hasOwnProperty(fieldParam) === false) {
                     // Route to catch-all.
                        next();
                    } else {
                        res.send(document[fieldParam]);
                    }
                    req.db.close();
                });
            } catch (e) {
             // Route to catch-all.
                next();
            }
        });
    });

    app.post("/:collection/query", express.json(), function (req, res) {
        var collectionParam;
        collectionParam = req.params.collection;
        req.db.collection(collectionParam, function (err, collection) {
            var options;
            options = {};
            if (req.query.limit) {
                options.limit = req.query.limit;
            }
            if (req.query.skip) {
                options.skip = req.query.skip;
            }
            if (req.query.sort) {
                options.sort = req.query.sort;
            }
            collection.find(req.body, options).toArray(function (err, documents) {
                res.send(documents);
                req.db.close();
            });
        });
    });

    app.post("/:collection", express.json(), function (req, res) {
        var collectionParam, payload;
        collectionParam = req.params.collection;
        payload = req.body;
        req.db.collection(collectionParam, function (err, collection) {
            collection.insert(payload, function (err, document) {
                res.location(collectionParam + "/" + document[0]._id.toHexString());
                res.send(201, "Created");
                req.db.close();
            });
        });
    });

    app.delete("/:collection/:document", function (req, res, next) {
        var collectionParam, documentParam;
        collectionParam = req.params.collection;
        documentParam = req.params.document;
        req.db.collection(collectionParam, function (err, collection) {
            var id;
            try {
                id = new mongo.ObjectID(documentParam);
                collection.remove({
                    _id: id
                }, function (err, num) {
                    if (num === 0) {
                     // Route to catch-all.
                        next();
                    } else {
                        res.send(200, "Deleted");
                    }
                    req.db.close();
                });
            } catch (e) {
             // Route to catch-all.
                next();
            }
        });
    });

 // Catch-all.
    app.use(function (req, res) {
        req.db.close();
        res.send(404, "Not Found");
    });

 // Error handler.
    app.use(function (err, req, res, next) {
        if (req.hasOwnProperty("db") === true) {
            req.db.close();
        }
        res.send(500, "Internal Server Error");
    });

    app.listen(argv.port);

    console.log("Ming is running on port " + argv.port + ", connected to " + argv["connection-string"]);

}());
<commit_msg>Reorder declarations.<commit_after>(function () {
    "use strict";

    var argv, express, corser, mongo, url, app;

    argv = require("optimist")
             .options("port", {
                 default: 1337,
                 describe: "Port"
             })
             .options("connection-string", {
                 default: "mongodb://localhost/ming",
                 describe: "MongoDB Connection String for the default deployment."
             })
             .options("enable-proxying", {
                 default: false,
                 describe: "Allow connections to other MongoDB deployments."
             })
             .argv;
    express = require("express");
    corser = require("corser");
    mongo = require("mongodb");
    url = require("url");

    app = express();

 // Handle CORS.
    app.use(corser.create({
        methods: corser.simpleMethods.concat(["DELETE"]),
        requestHeaders: corser.simpleRequestHeaders.concat(["Authorization", "X-Connection-String"]),
        responseHeaders: corser.simpleResponseHeaders.concat(["Location"])
    }));
    app.use(function (req, res, next) {
        if (req.method === "OPTIONS") {
            res.writeHead(204);
            res.end();
        } else {
            next();
        }
    });

 // Prepare MongoDB client.
    app.use(function (req, res, next) {
        var connectionString;
        if (argv["enable-proxying"] === true && req.headers.hasOwnProperty("x-connection-string") === true) {
            connectionString = req.headers["x-connection-string"];
        } else {
            connectionString = argv["connection-string"];
        }
        req.connectionString = url.parse(connectionString);
        mongo.MongoClient.connect(connectionString, function (err, db) {
            if (err !== null) {
                next(err);
            } else {
                req.db = db;
                next();
            }
        });
    });

 // Basic auth.
    app.use(function (req, res, next) {
        var basicAuth;
        basicAuth = express.basicAuth(function (username, password, callback) {
            req.db.authenticate(username, password, function (err) {
                if (err !== null) {
                 // Close database if authentication fails.
                    req.db.close();
                    callback(err, null);
                } else {
                    callback(null, username);
                }
            });
        }, "MongoDB");
        basicAuth(req, res, next);
    });

    app.get("/", function (req, res) {
        req.db.collectionNames({
            namesOnly: true
        }, function (err, collections) {
            var names;
            names = collections.map(function (collection) {
             // Strip database name.
                return collection.substring(req.connectionString.path.length);
            });
            res.send({
                collections: names
            });
            req.db.close();
        });
    });

    app.get("/:collection", function (req, res) {
        var collectionParam;
        collectionParam = req.params.collection;
        req.db.collection(collectionParam, function (err, collection) {
            collection.find().count(function (err, count) {
                res.send({count: count});
                req.db.close();
            });
        });
    });

    app.get("/:prefix.files/:file", function (req, res, next) {
        var prefixParam, fileParam;
        prefixParam = req.params.prefix;
        fileParam = req.params.file;
        req.db.collection(prefixParam + ".files", function (err, collection) {
            var id;
            try {
                id = new mongo.ObjectID(fileParam);
             // Get metadata first.
                collection.findOne({
                    _id: id
                }, function (err, document) {
                    var grid;
                    if (document === null) {
                     // Route to catch-all.
                        next();
                    } else {
                        if (req.query.hasOwnProperty("binary") === true && req.query.binary === "true") {
                            grid = new mongo.Grid(req.db, prefixParam);
                            grid.get(id, function (err, file) {
                                var fileType;
                             // Guess file type from file extension.
                                fileType = document.filename.match(/(\.\w+)$/)[1];
                                res.type(fileType);
                                res.send(file);
                                req.db.close();
                            });
                        } else {
                            res.send(document);
                            req.db.close();
                        }
                    }
                });
            } catch (e) {
             // Route to catch-all.
                next();
            }
        });
    });

    app.get("/:collection/:document", function (req, res, next) {
        var collectionParam, documentParam;
        collectionParam = req.params.collection;
        documentParam = req.params.document;
        req.db.collection(collectionParam, function (err, collection) {
            var id;
            try {
                id = new mongo.ObjectID(documentParam);
                collection.findOne({
                    _id: id
                }, function (err, document) {
                    if (document === null) {
                     // Route to catch-all.
                        next();
                    } else {
                        res.send(document);
                    }
                    req.db.close();
                });
            } catch (e) {
             // Route to catch-all.
                next();
            }
        });
    });

    app.get("/:collection/:document/:field", function (req, res, next) {
        var collectionParam, documentParam, fieldParam;
        collectionParam = req.params.collection;
        documentParam = req.params.document;
        fieldParam = req.params.field;
        req.db.collection(collectionParam, function (err, collection) {
            var id, fields;
            try {
                id = new mongo.ObjectID(documentParam);
                fields = {};
                fields[fieldParam] = 1;
                collection.findOne({
                    _id: id
                }, {
                    fields: fields
                }, function (err, document) {
                    if (document === null || document.hasOwnProperty(fieldParam) === false) {
                     // Route to catch-all.
                        next();
                    } else {
                        res.send(document[fieldParam]);
                    }
                    req.db.close();
                });
            } catch (e) {
             // Route to catch-all.
                next();
            }
        });
    });

    app.post("/:collection/query", express.json(), function (req, res) {
        var collectionParam;
        collectionParam = req.params.collection;
        req.db.collection(collectionParam, function (err, collection) {
            var options;
            options = {};
            if (req.query.limit) {
                options.limit = req.query.limit;
            }
            if (req.query.skip) {
                options.skip = req.query.skip;
            }
            if (req.query.sort) {
                options.sort = req.query.sort;
            }
            collection.find(req.body, options).toArray(function (err, documents) {
                res.send(documents);
                req.db.close();
            });
        });
    });

    app.post("/:collection", express.json(), function (req, res) {
        var collectionParam, payload;
        collectionParam = req.params.collection;
        payload = req.body;
        req.db.collection(collectionParam, function (err, collection) {
            collection.insert(payload, function (err, document) {
                res.location(collectionParam + "/" + document[0]._id.toHexString());
                res.send(201, "Created");
                req.db.close();
            });
        });
    });

    app.delete("/:collection/:document", function (req, res, next) {
        var collectionParam, documentParam;
        collectionParam = req.params.collection;
        documentParam = req.params.document;
        req.db.collection(collectionParam, function (err, collection) {
            var id;
            try {
                id = new mongo.ObjectID(documentParam);
                collection.remove({
                    _id: id
                }, function (err, num) {
                    if (num === 0) {
                     // Route to catch-all.
                        next();
                    } else {
                        res.send(200, "Deleted");
                    }
                    req.db.close();
                });
            } catch (e) {
             // Route to catch-all.
                next();
            }
        });
    });

 // Catch-all.
    app.use(function (req, res) {
        req.db.close();
        res.send(404, "Not Found");
    });

 // Error handler.
    app.use(function (err, req, res, next) {
        if (req.hasOwnProperty("db") === true) {
            req.db.close();
        }
        res.send(500, "Internal Server Error");
    });

    app.listen(argv.port);

    console.log("Ming is running on port " + argv.port + ", connected to " + argv["connection-string"]);

}());
<|endoftext|>


<commit_before>import {inject, NewInstance}  from 'aurelia-framework';
import {DialogController}     from 'aurelia-dialog';
import {ValidationController} from 'aurelia-validation';
import {ValidationRules}      from 'aurelia-validatejs';

@inject(DialogController, NewInstance.of(ValidationController))
export class ScaffoldProject {
  constructor(dialog, validator) {
    this.dialog = dialog;
    this.validator = validator;
  }

  attached() {
    ValidationRules
    .ensure('firstName').required()
    .ensure('lastName').required()
    .ensure('email').required().email()
    .on(this);
  }

  submit() {
    let errors = this.validator.validate();
    console.log(errors);
  }
}
<commit_msg>chore(setup): try out fs abstraction by loading file from aurelia-cli<commit_after>import {inject, NewInstance}  from 'aurelia-framework';
import {DialogController}     from 'aurelia-dialog';
import {ValidationController} from 'aurelia-validation';
import {ValidationRules}      from 'aurelia-validatejs';
import {Fs}                   from '../shared/abstractions/fs';

@inject(DialogController, NewInstance.of(ValidationController), Fs)
export class ScaffoldProject {
  constructor(dialog, validator, fs) {
    this.dialog = dialog;
    this.validator = validator;
    this.fs = fs;
  }

  async activate() {
    this.questions = JSON.parse(await this.fs.readFile('node_modules/aurelia-cli/lib/commands/new/new-application.json'));

    alert(`Loaded ${this.questions.activities.length} questions from aurelia-cli`);
  }

  async attached() {
    ValidationRules
    .ensure('firstName').required()
    .ensure('lastName').required()
    .ensure('email').required().email()
    .on(this);
  }

  submit() {
    let errors = this.validator.validate();
    console.log(errors);
  }
}
<|endoftext|>


<commit_before>const Events = require('./Events');

const updates = {}

/**
 * Store change to export.
 *
 * payload: component, entity, value.
 */
Events.on('entityupdate', payload => {
  let value = payload.value;

  const entity = payload.entity;
  updates[entity.id] = updates[entity.id] || {};

  const component = AFRAME.components[payload.componentName];
  if (component) {
    if (payload.propertyName) {
      value = component.schema[propertyName].stringify(payload.value);
    } else {
      value = component.schema.stringify(payload.value);
    }
  }

  updates[entity.id][payload.component] = value;
});

module.exports = {
  updates: updates
};
<commit_msg>modify watcher payload<commit_after>const Events = require('./Events');

const updates = {}

/**
 * Store change to export.
 *
 * payload: component, entity, value.
 */
Events.on('entityupdate', payload => {
  let value = payload.value;

  const entity = payload.entity;
  updates[entity.id] = updates[entity.id] || {};

  const component = AFRAME.components[payload.componentName];
  if (component) {
    if (payload.propertyName) {
      const componentUpdate = updates[entity.id][payload.componentName] || {};
      value = component.schema[propertyName].stringify(payload.value);
      componentUpdate[payload.propertyName] = componentUpdate;
    } else {
      value = component.schema.stringify(payload.value);
      updates[entity.id][payload.component] = value;
    }
  }
});

module.exports = {
  updates: updates
};
<|endoftext|>