<commit_before>var
    esPhinx;

(function($) {
    "use strict";

    var
        nodes = [],
        mappedListeners = {},

        mapped = function(node) {
            var
                index = nodes.indexOfEquivalence(node);

            return mappedListeners[index];
        },

        mapEventListener = function(node, eventName, runOnListener) {
            var
                index,
                mappedNode = mapped(node),
                map = {};

            if (runOnListener) {
                map[eventName] = [runOnListener];
                if (mappedNode) {
                    if (mappedNode[eventName]) {
                        mappedNode[eventName].push(runOnListener);
                    } else {
                        mappedNode[eventName] = map[eventName];
                    }
                    return mappedNode[eventName];
                } else {
                    nodes.push(node);
                    index = nodes.length - 1;
                    mappedListeners[index] = map;
                    return mappedListeners[index][eventName];
                }
            } else {
                if (mappedNode) {
                    return mappedNode[eventName];
                } else {
                    return [];
                }
            }
        },

        removeListener = function(node, eventName, runOnListener) {
            var
                mappedNode = mapped(node),
                callbacks = mappedNode[eventName];

            callbacks.delete(runOnListener);
        },

        removeListeners = function(node, eventName) {
            var
                mappedNode = mapped(node);

            delete mappedNode[eventName];
        },

        mapEach = function(eventName, runOnListener, callback) {
            var
                iteratorBlock = function(node) {
                    if (node instanceof window.Node || node == window) {
                        mapEventListener(node, eventName, runOnListener);
                        callback.call(node);
                    }
                };

            this.each(iteratorBlock);
        },

        // qual seria o evento neste caso, para, por exemplo, usar o stopPropagation?
        onChangeNode = function(runOnListener) {
            var
                added,
                self = this,

                callback = function(mutation) {
                    added = $(mutation.addedNodes).elements();
                    if (added.some()) {
                        runOnListener.call(self, added.asArray());
                    }
                },

                observeCallback = function(mutations) {
                    mutations.forEach(callback);

                };

            mapEach.call(self, "changeNode", runOnListener,
                         function() {
                            $(this).observe(observeCallback);
                        }
            );

        },

        // will see how to unbind the node event
        // offChangeNode = function(runOnListener) {
        //     // disconnect
        // },

        on = function(eventName, capture, runOnListener) {
            var
                cloned,
                runOnLoad,
                imgs,
                self = this,
                html = $("html"),
                clone = self.clone(true),

                callback = function(node) {
                    cloned = $(node);
                    cloned.hide();
                    html.prepend(node);

                    node.addEventListener(eventName, runOnLoad, capture);
                },

                removeListeningIteratorBlock = function(node) {
                    node.removeEventListener(eventName, runOnLoad, capture);
                };

            if (typeof capture == "function") {
                runOnListener = capture;
                capture = false;
            } else if (typeof capture != "boolean") {
                capture = false;
            }

            switch (eventName) {
                case "changeNode":
                    return onChangeNode.call(self, runOnListener);
                case "load":
                    imgs = clone.find("img");
                    if (imgs.some()) {
                        clone = imgs;
                    }

                    runOnLoad = function(e) {
                        runOnListener.call(this, e);
                        html.remove(clone);

                        clone.each(removeListeningIteratorBlock);
                    };

                    clone.each(callback);
                break;

                default:
                    mapEach.call(self, eventName, runOnListener,
                                 function() {
                        this.addEventListener(eventName, runOnListener,
                                              capture);
                    });
            }
        };

    $.prototype.extend(true, {

        on: function(eventName, capture, runOnListener) {
            on.call(this, eventName, capture, runOnListener);

            return this;
        },

        off: function(eventName, capture, runOnListener) {
            var
                callback,
                node,

                removeAllIteratorBlock = function(runOnListener) {
                    var
                        booleanIteratorBlock = function(capture) {
                            node.removeEventListener(eventName, runOnListener,
                                                     capture);
                        };

                    [true, false].forEach(booleanIteratorBlock);
                    removeListeners(node, eventName);
                };

            if (typeof capture == "function") {
                runOnListener = capture;
                capture = false;
            } else if (typeof capture != "boolean") {
                capture = false;
            }

            if (runOnListener) {
                callback = function(n) {
                    node = n;
                    node.removeEventListener(eventName, runOnListener, capture);
                    removeListener(node, eventName, runOnListener);
                };
            } else {
                callback = function(n) {
                    node = n;
                    if (mapped(node)) {
                        mapEventListener(node, eventName)
                            .forEach(removeAllIteratorBlock);
                    }
                };
            }

            this.each(callback);

            return this;
        },

        attachedEvent: function(eventName) {
            if (mapped(this.asNode())[eventName]) {
                return true;
            }

            return false;
        }

    });

})(esPhinx);
<commit_msg>refactor<commit_after>var
    esPhinx;

(function($) {
    "use strict";

    var
        nodes = [],
        mappedListeners = {},

        mapped = function(node) {
            var
                index = nodes.indexOfEquivalence(node);

            return mappedListeners[index];
        },

        mapEventListener = function(node, eventName, runOnListener) {
            var
                index,
                mappedNode = mapped(node),
                map = {};

            if (runOnListener) {
                map[eventName] = [runOnListener];
                if (mappedNode) {
                    if (mappedNode[eventName]) {
                        mappedNode[eventName].push(runOnListener);
                    } else {
                        mappedNode[eventName] = map[eventName];
                    }
                    return mappedNode[eventName];
                } else {
                    nodes.push(node);
                    index = nodes.length - 1;
                    mappedListeners[index] = map;
                    return mappedListeners[index][eventName];
                }
            } else {
                if (mappedNode) {
                    return mappedNode[eventName];
                } else {
                    return [];
                }
            }
        },

        removeListener = function(node, eventName, runOnListener) {
            var
                mappedNode = mapped(node),
                callbacks = mappedNode[eventName];

            callbacks.delete(runOnListener);
        },

        removeListeners = function(node, eventName) {
            var
                mappedNode = mapped(node);

            delete mappedNode[eventName];
        },

        mapEach = function(eventName, runOnListener, callback) {
            var
                iteratorBlock = function(node) {
                    if (node instanceof window.Node || node == window) {
                        mapEventListener(node, eventName, runOnListener);
                        callback.call(node);
                    }
                };

            this.each(iteratorBlock);
        },

        // qual seria o evento neste caso, para, por exemplo, usar o stopPropagation?
        onChangeNode = function(runOnListener) {
            var
                added,
                self = this,

                callback = function(mutation) {
                    added = $(mutation.addedNodes).elements();
                    if (added.some()) {
                        runOnListener.call(self, added.asArray());
                    }
                },

                observeCallback = function(mutations) {
                    mutations.forEach(callback);

                };

            mapEach.call(self, "changeNode", runOnListener,
                         function() {
                            $(this).observe(observeCallback);
                        }
            );

        },

        // will see how to unbind the node event
        // offChangeNode = function(runOnListener) {
        //     // disconnect
        // },

        on = function(eventName, capture, runOnListener) {
            var
                cloned,
                runOnLoad,
                imgs,
                self = this,
                html = $("html"),
                clone = self.clone(true),

                callback = function(node) {
                    cloned = $(node);
                    cloned.hide();
                    html.prepend(node);

                    node.addEventListener(eventName, runOnLoad, capture);
                },

                iteratorBlock = function(node) {
                    node.removeEventListener(eventName, runOnLoad, capture);
                };

            if (typeof capture == "function") {
                runOnListener = capture;
                capture = false;
            } else if (typeof capture != "boolean") {
                capture = false;
            }

            switch (eventName) {
                case "changeNode":
                    return onChangeNode.call(self, runOnListener);
                case "load":
                    imgs = clone.find("img");
                    if (imgs.some()) {
                        clone = imgs;
                    }

                    runOnLoad = function(e) {
                        runOnListener.call(this, e);
                        html.remove(clone);

                        clone.each(iteratorBlock);
                    };

                    clone.each(callback);
                break;

                default:
                    mapEach.call(self, eventName, runOnListener,
                                 function() {
                        this.addEventListener(eventName, runOnListener,
                                              capture);
                    });
            }
        };

    $.prototype.extend(true, {

        on: function(eventName, capture, runOnListener) {
            on.call(this, eventName, capture, runOnListener);

            return this;
        },

        off: function(eventName, capture, runOnListener) {
            var
                callback,
                node,

                iteratorBlock = function(runOnListener) {
                    var
                        booleanIteratorBlock = function(capture) {
                            node.removeEventListener(eventName, runOnListener,
                                                     capture);
                        };

                    [true, false].forEach(booleanIteratorBlock);
                    removeListeners(node, eventName);
                };

            if (typeof capture == "function") {
                runOnListener = capture;
                capture = false;
            } else if (typeof capture != "boolean") {
                capture = false;
            }

            if (runOnListener) {
                callback = function(n) {
                    node = n;
                    node.removeEventListener(eventName, runOnListener, capture);
                    removeListener(node, eventName, runOnListener);
                };
            } else {
                callback = function(n) {
                    node = n;
                    if (mapped(node)) {
                        mapEventListener(node, eventName)
                            .forEach(iteratorBlock);
                    }
                };
            }

            this.each(callback);

            return this;
        },

        attachedEvent: function(eventName) {
            if (mapped(this.asNode())[eventName]) {
                return true;
            }

            return false;
        }

    });

})(esPhinx);
<|endoftext|>


<commit_before>/* eslint no-console:0 */
import 'rc-input-number/assets/index.less';
import InputNumber from 'rc-input-number';
import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {
  render() {
    return (

        <InputNumber
          defaultValue={1000}
          formatter={value => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
        />

    );
  }
}

ReactDOM.render(<App />, document.getElementById('__react-content'));
<commit_msg>update examples<commit_after>/* eslint no-console:0 */
import 'rc-input-number/assets/index.less';
import InputNumber from 'rc-input-number';
import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {
  render() {
    return (

        <InputNumber
          defaultValue={1000}
          formatter={value => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
        />
        <InputNumber
          defaultValue={100}
          formatter={value => `${value}%`}
          parser={value => value.replace('%', '')}
        />

    );
  }
}

ReactDOM.render(<App />, document.getElementById('__react-content'));
<|endoftext|>


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

	module.exports = function ($scope, $timeout, $uibModal, $, lncli, config) {

		var $ctrl = this;

		$scope.queryRoute = function () {

			var modalInstance = $uibModal.open({
				animation: true,
				ariaLabelledBy: "queryroute-modal-title",
				ariaDescribedBy: "queryroute-modal-body",
				templateUrl: "templates/partials/lnd/queryroute.html",
				controller: "ModalQueryRouteCtrl",
				controllerAs: "$ctrl",
				size: "lg",
				resolve: {
					defaults: {
						amount: 0
					}
				}
			});

			modalInstance.rendered.then(function () {
				$("#queryroute-pubkey").focus();
			});

			modalInstance.result.then(function (values) {
				console.log("values", values);
			}, function () {
				console.log("Modal dismissed at: " + new Date());
			});

		};

		$scope.newAddress = function () {

			var modalInstance = $uibModal.open(config.modals.NEW_ADDRESS);

			modalInstance.rendered.then(function () {
				$("#newaddress-type").focus();
			});

			modalInstance.result.then(function (values) {
				console.log("values", values);
			}, function () {
				console.log("Modal dismissed at: " + new Date());
			});

		};

		$scope.renderGraph = function () {

			lncli.renderGraph().then(function (response) {
				window.open("/api/lnd/networkgraph.svg", "_blank");
			}, function (err) {
				console.log(err);
			});

		};

		$scope.signMessage = function () {

			var modalInstance = $uibModal.open(config.modals.SIGN_MESSAGE);

			modalInstance.rendered.then(function () {
				$("#signmessage-message").focus();
			});

			modalInstance.result.then(function (values) {
				console.log("values", values);
			}, function () {
				console.log("Modal dismissed at: " + new Date());
			});

		};

		$scope.verifyMessage = function () {

			var modalInstance = $uibModal.open(config.modals.VERIFY_MESSAGE);

			modalInstance.rendered.then(function () {
				$("#verifymessage-message").focus();
			});

			modalInstance.result.then(function (values) {
				console.log("values", values);
			}, function () {
				console.log("Modal dismissed at: " + new Date());
			});

		};

		$scope.editSettings = function () {

			var modalInstance = $uibModal.open({
				animation: true,
				ariaLabelledBy: "editsettings-modal-title",
				ariaDescribedBy: "editsettings-modal-body",
				templateUrl: "templates/partials/lnd/editsettings.html",
				controller: "ModalEditSettingsCtrl",
				controllerAs: "$ctrl",
				size: "lg",
				resolve: {
					settings: function () {
						return lncli.getConfigValues();
					}
				}
			});

			modalInstance.rendered.then(function () {
				$("#editsettings-autorefresh").focus();
			});

			modalInstance.result.then(function (values) {
				console.log("values", values);
			}, function () {
				console.log("Modal dismissed at: " + new Date());
			});

		};

	};

})();
<commit_msg>RenderGraph URL fix<commit_after>(function () {
	"use strict";

	module.exports = function ($scope, $timeout, $uibModal, $, lncli, config) {

		var $ctrl = this;

		$scope.queryRoute = function () {

			var modalInstance = $uibModal.open({
				animation: true,
				ariaLabelledBy: "queryroute-modal-title",
				ariaDescribedBy: "queryroute-modal-body",
				templateUrl: "templates/partials/lnd/queryroute.html",
				controller: "ModalQueryRouteCtrl",
				controllerAs: "$ctrl",
				size: "lg",
				resolve: {
					defaults: {
						amount: 0
					}
				}
			});

			modalInstance.rendered.then(function () {
				$("#queryroute-pubkey").focus();
			});

			modalInstance.result.then(function (values) {
				console.log("values", values);
			}, function () {
				console.log("Modal dismissed at: " + new Date());
			});

		};

		$scope.newAddress = function () {

			var modalInstance = $uibModal.open(config.modals.NEW_ADDRESS);

			modalInstance.rendered.then(function () {
				$("#newaddress-type").focus();
			});

			modalInstance.result.then(function (values) {
				console.log("values", values);
			}, function () {
				console.log("Modal dismissed at: " + new Date());
			});

		};

		$scope.renderGraph = function () {

			lncli.renderGraph().then(function (response) {
				window.open(lncli.getEndPoint() + "/api/lnd/networkgraph.svg", "_blank");
			}, function (err) {
				console.log(err);
			});

		};

		$scope.signMessage = function () {

			var modalInstance = $uibModal.open(config.modals.SIGN_MESSAGE);

			modalInstance.rendered.then(function () {
				$("#signmessage-message").focus();
			});

			modalInstance.result.then(function (values) {
				console.log("values", values);
			}, function () {
				console.log("Modal dismissed at: " + new Date());
			});

		};

		$scope.verifyMessage = function () {

			var modalInstance = $uibModal.open(config.modals.VERIFY_MESSAGE);

			modalInstance.rendered.then(function () {
				$("#verifymessage-message").focus();
			});

			modalInstance.result.then(function (values) {
				console.log("values", values);
			}, function () {
				console.log("Modal dismissed at: " + new Date());
			});

		};

		$scope.editSettings = function () {

			var modalInstance = $uibModal.open({
				animation: true,
				ariaLabelledBy: "editsettings-modal-title",
				ariaDescribedBy: "editsettings-modal-body",
				templateUrl: "templates/partials/lnd/editsettings.html",
				controller: "ModalEditSettingsCtrl",
				controllerAs: "$ctrl",
				size: "lg",
				resolve: {
					settings: function () {
						return lncli.getConfigValues();
					}
				}
			});

			modalInstance.rendered.then(function () {
				$("#editsettings-autorefresh").focus();
			});

			modalInstance.result.then(function (values) {
				console.log("values", values);
			}, function () {
				console.log("Modal dismissed at: " + new Date());
			});

		};

	};

})();
<|endoftext|>


<commit_before>const gulp = require('gulp');
const gutil = require('gulp-util');
const babel = require('gulp-babel');
const webpack = require('webpack');

require('babel-polyfill');

const WEBPACK_CONFIG = {
  entry: [
    'babel-polyfill',
    './target/bondage.js',
  ],
  output: {
    path: './dist',
    filename: '[name].bundle.js',
    libraryTarget: 'var',
    library: 'bondage',
  },
  plugins: [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin(),
  ],
};

gulp.task('default', ['webpack']);

gulp.task('babel', () => {
  return gulp.src('src/**.js')
    .pipe(babel())
    .pipe(gulp.dest('target'));
});

gulp.task('webpack', ['babel'], (callback) => {
  webpack(WEBPACK_CONFIG, (err, stats) => {
    if (err) throw new gutil.PluginError('webpack', err);

    gutil.log('[webpack]', stats.toString({
      colors: true,
      progress: true,
    }));
    callback();
  });
});
<commit_msg>.bundle -> .min<commit_after>const gulp = require('gulp');
const gutil = require('gulp-util');
const babel = require('gulp-babel');
const webpack = require('webpack');

require('babel-polyfill');

const WEBPACK_CONFIG = {
  entry: [
    'babel-polyfill',
    './target/bondage.js',
  ],
  output: {
    path: './dist',
    filename: '[name].min.js',
    libraryTarget: 'var',
    library: 'bondage',
  },
  plugins: [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin(),
  ],
};

gulp.task('default', ['webpack']);

gulp.task('babel', () => {
  return gulp.src('src/**.js')
    .pipe(babel())
    .pipe(gulp.dest('target'));
});

gulp.task('webpack', ['babel'], (callback) => {
  webpack(WEBPACK_CONFIG, (err, stats) => {
    if (err) throw new gutil.PluginError('webpack', err);

    gutil.log('[webpack]', stats.toString({
      colors: true,
      progress: true,
    }));
    callback();
  });
});
<|endoftext|>


<commit_before>const EventEmitter = require('events')
const fs = require('fs')

const config = require('../printer/config')
const format = require('string-format')
const spawn = require('spawn-promise')

let SerialPort
let serialDevice = '/dev/ttyACM0'

try {
  fs.accessSync(serialDevice, fs.F_OK)
  SerialPort = require('serialport')
} catch (e) {
  console.log('warning using virtual serialport')
  SerialPort = require('virtual-serialport')
  SerialPort.parsers = {
    readline: (foo) => 42
  }
}

let arduino = new SerialPort(serialDevice, {
  baudrate: 9600,
  parser: SerialPort.parsers.readline('\n')
})

function waitForCompletion (port) { // add a timeout?
  return new Promise((resolve, reject) => {
    port.write('G4 P1\n')
    console.log('G4 send')
    port.on('data', (data) => {
      if (data.toString().includes('Z_move_comp')) {
        resolve(data.toString())
      } else {
        console.log(data.toString())
      }
    })

    port.on('error', (err) => {
      reject(err)
    })
  })
}

function send (port, gcode) {
  return new Promise((resolve, reject) => {
    port.write(gcode + '\n')
    console.log('send: ' + gcode)

    let received = (data) => {
      // console.log('received: ' + data)
      if (data.toString().includes(gcode)) {
        console.log('resolve ' + gcode)
        port.removeListener('data', received)
        resolve(data.toString())
      }
    }
    port.on('data', received)

    port.once('error', (err) => {
      reject(err)
    })
  })
}

function sendAll (port, gcodes) {
  return gcodes.reduce((p, gcode) => p.then(() => send(port, gcode)), Promise.resolve())
}

function sendLayers (num) {
  let p = Promise.resolve()
  let layerheight = 2

  let root = `${__dirname}/../models`
  let fb_device = '/dev/fb0'

  for (var i = 0; i < num; i++) {
    let before = config.gcode.layer.before.map((gcode) => format(gcode, {position: i * layerheight}))
    let open = config.gcode.shutter.open.map((gcode) => format(gcode, {position: i * layerheight}))
    let close = config.gcode.shutter.close.map((gcode) => format(gcode, {position: i * layerheight}))
    let after = config.gcode.layer.after.map((gcode) => format(gcode, {position: i * layerheight}))

    let export_layer = `--export-id=layer${i}`

    p = p.then(() => sendAll(arduino, before))
    .then(() => spawn('inkscape', ['--without-gui', `--export-png=${root}/render.png`, export_layer, '--export-id-only', '--export-area-page', '--export-dpi=1000', '--export-background=black', `${root}/gear_small.svg`]))
    .then(() => spawn('avconv', ['-loglevel', 'panic', '-y', '-vcodec', 'png', '-i', `${root}/render.png`, '-vcodec', 'rawvideo', '-f', 'rawvideo', '-pix_fmt', 'rgb32', '-vf', 'pad=1024:768:120:40:blue', fb_device]))
    .then(() => sendAll(arduino, open))
    .then(() => new Promise((resolve) => setTimeout(resolve, 5000)))
    .then(() => sendAll(arduino, close))
    .then(() => sendAll(arduino, after))
    // this.emit('progress', i / num)
  }
  return p
}

class Controller extends EventEmitter {
  startJob (job, sync = false) {
    if (!sync) {
      console.log('hey ho let\'s go')
      setTimeout(job => this.startJob(job, sync = true))
      return
    }
    console.log('preparing to print')
    // arduino.on('open', function () {
    console.log('### opened')
    arduino.write(config.gcode.start)
    this.emit('start')

    console.log('### sending stuff')

    sendAll(arduino, config.gcode.start)
    .then(() => sendLayers(10))
    .then(() => sendAll(arduino, ['G4 P100']))
    .then(() => sendAll(arduino, config.gcode.end))
    .then(function () { console.log('TADAAAA') })

    this.emit('end')
    arduino.write(config.gcode.end)
    waitForCompletion(arduino)
    this.emit('done')
    // })
  }
}

module.exports.Controller = Controller
<commit_msg>Fix event emitting<commit_after>const EventEmitter = require('events')
const fs = require('fs')

const config = require('../printer/config')
const format = require('string-format')
const spawn = require('spawn-promise')

let SerialPort
let serialDevice = '/dev/ttyACM0'

try {
  fs.accessSync(serialDevice, fs.F_OK)
  SerialPort = require('serialport')
} catch (e) {
  console.log('warning using virtual serialport')
  SerialPort = require('virtual-serialport')
  SerialPort.parsers = {
    readline: (foo) => 42
  }
}

let arduino = new SerialPort(serialDevice, {
  baudrate: 9600,
  parser: SerialPort.parsers.readline('\n')
})

function send (port, gcode) {
  return new Promise((resolve, reject) => {
    port.write(gcode + '\n')

    let received = (data) => {
      // console.log('received: ' + data)
      if (data.toString().includes(gcode)) {
        console.log('resolve ' + gcode)
        port.removeListener('data', received)
        resolve(data.toString())
      }
    }
    port.on('data', received)

    port.once('error', (err) => {
      reject(err)
    })
  })
}

function sendAll (port, gcodes) {
  return gcodes.reduce((p, gcode) => p.then(() => send(port, gcode)), Promise.resolve())
}

class Controller extends EventEmitter {
  startJob (job, sync = false) {
    if (!sync) {
      setTimeout(job => this.startJob(job, sync = true))
      return
    }

    this.emit('start')
    sendAll(arduino, config.gcode.start)
    .then(() => this.sendLayers(10))
    .then(() => sendAll(arduino, ['G4 P100']))
    .then(() => this.emit('end'))
    .then(() => sendAll(arduino, config.gcode.end))
    .then(() => this.emit('done'))
  }

  sendLayers (num) {
    let p = Promise.resolve()
    let layerheight = 2

    let root = `${__dirname}/../models`
    let fb_device = '/dev/fb0'

    for (var i = 0; i < num; i++) {
      let before = config.gcode.layer.before.map((gcode) => format(gcode, {position: i * layerheight}))
      let open = config.gcode.shutter.open.map((gcode) => format(gcode, {position: i * layerheight}))
      let close = config.gcode.shutter.close.map((gcode) => format(gcode, {position: i * layerheight}))
      let after = config.gcode.layer.after.map((gcode) => format(gcode, {position: i * layerheight}))

      let export_layer = `--export-id=layer${i}`

      p = p.then(() => sendAll(arduino, before))
      .then(() => spawn('inkscape', ['--without-gui', `--export-png=${root}/render.png`, export_layer, '--export-id-only', '--export-area-page', '--export-dpi=1000', '--export-background=black', `${root}/gear_small.svg`]))
      .then(() => spawn('avconv', ['-loglevel', 'panic', '-y', '-vcodec', 'png', '-i', `${root}/render.png`, '-vcodec', 'rawvideo', '-f', 'rawvideo', '-pix_fmt', 'rgb32', '-vf', 'pad=1024:768:120:40:blue', fb_device]))
      .then(() => sendAll(arduino, open))
      .then(() => new Promise((resolve) => setTimeout(resolve, 5000)))
      .then(() => sendAll(arduino, close))
      .then(() => sendAll(arduino, after))
      .then(() => this.emit('progress', i / num))
    }
    return p
  }
}

module.exports.Controller = Controller
<|endoftext|>


<commit_before>const SamlStrategy = require('passport-saml').Strategy
  , log = require('winston')
  , User = require('../models/user')
  , Role = require('../models/role')
  , Device = require('../models/device')
  , TokenAssertion = require('./verification').TokenAssertion
  , api = require('../api')
  , userTransformer = require('../transformers/user')
  , AuthenticationInitializer = require('./index')
  , authenticationApiAppender = require('../utilities/authenticationApiAppender');

function configure(strategy) {
  log.info('Configuring ' + strategy.title + ' authentication');

  const options = {
    path: `/auth/${strategy.name}/callback`,
    entryPoint: strategy.settings.options.entryPoint,
    issuer: strategy.settings.options.issuer
  }

  if (strategy.settings.cert) {
    options.cert = strategy.settings.cert;
  }
  if (strategy.settings.privateCert) {
    options.privateCert = strategy.settings.privateCert;
  }
  if (strategy.settings.decryptionPvk) {
    options.decryptionPvk = strategy.settings.decryptionPvk;
  }
  if (strategy.settings.signatureAlgorithm) {
    options.signatureAlgorithm = strategy.settings.signatureAlgorithm;
  }
  if(strategy.settings.audience) {
    options.audience = strategy.settings.audience;
  }
  if(strategy.settings.identifierFormat) {
    options.identifierFormat = strategy.settings.identifierFormat;
  }
  if(strategy.settings.acceptedClockSkewMs) {
    options.acceptedClockSkewMs = strategy.settings.acceptedClockSkewMs;
  }
  if(strategy.settings.attributeConsumingServiceIndex) {
    options.attributeConsumingServiceIndex = strategy.settings.attributeConsumingServiceIndex;
  }
  if(strategy.settings.disableRequestedAuthnContext) {
    options.disableRequestedAuthnContext = strategy.settings.disableRequestedAuthnContext;
  }
  if(strategy.settings.authnContext) {
    options.authnContext = strategy.settings.authnContext;
  }
  if(strategy.settings.forceAuthn) {
    options.forceAuthn = strategy.settings.forceAuthn;
  }
  if(strategy.settings.skipRequestCompression) {
    options.skipRequestCompression = strategy.settings.skipRequestCompression;
  }
  if(strategy.settings.authnRequestBinding) {
    options.authnRequestBinding = strategy.settings.authnRequestBinding;
  }
  if(strategy.settings.RACComparison) {
    options.RACComparison = strategy.settings.RACComparison;
  }
  if(strategy.settings.providerName) {
    options.providerName = strategy.settings.providerName;
  }
  if(strategy.settings.idpIssuer) {
    options.idpIssuer = strategy.settings.idpIssuer;
  }
  if(strategy.settings.validateInResponseTo) {
    options.validateInResponseTo = strategy.settings.validateInResponseTo;
  }
  if(strategy.settings.requestIdExpirationPeriodMs) {
    options.requestIdExpirationPeriodMs = strategy.settings.requestIdExpirationPeriodMs;
  }
  if(strategy.settings.logoutUrl) {
    options.logoutUrl = strategy.settings.logoutUrl;
  }

  AuthenticationInitializer.passport.use(new SamlStrategy(options, function (profile, done) {
    const uid = profile[strategy.settings.profile.id];

    if (!uid) {
      log.warn('Failed to find property uid. SAML profile keys ' + Object.keys(profile));
      return done('Failed to load user id from SAML profile');
    }

    User.getUserByAuthenticationStrategy(strategy.type, uid, function (err, user) {
      if (err) return done(err);

      if (!user) {
        // Create an account for the user
        Role.getRole('USER_ROLE', function (err, role) {
          if (err) return done(err);

          const user = {
            username: uid,
            displayName: profile[strategy.settings.profile.displayName],
            email: profile[strategy.settings.profile.email],
            active: false,
            roleId: role._id,
            authentication: {
              type: strategy.name,
              id: uid,
              authenticationConfiguration: {
                name: strategy.name
              }
            }
          };

          new api.User().create(user).then(newUser => {
            if (!newUser.authentication.authenticationConfiguration.enabled) {
              log.warn(newUser.authentication.authenticationConfiguration.title + " authentication is not enabled");
              return done(null, false, { message: 'Authentication method is not enabled, please contact a MAGE administrator for assistance.' });
            }
            return done(null, newUser);
          }).catch(err => done(err));
        });
      } else if (!user.active) {
        return done(null, user, { message: "User is not approved, please contact your MAGE administrator to approve your account." });
      } else if (!user.authentication.authenticationConfiguration.enabled) {
        log.warn(user.authentication.authenticationConfiguration.title + " authentication is not enabled");
        return done(null, user, { message: 'Authentication method is not enabled, please contact a MAGE administrator for assistance.' });
      } else {
        return done(null, user);
      }
    });
  }));

  function authenticate(req, res, next) {
    AuthenticationInitializer.passport.authenticate(strategy.name, function (err, user, info = {}) {
      if (err) return next(err);

      req.user = user;

      // For inactive or disabled accounts don't generate an authorization token
      if (!user.active || !user.enabled) {
        log.warn('Failed user login attempt: User ' + user.username + ' account is inactive or disabled.');
        return next();
      }

      if (!user.authentication.authenticationConfigurationId) {
        log.warn('Failed user login attempt: ' + user.authentication.type + ' is not configured');
        return next();
      }

      if (!user.authentication.authenticationConfiguration.enabled) {
        log.warn('Failed user login attempt: Authentication ' + user.authentication.authenticationConfiguration.title + ' is disabled.');
        return next();
      }

      // DEPRECATED session authorization, remove req.login which creates session in next version
      req.login(user, function (err) {
        AuthenticationInitializer.tokenService.generateToken(user._id.toString(), TokenAssertion.Authorized, 60 * 5)
          .then(token => {
            req.token = token;
            req.user = user;
            req.info = info
            next();
          }).catch(err => {
            next(err);
          });
      });
    })(req, res, next);
  }

  AuthenticationInitializer.app.post(
    `/auth/${strategy.name}/callback`,
    authenticate,
    function (req, res) {
      const state = JSON.parse(req.body.RelayState) || {};

      if (state.initiator === 'mage') {
        if (state.client === 'mobile') {
          let uri;
          if (!req.user.active || !req.user.enabled) {
            uri = `mage://app/invalid_account?active=${req.user.active}&enabled=${req.user.enabled}`;
          } else {
            uri = `mage://app/authentication?token=${req.token}`
          }

          res.redirect(uri);
        } else {
          res.render('authentication', { host: req.getRoot(), login: { token: req.token, user: req.user } });
        }
      } else {
        if (req.user.active && req.user.enabled) {
          res.redirect(`/#/signin?strategy=${config.name}&action=authorize-device&token=${req.token}`);
        } else {
          const action = !req.user.active ? 'inactive-account' : 'disabled-account';
          res.redirect(`/#/signin?strategy=${config.name}&action=${action}`);
        }
      }
    }
  );
}

function setDefaults(strategy) {
  if (!strategy.settings.profile) {
    strategy.settings.profile = {};
  }
  if (!strategy.settings.profile.displayName) {
    strategy.settings.profile.displayName = 'email';
  }
  if (!strategy.settings.profile.email) {
    strategy.settings.profile.email = 'email';
  }
  if (!strategy.settings.profile.id) {
    strategy.settings.profile.id = 'uid';
  }
  if (!strategy.settings.options) {
    strategy.settings.options = {};
  }
}

function initialize(strategy) {
  const app = AuthenticationInitializer.app;
  const passport = AuthenticationInitializer.passport;
  const provision = AuthenticationInitializer.provision;

  setDefaults(strategy);
  configure(strategy);

  function parseLoginMetadata(req, res, next) {
    req.loginOptions = {
      userAgent: req.headers['user-agent'],
      appVersion: req.param('appVersion')
    };

    next();
  }
  app.get(
    '/auth/' + strategy.name + '/signin',
    function (req, res, next) {
      const state = {
        initiator: 'mage',
        client: req.query.state
      };

      passport.authenticate(strategy.name, {
        additionalParams: { RelayState: JSON.stringify(state) }
      })(req, res, next);
    }
  );

  // DEPRECATED retain old routes as deprecated until next major version.
  // Create a new device
  // Any authenticated user can create a new device, the registered field
  // will be set to false.
  app.post('/auth/' + strategy.name + '/devices',
    function (req, res, next) {
      if (req.user) {
        next();
      } else {
        res.sendStatus(401);
      }
    },
    function (req, res, next) {
      const newDevice = {
        uid: req.param('uid'),
        name: req.param('name'),
        registered: false,
        description: req.param('description'),
        userAgent: req.headers['user-agent'],
        appVersion: req.param('appVersion'),
        userId: req.user.id
      };

      Device.getDeviceByUid(newDevice.uid)
        .then(device => {
          if (device) {
            // already exists, do not register
            return res.json(device);
          }

          Device.createDevice(newDevice)
            .then(device => res.json(device))
            .catch(err => next(err));
        })
        .catch(err => next(err));
    }
  );

  // DEPRECATED session authorization, remove in next version.
  app.post(
    '/auth/' + strategy.name + '/authorize',
    function (req, res, next) {
      if (req.user) {
        log.warn('session authorization is deprecated, please use jwt');
        return next();
      }

      passport.authenticate('authorization', function (err, user, info = {}) {
        if (!user) return res.status(401).send(info.message);

        req.user = user;
        next();
      })(req, res, next);
    },
    provision.check(strategy.name),
    parseLoginMetadata,
    function (req, res, next) {
      new api.User().login(req.user, req.provisionedDevice, req.loginOptions, function (err, token) {
        if (err) return next(err);

        authenticationApiAppender.append(strategy.api).then(api => {
          res.json({
            token: token.token,
            expirationDate: token.expirationDate,
            user: userTransformer.transform(req.user, { path: req.getRoot() }),
            device: req.provisionedDevice,
            api: api
          });
        }).catch(err => {
          next(err);
        });
      });

      req.session = null;
    }
  );

};

module.exports = {
  initialize
}<commit_msg>Catch JSON parse exception if RelayState is not set<commit_after>const SamlStrategy = require('passport-saml').Strategy
  , log = require('winston')
  , User = require('../models/user')
  , Role = require('../models/role')
  , Device = require('../models/device')
  , TokenAssertion = require('./verification').TokenAssertion
  , api = require('../api')
  , userTransformer = require('../transformers/user')
  , AuthenticationInitializer = require('./index')
  , authenticationApiAppender = require('../utilities/authenticationApiAppender');

function configure(strategy) {
  log.info('Configuring ' + strategy.title + ' authentication');

  const options = {
    path: `/auth/${strategy.name}/callback`,
    entryPoint: strategy.settings.options.entryPoint,
    issuer: strategy.settings.options.issuer
  }

  if (strategy.settings.cert) {
    options.cert = strategy.settings.cert;
  }
  if (strategy.settings.privateCert) {
    options.privateCert = strategy.settings.privateCert;
  }
  if (strategy.settings.decryptionPvk) {
    options.decryptionPvk = strategy.settings.decryptionPvk;
  }
  if (strategy.settings.signatureAlgorithm) {
    options.signatureAlgorithm = strategy.settings.signatureAlgorithm;
  }
  if(strategy.settings.audience) {
    options.audience = strategy.settings.audience;
  }
  if(strategy.settings.identifierFormat) {
    options.identifierFormat = strategy.settings.identifierFormat;
  }
  if(strategy.settings.acceptedClockSkewMs) {
    options.acceptedClockSkewMs = strategy.settings.acceptedClockSkewMs;
  }
  if(strategy.settings.attributeConsumingServiceIndex) {
    options.attributeConsumingServiceIndex = strategy.settings.attributeConsumingServiceIndex;
  }
  if(strategy.settings.disableRequestedAuthnContext) {
    options.disableRequestedAuthnContext = strategy.settings.disableRequestedAuthnContext;
  }
  if(strategy.settings.authnContext) {
    options.authnContext = strategy.settings.authnContext;
  }
  if(strategy.settings.forceAuthn) {
    options.forceAuthn = strategy.settings.forceAuthn;
  }
  if(strategy.settings.skipRequestCompression) {
    options.skipRequestCompression = strategy.settings.skipRequestCompression;
  }
  if(strategy.settings.authnRequestBinding) {
    options.authnRequestBinding = strategy.settings.authnRequestBinding;
  }
  if(strategy.settings.RACComparison) {
    options.RACComparison = strategy.settings.RACComparison;
  }
  if(strategy.settings.providerName) {
    options.providerName = strategy.settings.providerName;
  }
  if(strategy.settings.idpIssuer) {
    options.idpIssuer = strategy.settings.idpIssuer;
  }
  if(strategy.settings.validateInResponseTo) {
    options.validateInResponseTo = strategy.settings.validateInResponseTo;
  }
  if(strategy.settings.requestIdExpirationPeriodMs) {
    options.requestIdExpirationPeriodMs = strategy.settings.requestIdExpirationPeriodMs;
  }
  if(strategy.settings.logoutUrl) {
    options.logoutUrl = strategy.settings.logoutUrl;
  }

  AuthenticationInitializer.passport.use(new SamlStrategy(options, function (profile, done) {
    const uid = profile[strategy.settings.profile.id];

    if (!uid) {
      log.warn('Failed to find property uid. SAML profile keys ' + Object.keys(profile));
      return done('Failed to load user id from SAML profile');
    }

    User.getUserByAuthenticationStrategy(strategy.type, uid, function (err, user) {
      if (err) return done(err);

      if (!user) {
        // Create an account for the user
        Role.getRole('USER_ROLE', function (err, role) {
          if (err) return done(err);

          const user = {
            username: uid,
            displayName: profile[strategy.settings.profile.displayName],
            email: profile[strategy.settings.profile.email],
            active: false,
            roleId: role._id,
            authentication: {
              type: strategy.name,
              id: uid,
              authenticationConfiguration: {
                name: strategy.name
              }
            }
          };

          new api.User().create(user).then(newUser => {
            if (!newUser.authentication.authenticationConfiguration.enabled) {
              log.warn(newUser.authentication.authenticationConfiguration.title + " authentication is not enabled");
              return done(null, false, { message: 'Authentication method is not enabled, please contact a MAGE administrator for assistance.' });
            }
            return done(null, newUser);
          }).catch(err => done(err));
        });
      } else if (!user.active) {
        return done(null, user, { message: "User is not approved, please contact your MAGE administrator to approve your account." });
      } else if (!user.authentication.authenticationConfiguration.enabled) {
        log.warn(user.authentication.authenticationConfiguration.title + " authentication is not enabled");
        return done(null, user, { message: 'Authentication method is not enabled, please contact a MAGE administrator for assistance.' });
      } else {
        return done(null, user);
      }
    });
  }));

  function authenticate(req, res, next) {
    AuthenticationInitializer.passport.authenticate(strategy.name, function (err, user, info = {}) {
      if (err) return next(err);

      req.user = user;

      // For inactive or disabled accounts don't generate an authorization token
      if (!user.active || !user.enabled) {
        log.warn('Failed user login attempt: User ' + user.username + ' account is inactive or disabled.');
        return next();
      }

      if (!user.authentication.authenticationConfigurationId) {
        log.warn('Failed user login attempt: ' + user.authentication.type + ' is not configured');
        return next();
      }

      if (!user.authentication.authenticationConfiguration.enabled) {
        log.warn('Failed user login attempt: Authentication ' + user.authentication.authenticationConfiguration.title + ' is disabled.');
        return next();
      }

      // DEPRECATED session authorization, remove req.login which creates session in next version
      req.login(user, function (err) {
        AuthenticationInitializer.tokenService.generateToken(user._id.toString(), TokenAssertion.Authorized, 60 * 5)
          .then(token => {
            req.token = token;
            req.user = user;
            req.info = info
            next();
          }).catch(err => {
            next(err);
          });
      });
    })(req, res, next);
  }

  AuthenticationInitializer.app.post(
    `/auth/${strategy.name}/callback`,
    authenticate,
    function (req, res) {
      let state = {};
      try {
        state = JSON.parse(req.body.RelayState)
      } catch(ignore) {}

      if (state.initiator === 'mage') {
        if (state.client === 'mobile') {
          let uri;
          if (!req.user.active || !req.user.enabled) {
            uri = `mage://app/invalid_account?active=${req.user.active}&enabled=${req.user.enabled}`;
          } else {
            uri = `mage://app/authentication?token=${req.token}`
          }

          res.redirect(uri);
        } else {
          res.render('authentication', { host: req.getRoot(), login: { token: req.token, user: req.user } });
        }
      } else {
        if (req.user.active && req.user.enabled) {
          res.redirect(`/#/signin?strategy=${strategy.name}&action=authorize-device&token=${req.token}`);
        } else {
          const action = !req.user.active ? 'inactive-account' : 'disabled-account';
          res.redirect(`/#/signin?strategy=${strategy.name}&action=${action}`);
        }
      }
    }
  );
}

function setDefaults(strategy) {
  if (!strategy.settings.profile) {
    strategy.settings.profile = {};
  }
  if (!strategy.settings.profile.displayName) {
    strategy.settings.profile.displayName = 'email';
  }
  if (!strategy.settings.profile.email) {
    strategy.settings.profile.email = 'email';
  }
  if (!strategy.settings.profile.id) {
    strategy.settings.profile.id = 'uid';
  }
  if (!strategy.settings.options) {
    strategy.settings.options = {};
  }
}

function initialize(strategy) {
  const app = AuthenticationInitializer.app;
  const passport = AuthenticationInitializer.passport;
  const provision = AuthenticationInitializer.provision;

  setDefaults(strategy);
  configure(strategy);

  function parseLoginMetadata(req, res, next) {
    req.loginOptions = {
      userAgent: req.headers['user-agent'],
      appVersion: req.param('appVersion')
    };

    next();
  }
  app.get(
    '/auth/' + strategy.name + '/signin',
    function (req, res, next) {
      const state = {
        initiator: 'mage',
        client: req.query.state
      };

      passport.authenticate(strategy.name, {
        additionalParams: { RelayState: JSON.stringify(state) }
      })(req, res, next);
    }
  );

  // DEPRECATED retain old routes as deprecated until next major version.
  // Create a new device
  // Any authenticated user can create a new device, the registered field
  // will be set to false.
  app.post('/auth/' + strategy.name + '/devices',
    function (req, res, next) {
      if (req.user) {
        next();
      } else {
        res.sendStatus(401);
      }
    },
    function (req, res, next) {
      const newDevice = {
        uid: req.param('uid'),
        name: req.param('name'),
        registered: false,
        description: req.param('description'),
        userAgent: req.headers['user-agent'],
        appVersion: req.param('appVersion'),
        userId: req.user.id
      };

      Device.getDeviceByUid(newDevice.uid)
        .then(device => {
          if (device) {
            // already exists, do not register
            return res.json(device);
          }

          Device.createDevice(newDevice)
            .then(device => res.json(device))
            .catch(err => next(err));
        })
        .catch(err => next(err));
    }
  );

  // DEPRECATED session authorization, remove in next version.
  app.post(
    '/auth/' + strategy.name + '/authorize',
    function (req, res, next) {
      if (req.user) {
        log.warn('session authorization is deprecated, please use jwt');
        return next();
      }

      passport.authenticate('authorization', function (err, user, info = {}) {
        if (!user) return res.status(401).send(info.message);

        req.user = user;
        next();
      })(req, res, next);
    },
    provision.check(strategy.name),
    parseLoginMetadata,
    function (req, res, next) {
      new api.User().login(req.user, req.provisionedDevice, req.loginOptions, function (err, token) {
        if (err) return next(err);

        authenticationApiAppender.append(strategy.api).then(api => {
          res.json({
            token: token.token,
            expirationDate: token.expirationDate,
            user: userTransformer.transform(req.user, { path: req.getRoot() }),
            device: req.provisionedDevice,
            api: api
          });
        }).catch(err => {
          next(err);
        });
      });

      req.session = null;
    }
  );

};

module.exports = {
  initialize
}<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */
'use strict';

// Shimming starts here.
(function() {
  // Utils.
  var logging = require('./utils').log;
  var browserDetails = require('./utils').browserDetails;
  // Export to the adapter global object visible in the browser.
  module.exports.browserDetails = browserDetails;
  module.exports.extractVersion = require('./utils').extractVersion;
  module.exports.disableLog = require('./utils').disableLog;

  // Uncomment if you do not want any logging at all including the switch
  // statement below. Can also be turned off in the browser via
  // adapter.disableLog(true) but then logging from the switch statement below
  // will still appear.
  //require('./utils').disableLog(true);

  // Warn if version is not supported regardless of browser.
  // Min version can be set per browser in utils.js
  if (browserDetails.version < browserDetails.minVersion) {
    logging('Browser: ' + browserDetails.browser + ' Version: ' +
        browserDetails.version + ' <' + ' minimum supported version: ' +
        browserDetails.minVersion + '\n some things might not work!');
  }

  // Browser shims.
  var chromeShim = require('./chrome/chrome_shim') || null;
  var edgeShim = require('./edge/edge_shim') || null;
  var firefoxShim = require('./firefox/firefox_shim') || null;

  // Shim browser if found.
  switch (browserDetails.browser) {
    case 'chrome':
      if (!chromeShim) {
        logging('Chrome shim is not included in this adapter release.');
        return;
      }
      logging('Adapter.js shimming chrome!');
      // Export to the adapter global object visible in the browser.
      module.exports.browserShim = chromeShim;

      chromeShim.shimGetUserMedia();
      chromeShim.shimOnTrack();
      chromeShim.shimSourceObject();
      chromeShim.shimPeerConnection();
      break;
    case 'edge':
      if (!edgeShim) {
        logging('MS edge shim is not included in this adapter release.');
        return;
      }
      logging('Adapter.js shimming edge!');
      // Export to the adapter global object visible in the browser.
      module.exports.browserShim = edgeShim;

      edgeShim.shimPeerConnection();
      break;
    case 'firefox':
    if (!firefoxShim) {
        logging('Firefox shim is not included in this adapter release.');
        return;
      }
      logging('Adapter.js shimming firefox!');
      // Export to the adapter global object visible in the browser.
      module.exports.browserShim = firefoxShim;

      firefoxShim.shimGetUserMedia();
      firefoxShim.shimOnTrack();
      firefoxShim.shimSourceObject();
      firefoxShim.shimPeerConnection();
      break;
    default:
      logging('Unsupported browser!');
  }
})();
<commit_msg>ontrack shim requires peerconnection shim<commit_after>/*
 *  Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */
'use strict';

// Shimming starts here.
(function() {
  // Utils.
  var logging = require('./utils').log;
  var browserDetails = require('./utils').browserDetails;
  // Export to the adapter global object visible in the browser.
  module.exports.browserDetails = browserDetails;
  module.exports.extractVersion = require('./utils').extractVersion;
  module.exports.disableLog = require('./utils').disableLog;

  // Uncomment if you do not want any logging at all including the switch
  // statement below. Can also be turned off in the browser via
  // adapter.disableLog(true) but then logging from the switch statement below
  // will still appear.
  //require('./utils').disableLog(true);

  // Warn if version is not supported regardless of browser.
  // Min version can be set per browser in utils.js
  if (browserDetails.version < browserDetails.minVersion) {
    logging('Browser: ' + browserDetails.browser + ' Version: ' +
        browserDetails.version + ' <' + ' minimum supported version: ' +
        browserDetails.minVersion + '\n some things might not work!');
  }

  // Browser shims.
  var chromeShim = require('./chrome/chrome_shim') || null;
  var edgeShim = require('./edge/edge_shim') || null;
  var firefoxShim = require('./firefox/firefox_shim') || null;

  // Shim browser if found.
  switch (browserDetails.browser) {
    case 'chrome':
      if (!chromeShim) {
        logging('Chrome shim is not included in this adapter release.');
        return;
      }
      logging('Adapter.js shimming chrome!');
      // Export to the adapter global object visible in the browser.
      module.exports.browserShim = chromeShim;

      chromeShim.shimGetUserMedia();
      chromeShim.shimSourceObject();
      chromeShim.shimPeerConnection();
      chromeShim.shimOnTrack();
      break;
    case 'edge':
      if (!edgeShim) {
        logging('MS edge shim is not included in this adapter release.');
        return;
      }
      logging('Adapter.js shimming edge!');
      // Export to the adapter global object visible in the browser.
      module.exports.browserShim = edgeShim;

      edgeShim.shimPeerConnection();
      break;
    case 'firefox':
    if (!firefoxShim) {
        logging('Firefox shim is not included in this adapter release.');
        return;
      }
      logging('Adapter.js shimming firefox!');
      // Export to the adapter global object visible in the browser.
      module.exports.browserShim = firefoxShim;

      firefoxShim.shimGetUserMedia();
      firefoxShim.shimSourceObject();
      firefoxShim.shimPeerConnection();
      firefoxShim.shimOnTrack();
      break;
    default:
      logging('Unsupported browser!');
  }
})();
<|endoftext|>


<commit_before>// Static file handler. Serves all of the files from `public/root` directory
// under the main application root path.

'use strict';

module.exports = function (N) {

  N.validate('server_bin:core.gridfs', {
    // DON'T validate unknown params - those can exists,
    // if someone requests '/myfile.txt?xxxx' instead of '/myfile.txt/
    additionalProperties: true,
    properties: {
      bucket: {
        type: 'string',
        required: true
      }
    }
  });

  // Check if we can respond with 304 header
  // Logic borrowed from `fresh` package
  // https://github.com/visionmedia/node-fresh/blob/master/index.js
  //
  function isCacheOk(headers, fileInfo) {
    // defaults
    var etagMatches = true;
    var notModified = true;

    // fields
    var modifiedSince = headers['if-modified-since'];
    var noneMatch     = headers['if-none-match'];
    var cc            = headers['cache-control'];

    var lastModified  = fileInfo.uploadDate.getTime();
    var etag          = fileInfo.md5;

    // unconditional request
    if (!modifiedSince && !noneMatch) { return false; }

    // check for no-cache cache request directive
    if (cc && cc.indexOf('no-cache') !== -1) { return false; }

    // parse if-none-match
    if (noneMatch) { noneMatch = noneMatch.split(/ *, */); }

    // if-none-match
    if (noneMatch) { etagMatches = (noneMatch.indexOf(etag) !== -1) || noneMatch[0] === '*'; }

    // if-modified-since
    if (modifiedSince) {
      // Drop milliseconds, because header don't have those. When server
      // responded previous time, timestamp lost milliseconds.
      lastModified -= lastModified % 1000;

      notModified = lastModified <= (new Date(modifiedSince)).getTime();
    }
    return !!(etagMatches && notModified);
  }

  N.wire.on('server_bin:core.gridfs', function static_file_send(env, callback) {
    var req = env.origin.req,
        res = env.origin.res;

    if (req.method !== 'GET' && req.method !== 'HEAD') {
      callback(403);
      return;
    }

    var file = N.models.core.File;

    file.getInfo(env.params.bucket, function (err, fileInfo) {
      if (err) {
        callback(500);
        return;
      }

      if (!fileInfo) {
        callback(404);
        return;
      }

      // Ranges are not supported yet
      // We don't have files > 5MB, cache headers are enougth
      res.removeHeader('Accept-Ranges');

      // Mark for proxies, that we can return different content (plain & gzipped),
      res.setHeader('Vary', 'Accept-Encoding');

      res.setHeader('Date',           (new Date()).toUTCString());
      res.setHeader('Last-Modified',  fileInfo.uploadDate.toUTCString());
      res.setHeader('ETag',           fileInfo.md5);
      res.setHeader('Server',         'Windoz Sufface 3');
      // That helps browser to avoid unnecessary requests with 304 responses
      res.setHeader('Cache-Control',  'max-age=31536000');

      //
      // If metadata has original name, add content-disposition header.
      // Note, that images with this header can not be opened in browser
      // by direct link - download will be started. However, images in html
      // are ok.
      //
      // On practive, we should store original names only for binary attachments.
      //

      var name = (fileInfo.metadata || {}).origName;
      if (name) {
        // Some Content-Disposition magic
        // http://stackoverflow.com/questions/93551/
        var contentDisposition;
        if (/^[\x20-\x36\x38\x40\x41\x43-\x7F]*$/.test(name)) {
          // ascii chars without *,',%
          contentDisposition = 'attachment; filename=' + name;
        } else {
          // Don't care about old browsers
          // XXX: use `ua-parser` module to add alternatives
          contentDisposition = 'attachment; filename*=UTF-8\'\'' + encodeURIComponent(name);
        }
        res.setHeader('Content-Disposition', contentDisposition);
      }

      // If we can finish with 304 reply - do it.
      if (isCacheOk(req.headers, fileInfo)) {
        env.status = 304;
        env.log_request(env);
        res.statusCode = env.status;
        res.end();
        return;
      }

      // Set content type and length headers
      res.setHeader('Content-Type', fileInfo.contentType);
      res.setHeader('Content-Length', fileInfo.length);

      //
      // Begin output
      //

      env.status = 200;
      // XXX: that will cause improper size logging on connection termination
      env.log_request(env);
      res.statusCode = env.status;

      if (req.method === 'HEAD') {
        res.end();
        return;
      }

      var stream = file.getStream(env.params.bucket);

      stream.on('error', function (err) {
        N.logger.error('Error while streaming from gridfs: ' + err.message);
        res.end();
      });

      stream.pipe(res);
    });
  });
};
<commit_msg>Reduce gridfs max-age header to 7 days<commit_after>// Static file handler. Serves all of the files from `public/root` directory
// under the main application root path.

'use strict';

module.exports = function (N) {

  N.validate('server_bin:core.gridfs', {
    // DON'T validate unknown params - those can exists,
    // if someone requests '/myfile.txt?xxxx' instead of '/myfile.txt/
    additionalProperties: true,
    properties: {
      bucket: {
        type: 'string',
        required: true
      }
    }
  });

  // Check if we can respond with 304 header
  // Logic borrowed from `fresh` package
  // https://github.com/visionmedia/node-fresh/blob/master/index.js
  //
  function isCacheOk(headers, fileInfo) {
    // defaults
    var etagMatches = true;
    var notModified = true;

    // fields
    var modifiedSince = headers['if-modified-since'];
    var noneMatch     = headers['if-none-match'];
    var cc            = headers['cache-control'];

    var lastModified  = fileInfo.uploadDate.getTime();
    var etag          = fileInfo.md5;

    // unconditional request
    if (!modifiedSince && !noneMatch) { return false; }

    // check for no-cache cache request directive
    if (cc && cc.indexOf('no-cache') !== -1) { return false; }

    // parse if-none-match
    if (noneMatch) { noneMatch = noneMatch.split(/ *, */); }

    // if-none-match
    if (noneMatch) { etagMatches = (noneMatch.indexOf(etag) !== -1) || noneMatch[0] === '*'; }

    // if-modified-since
    if (modifiedSince) {
      // Drop milliseconds, because header don't have those. When server
      // responded previous time, timestamp lost milliseconds.
      lastModified -= lastModified % 1000;

      notModified = lastModified <= (new Date(modifiedSince)).getTime();
    }
    return !!(etagMatches && notModified);
  }

  N.wire.on('server_bin:core.gridfs', function static_file_send(env, callback) {
    var req = env.origin.req,
        res = env.origin.res;

    if (req.method !== 'GET' && req.method !== 'HEAD') {
      callback(403);
      return;
    }

    var file = N.models.core.File;

    file.getInfo(env.params.bucket, function (err, fileInfo) {
      if (err) {
        callback(500);
        return;
      }

      if (!fileInfo) {
        callback(404);
        return;
      }

      // Ranges are not supported yet
      // We don't have files > 5MB, cache headers are enougth
      res.removeHeader('Accept-Ranges');

      // Mark for proxies, that we can return different content (plain & gzipped),
      res.setHeader('Vary', 'Accept-Encoding');

      res.setHeader('Date',           (new Date()).toUTCString());
      res.setHeader('Last-Modified',  fileInfo.uploadDate.toUTCString());
      res.setHeader('ETag',           fileInfo.md5);
      res.setHeader('Server',         'Windoz Sufface 3');
      // That helps browser to avoid unnecessary requests with 304 responses
      // 7 days is ok. If we decide to rebuild thumbnails, those will be
      // refreshed with reasonable delay.
      res.setHeader('Cache-Control',  'max-age=604800');

      //
      // If metadata has original name, add content-disposition header.
      // Note, that images with this header can not be opened in browser
      // by direct link - download will be started. However, images in html
      // are ok.
      //
      // On practive, we should store original names only for binary attachments.
      //

      var name = (fileInfo.metadata || {}).origName;
      if (name) {
        // Some Content-Disposition magic
        // http://stackoverflow.com/questions/93551/
        var contentDisposition;
        if (/^[\x20-\x36\x38\x40\x41\x43-\x7F]*$/.test(name)) {
          // ascii chars without *,',%
          contentDisposition = 'attachment; filename=' + name;
        } else {
          // Don't care about old browsers
          // XXX: use `ua-parser` module to add alternatives
          contentDisposition = 'attachment; filename*=UTF-8\'\'' + encodeURIComponent(name);
        }
        res.setHeader('Content-Disposition', contentDisposition);
      }

      // If we can finish with 304 reply - do it.
      if (isCacheOk(req.headers, fileInfo)) {
        env.status = 304;
        env.log_request(env);
        res.statusCode = env.status;
        res.end();
        return;
      }

      // Set content type and length headers
      res.setHeader('Content-Type', fileInfo.contentType);
      res.setHeader('Content-Length', fileInfo.length);

      //
      // Begin output
      //

      env.status = 200;
      // XXX: that will cause improper size logging on connection termination
      env.log_request(env);
      res.statusCode = env.status;

      if (req.method === 'HEAD') {
        res.end();
        return;
      }

      var stream = file.getStream(env.params.bucket);

      stream.on('error', function (err) {
        N.logger.error('Error while streaming from gridfs: ' + err.message);
        res.end();
      });

      stream.pipe(res);
    });
  });
};
<|endoftext|>


<commit_before>var indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
require('dotenv').load();
var url = require('url');

var querystring = require('querystring');

var eventTypesRaw = process.env.BAMBOO_EVENT_NOTIFIER_TYPES;

var eventTypes = [];

if (eventTypesRaw != null) {
    eventTypes = eventTypesRaw.split(',');
} else {
    console.warn("github-repo-event-notifier is not setup to receive any events (BAMBOO_EVENT_NOTIFIER_TYPES is empty).");
}

var express = require('express');
var fetch = require('node-fetch');
var FormData = require('form-data');
var router = express.Router();

router.get("/", function(req, res) {
    return res.end("GitHub Bamboo Proxy");
});

console.info("registered GET /bamboo");

router.post("/", function(req, res) {
    var auth, auto_trigger, bamboo_uri, bamboo_url, build_key, data, error, error1, eventType, pass, query, room, user;
    user = process.env.BAMBOO_USERNAME;
    pass = process.env.BAMBOO_PASSWORD;
    auth = new Buffer(user + ':' + pass).toString('base64');
    query = querystring.parse(url.parse(req.url).query);
    bamboo_url = query.bamboo;
    build_key = query.buildKey;
    room = query.room;
    auto_trigger = query.auto;
    if (!bamboo_url) {
        return res.end("");
    }
    bamboo_url = bamboo_url.replace(/\/$/, "");

    data = req.body;
    eventType = req.headers["x-github-event"];
    console.log("Processing event type " + eventType + "...");
    try {
        if (indexOf.call(eventTypes, eventType) >= 0) {
            if (auto_trigger) {
                bamboo_uri = bamboo_url + "/rest/api/latest/queue/" + build_key;

                var form = new FormData();
                form.append('bamboo.variable.pull_ref', data.pull_request.head.ref);
                form.append('bamboo.variable.pull_sha', data.pull_request.head.sha);
                form.append('bamboo.variable.pull_num', data.number);

                var headers = { Authorization: "Basic " + auth};
                console.log("Invoking " + bamboo_uri);
                console.log("Headers: " + headers);
                fetch(bamboo_uri, { method: 'POST', body: form, headers: headers })
                    .catch(function(rejection) {
                        return console.log("Encountered an error sending to bamboo " + rejection);
                    })
                    .then(function(res) {
                        return res.text();
                    }).then(function(body) {
                    console.log(body);
                });
            }
        } else {
            console.log("Ignoring " + eventType + " event as it's not allowed.");
        }
    } catch (error1) {
        error = error1;
        console.log("github repo event notifier error: " + error + ". Request: " + req.body);
        console.log(error.stack);
    }
    console.log("Finished processing event type " + eventType);
    return res.end("");
});

module.exports = router
<commit_msg>Form headers.<commit_after>var indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
require('dotenv').load();
var url = require('url');

var querystring = require('querystring');

var eventTypesRaw = process.env.BAMBOO_EVENT_NOTIFIER_TYPES;

var eventTypes = [];

if (eventTypesRaw != null) {
    eventTypes = eventTypesRaw.split(',');
} else {
    console.warn("github-repo-event-notifier is not setup to receive any events (BAMBOO_EVENT_NOTIFIER_TYPES is empty).");
}

var express = require('express');
var fetch = require('node-fetch');
var FormData = require('form-data');
var router = express.Router();

router.get("/", function(req, res) {
    return res.end("GitHub Bamboo Proxy");
});

console.info("registered GET /bamboo");

router.post("/", function(req, res) {
    var auth, auto_trigger, bamboo_uri, bamboo_url, build_key, data, error, error1, eventType, pass, query, room, user;
    user = process.env.BAMBOO_USERNAME;
    pass = process.env.BAMBOO_PASSWORD;
    auth = new Buffer(user + ':' + pass).toString('base64');
    query = querystring.parse(url.parse(req.url).query);
    bamboo_url = query.bamboo;
    build_key = query.buildKey;
    room = query.room;
    auto_trigger = query.auto;
    if (!bamboo_url) {
        return res.end("");
    }
    bamboo_url = bamboo_url.replace(/\/$/, "");

    data = req.body;
    eventType = req.headers["x-github-event"];
    console.log("Processing event type " + eventType + "...");
    try {
        if (indexOf.call(eventTypes, eventType) >= 0) {
            if (auto_trigger) {
                bamboo_uri = bamboo_url + "/rest/api/latest/queue/" + build_key;

                var form = new FormData();
                form.append('bamboo.variable.pull_ref', data.pull_request.head.ref);
                form.append('bamboo.variable.pull_sha', data.pull_request.head.sha);
                form.append('bamboo.variable.pull_num', data.number);

                var headers = { Authorization: "Basic " + auth};
                console.log("Invoking " + bamboo_uri);
                console.log("Headers: " + headers);
                console.log(form.getHeaders({ Authorization: "Basic " + auth}));
                fetch(bamboo_uri, { method: 'POST', body: form, headers: headers })
                    .catch(function(rejection) {
                        return console.log("Encountered an error sending to bamboo " + rejection);
                    })
                    .then(function(res) {
                        return res.text();
                    }).then(function(body) {
                    console.log(body);
                });
            }
        } else {
            console.log("Ignoring " + eventType + " event as it's not allowed.");
        }
    } catch (error1) {
        error = error1;
        console.log("github repo event notifier error: " + error + ". Request: " + req.body);
        console.log(error.stack);
    }
    console.log("Finished processing event type " + eventType);
    return res.end("");
});

module.exports = router
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2018 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import React from 'react'
import ReactDOM from 'react-dom'
import page from 'page'
import qs from 'qs'
import DeveloperKeysApp from './App'
import actions from './actions/developerKeysActions'
import store from './store/store'

/**
 * Route Handlers
 */
// ctx is context
function renderShowDeveloperKeys(ctx) {
  if (ctx.hash === 'key_modal_opened') {
    store.dispatch(actions.developerKeysModalOpen())
  } else {
    store.dispatch(actions.developerKeysModalClose())
  }

  store.dispatch(
    actions.getDeveloperKeys(`/api/v1/accounts/${ctx.params.contextId}/developer_keys`, true)
  )

  store.dispatch(actions.listDeveloperKeyScopes(ctx.params.contextId))

  const view = () => {
    const state = store.getState()
    ReactDOM.render(
      <DeveloperKeysApp applicationState={state} actions={actions} store={store} ctx={ctx} />,
      document.getElementById('reactContent')
    )
  }
  // returns A function that unsubscribes the change listener.
  store.subscribe(view)

  // renders the page
  view()
}

/**
 * Middlewares
 */

function parseQueryString(ctx, next) {
  ctx.query = qs.parse(ctx.querystring)
  next()
}

/**
 * Route Configuration
 */
page('*', parseQueryString) // Middleware to parse querystring to object

page('/accounts/:contextId/developer_keys', renderShowDeveloperKeys)

// export default for a module
// when we import router.js, this is what we get by default
export default {
  start() {
    page.start()
  }
}
<commit_msg>Close DevKey Modal without refetching the DevKey index<commit_after>/*
 * Copyright (C) 2018 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import React from 'react'
import ReactDOM from 'react-dom'
import page from 'page'
import qs from 'qs'
import DeveloperKeysApp from './App'
import actions from './actions/developerKeysActions'
import store from './store/store'

let state = store.getState()
/**
 * Route Handlers
 */
// ctx is context
function renderShowDeveloperKeys(ctx) {
  if (ctx.hash === 'key_modal_opened') {
    store.dispatch(actions.developerKeysModalOpen())
  } else {
    store.dispatch(actions.developerKeysModalClose())
  }

  if (!state.listDeveloperKeys.listDeveloperKeysSuccessful) {
    store.dispatch(
      actions.getDeveloperKeys(`/api/v1/accounts/${ctx.params.contextId}/developer_keys`, true)
    )

    if (!state.listDeveloperKeyScopes.listDeveloperKeyScopesSuccessful) {
      store.dispatch(actions.listDeveloperKeyScopes(ctx.params.contextId))
    }

    const view = () => {
      state = store.getState()
      ReactDOM.render(
        <DeveloperKeysApp applicationState={state} actions={actions} store={store} ctx={ctx} />,
        document.getElementById('reactContent')
      )
    }
    // returns A function that unsubscribes the change listener.
    store.subscribe(view)
    // renders the page
    view()
  }
}

/**
 * Middlewares
 */

function parseQueryString(ctx, next) {
  ctx.query = qs.parse(ctx.querystring)
  next()
}

/**
 * Route Configuration
 */
page('*', parseQueryString) // Middleware to parse querystring to object

page('/accounts/:contextId/developer_keys', renderShowDeveloperKeys)

// export default for a module
// when we import router.js, this is what we get by default
export default {
  start() {
    page.start()
  }
}
<|endoftext|>


<commit_before>
$(document).ready(function() {
	$('#target-input').autocomplete({
		autoFocus: true,
		delay: 500,
		minLength: 0,
		select: function(event, selected) {
			$(event.target).focus();

			if (!selected.item.leaf) {
				setTimeout(function() {
					$(event.target).autocomplete("search", selected.item.value);
				}, 1);
			}
		},
		source: function(request, response) {
			$.ajax({
				cache: false,
				url: '/graphite/metrics',
				data: {
					"target": request.term
				},
				timeout: 5000,
				success: function(data, status, xhr) {
					var options = $.map(data, function(element) {
						return {"label": element['p'], "value": element['p'], "leaf": element['l']};
					});
					response(options);
				},
				error: function(xhr, status, error) {
					response([]);
				}
			});
		}
	});

	setTimeout(function() {
		$('#target-input').focus();
		$('#target-input').autocomplete("search", "");
	}, 1);

	function graphPreview() {
		var start = moment().subtract("hours", 1).format('X');
		var end = moment().format('X');
		var target = $('#target-input').val();
		var query = (target == '') ? '' : "target[]=" + target;
		updateGraphHelper("/graphite/datapoints?" + query, true, "target-graph svg", start, end);
	}
});
<commit_msg>increase timeout on metric search autocomplete to 30 seconds<commit_after>
$(document).ready(function() {
	$('#target-input').autocomplete({
		autoFocus: true,
		delay: 500,
		minLength: 0,
		select: function(event, selected) {
			$(event.target).focus();

			if (!selected.item.leaf) {
				setTimeout(function() {
					$(event.target).autocomplete("search", selected.item.value);
				}, 1);
			}
		},
		source: function(request, response) {
			$.ajax({
				cache: false,
				url: '/graphite/metrics',
				data: {
					"target": request.term
				},
				timeout: 30000,
				success: function(data, status, xhr) {
					var options = $.map(data, function(element) {
						return {"label": element['p'], "value": element['p'], "leaf": element['l']};
					});
					response(options);
				},
				error: function(xhr, status, error) {
					response([]);
				}
			});
		}
	});

	setTimeout(function() {
		$('#target-input').focus();
		$('#target-input').autocomplete("search", "");
	}, 1);

	function graphPreview() {
		var start = moment().subtract("hours", 1).format('X');
		var end = moment().format('X');
		var target = $('#target-input').val();
		var query = (target == '') ? '' : "target[]=" + target;
		updateGraphHelper("/graphite/datapoints?" + query, true, "target-graph svg", start, end);
	}
});
<|endoftext|>


<commit_before>var gulp = require("gulp");
var sass = require("gulp-sass");
var autoPrefixer = require("gulp-autoprefixer");
var minifyCss = require("gulp-minify-css");
var jshint = require("gulp-jshint");
var stylishJshint = require("jshint-stylish");
var uglify = require("gulp-uglify");
var plumber = require("gulp-plumber");
var glob = require("glob");
var path = require("path");

var SASS_SRC = "./web-src/scss/*.scss"
var SASS_DEST = "./static/css"
var JS_SRC = "./web-src/js/*.js"
var JS_DEST = "./static/js"

//Search themes folder for theme gulpfiles
//This must be synchronus so it runs before gulp searches for tasks
files = glob("themes/*/*(gulpfile|gulp|build).js", {sync: true})
files.forEach(function(file){
	require(path.resolve(file)) //We don't have to store this, beacuse we just need its code to execute.
});

gulp.task("sass", function() {
	return gulp.src(SASS_SRC)
		.pipe(plumber())
		.pipe(sass().on("error", sass.logError))
		.pipe(autoPrefixer({
			browsers: [
				"last 2 versions",
				"IE 9"
			]
		}))
		.pipe(minifyCss())
		.pipe(gulp.dest(SASS_DEST));
});

gulp.task("js", function() {
	return gulp.src(JS_SRC)
		.pipe(plumber())
		.pipe(jshint())
		.pipe(jshint.reporter(stylishJshint))
		.pipe(jshint.reporter("fail"))
		.pipe(uglify())
		.pipe(gulp.dest(JS_DEST));
});

gulp.task("watch", function() {
	//Watch Sass for changes.
	var sassWatch = gulp.watch(SASS_SRC, ["sass"]);
	sassWatch.on("change", function (event) {
		console.log("Event '"+ event.type + "' detected on " + event.path + ". Running sass.");
	});

	//Watch JS for changes.
	var jsWatch = gulp.watch(JS_SRC, ["js"]);
	jsWatch.on("change", function(event) {
		console.log("Event '"+ event.type + "' detected on " + event.path + ". Running js.");
	});
});
<commit_msg>Run jshint on gulpfile<commit_after>var gulp = require("gulp");
var sass = require("gulp-sass");
var autoPrefixer = require("gulp-autoprefixer");
var minifyCss = require("gulp-minify-css");
var jshint = require("gulp-jshint");
var stylishJshint = require("jshint-stylish");
var uglify = require("gulp-uglify");
var plumber = require("gulp-plumber");
var glob = require("glob");
var path = require("path");

var SASS_SRC = "./web-src/scss/*.scss";
var SASS_DEST = "./static/css";
var JS_SRC = "./web-src/js/*.js";
var JS_DEST = "./static/js";

//Search themes folder for theme gulpfiles
//This must be synchronus so it runs before gulp searches for tasks
files = glob("themes/*/*(gulpfile|gulp|build).js", {sync: true});
files.forEach(function(file){
	require(path.resolve(file)); //We don't have to store this, beacuse we just need its code to execute.
});

gulp.task("sass", function() {
	return gulp.src(SASS_SRC)
		.pipe(plumber())
		.pipe(sass().on("error", sass.logError))
		.pipe(autoPrefixer({
			browsers: [
				"last 2 versions",
				"IE 9"
			]
		}))
		.pipe(minifyCss())
		.pipe(gulp.dest(SASS_DEST));
});

gulp.task("js", function() {
	return gulp.src(JS_SRC)
		.pipe(plumber())
		.pipe(jshint())
		.pipe(jshint.reporter(stylishJshint))
		.pipe(jshint.reporter("fail"))
		.pipe(uglify())
		.pipe(gulp.dest(JS_DEST));
});

gulp.task("watch", function() {
	//Watch Sass for changes.
	var sassWatch = gulp.watch(SASS_SRC, ["sass"]);
	sassWatch.on("change", function (event) {
		console.log("Event '"+ event.type + "' detected on " + event.path + ". Running sass.");
	});

	//Watch JS for changes.
	var jsWatch = gulp.watch(JS_SRC, ["js"]);
	jsWatch.on("change", function(event) {
		console.log("Event '"+ event.type + "' detected on " + event.path + ". Running js.");
	});
});
<|endoftext|>


<commit_before>'use strict';

const database = require('./data.json');

// Starts connection
const connect = function () {
  return database;
};

module.exports = {
  connect,
};
<commit_msg>Validate that memory database is not used in production<commit_after>'use strict';

const { throwError } = require('../../../error');

const database = require('./data.json');

// Starts connection
const connect = function ({ runOpts }) {
  validateEnv({ runOpts });

  return database;
};

const validateEnv = function ({ runOpts }) {
  if (runOpts.env === 'dev') { return; }

  const message = 'Memory database must not be used in production, i.e. option \'env\' must be equal to \'dev\'';
  throwError(message, { reason: 'CONF_VALIDATION' });
};

module.exports = {
  connect,
};
<|endoftext|>