<commit_before>'use strict';

var assert  = require('assert');
var Syntax  = require('esprima-fb').Syntax;
var utils   = require('jstransform/src/utils');

/**
 * Visit ImportDeclaration.
 *
 * Examples:
 *
 *    import "module"
 *    import name from "module"
 *    import { name, one as other } from "module"
 */
function visitImportDeclaration(traverse, node, path, state) {
  var specifier, name;
  utils.catchup(node.range[0], state);

  switch (node.kind) {

    // import "module"
    case undefined:
      utils.append('require(' + node.source.raw + ');', state);
      break;

    // import name from "module"
    case "default":
      specifier = node.specifiers[0];
      assert(specifier, "default import without specifier: " + node);
      name = specifier.name ? specifier.name.name : specifier.id.name;
      utils.append('var ' + name + ' = require(' + node.source.raw + ');', state);
      break;

    // import {name, one as other} from "module"
    case "named":
      var modID = genID('mod');
      utils.append('var ' + modID + ' = require(' + node.source.raw + ');\n', state);

      for (var i = 0, len = node.specifiers.length; i < len; i++) {
        specifier = node.specifiers[i];
        name = specifier.name ? specifier.name.name : specifier.id.name;
        utils.append('var ' + name + ' = ' + modID + '.' + specifier.id.name + ';', state);
        if (i !== len - 1) {
          utils.append('\n', state);
        }
      }

      break;

    default:
      assert(false, "don't know how to transform: " + node.kind);
  }

  utils.move(node.range[1], state);
  return false;
}

visitImportDeclaration.test = function(node, path, state) {
  return node.type === Syntax.ImportDeclaration;
};

/**
 * Visit ExportDeclaration.
 *
 * Examples:
 *
 *    export default = value
 *    export DECLARATION
 *    export { name, one as other }
 */
function visitExportDeclaration(traverse, node, path, state) {
  var specifier, name, len, i;
  utils.catchup(node.range[0], state);

  if (node.declaration) {

    // export default = value
    if (Array.isArray(node.declaration)) {
      name = node.declaration[0].id.name;
      switch (name) {
        case 'default':
          utils.append('module.exports =', state);
          break;
        default:
          utils.append('module.exports.' + name + ' = ', state);
      }

      if (node.declaration[0].init) {
        // -1 compensates for a additiona space after '=' token
        utils.move(node.declaration[0].init.range[0] - 1, state);
      } else {
        utils.move(node.range[1], state);
      }

    // export DECLARATION
    } else {
      switch (node.declaration.type) {
        // export var name = value
        case Syntax.VariableDeclaration:
          name = node.declaration.declarations[0].id.name;
          utils.append('var ' + name + ' = module.exports.' + name + ' = ', state);
          utils.move(node.declaration.declarations[0].init.range[0], state);
          break;
        case Syntax.FunctionDeclaration:
          name = node.declaration.id.name;
          utils.move(node.declaration.range[0], state);
          utils.catchup(node.declaration.range[1], state);
          utils.append('\nmodule.exports.' + name + ' = ' + name + ';', state);
          break;
        case Syntax.ClassDeclaration:
          name = node.declaration.id.name;
          utils.move(node.declaration.range[0], state);
          traverse(node.declaration, path, state);
          utils.append('module.exports.' + name + ' = ' + name + ';', state);
          break;
        default:
          assert(false, "unknown declaration: " + node.declaration.type);
      }
    }

  } else if (node.source) {

    var modID = genID('mod');
    utils.append('var ' + modID + ' = require(' + node.source.raw + ');\n', state);

    // export * from "module"
    if (node.specifiers.length === 1 &&
        node.specifiers[0].type === Syntax.ExportBatchSpecifier) {
      var keyID = genID('key');
      utils.append(
        'for (var ' + keyID + ' in ' + modID + ') ' +
        'module.exports[' + keyID + '] = ' + modID + '[' + keyID + '];',
        state
      );

    // export {name, one as other} from "module"
    } else {
      for (i = 0, len = node.specifiers.length; i < len; i++) {
        specifier = node.specifiers[i];
        name = specifier.name ? specifier.name.name : specifier.id.name;
        utils.append(
          'module.exports.' + name + ' = ' + modID +
          '.' + specifier.id.name + ';',
          state
        );
        if (i !== len - 1) {
          utils.append('\n', state);
        }
      }
    }
    utils.move(node.range[1], state);

  } else if (node.specifiers) {

    // export { name, one as other }
    for (i = 0, len = node.specifiers.length; i < len; i++) {
      specifier = node.specifiers[i];
      name = specifier.name ? specifier.name.name : specifier.id.name;
      utils.append('module.exports.' + name + ' = ' + specifier.id.name + ';', state);
      if (i !== len - 1) {
        utils.append('\n', state);
      }
    }
    utils.move(node.range[1], state);

  } else {

    assert(false, "don't know how to compile export declaration");
  }

  return false;
}

visitExportDeclaration.test = function(node, path, state) {
  return node.type === Syntax.ExportDeclaration;
};

/**
 * Visit ModuleDeclaration.
 *
 * Example:
 *
 *    module name from "module"
 */
function visitModuleDeclaration(traverse, node, path, state) {
  utils.catchup(node.range[0], state);
  utils.append('var ' + node.id.name + ' = require(' + node.source.raw + ');', state);
  utils.move(node.range[1], state);
  return false;
}

visitModuleDeclaration.test = function(node, path, state) {
  return node.type === Syntax.ModuleDeclaration;
};

var num = 0;

/**
 * Generate unique identifier with a given prefix.
 *
 * @private
 */
function genID(prefix) {
  return prefix + '$' + (num++);
}

module.exports.__resetModuleState = function() { num = 0; };

module.exports.visitorList = [
  visitImportDeclaration,
  visitModuleDeclaration,
  visitExportDeclaration
];
<commit_msg>Gardening<commit_after>'use strict';

var assert  = require('assert');
var Syntax  = require('esprima-fb').Syntax;
var utils   = require('jstransform/src/utils');

/**
 * Visit ImportDeclaration.
 *
 * Examples:
 *
 *    import "module"
 *    import name from "module"
 *    import { name, one as other } from "module"
 */
function visitImportDeclaration(traverse, node, path, state) {
  var specifier, name;
  utils.catchup(node.range[0], state);

  switch (node.kind) {

    // import "module"
    case undefined:
      utils.append('require(' + node.source.raw + ');', state);
      break;

    // import name from "module"
    case "default":
      specifier = node.specifiers[0];
      assert(specifier, "default import without specifier: " + node);
      name = specifier.name ? specifier.name.name : specifier.id.name;
      utils.append('var ' + name + ' = require(' + node.source.raw + ');', state);
      break;

    // import {name, one as other} from "module"
    case "named":
      var modID = genID('mod');
      utils.append('var ' + modID + ' = require(' + node.source.raw + ');\n', state);

      for (var i = 0, len = node.specifiers.length; i < len; i++) {
        specifier = node.specifiers[i];
        name = specifier.name ? specifier.name.name : specifier.id.name;
        utils.append('var ' + name + ' = ' + modID + '.' + specifier.id.name + ';', state);
        if (i !== len - 1) {
          utils.append('\n', state);
        }
      }

      break;

    default:
      assert(false, "don't know how to transform: " + node.kind);
  }

  utils.move(node.range[1], state);
  return false;
}

visitImportDeclaration.test = function(node, path, state) {
  return node.type === Syntax.ImportDeclaration;
};

/**
 * Visit ExportDeclaration.
 *
 * Examples:
 *
 *    export default = value
 *    export default;
 *    export DECLARATION
 *    export { name, one as other }
 */
function visitExportDeclaration(traverse, node, path, state) {
  var specifier, name, len, i;
  utils.catchup(node.range[0], state);

  if (node.declaration) {

    // export default = value
    if (Array.isArray(node.declaration)) {
      name = node.declaration[0].id.name;
      switch (name) {
        case 'default':
          utils.append('module.exports =', state);
          break;
        default:
          utils.append('module.exports.' + name + ' = ', state);
      }

      if (node.declaration[0].init) {
        // -1 compensates for an additional space after '=' token
        utils.move(node.declaration[0].init.range[0] - 1, state);
      } else {
        utils.move(node.range[1], state);
      }

    // export DECLARATION
    } else {
      switch (node.declaration.type) {
        // export var name = value
        case Syntax.VariableDeclaration:
          name = node.declaration.declarations[0].id.name;
          utils.append('var ' + name + ' = module.exports.' + name + ' = ', state);
          utils.move(node.declaration.declarations[0].init.range[0], state);
          break;
        case Syntax.FunctionDeclaration:
          name = node.declaration.id.name;
          utils.move(node.declaration.range[0], state);
          utils.catchup(node.declaration.range[1], state);
          utils.append('\nmodule.exports.' + name + ' = ' + name + ';', state);
          break;
        case Syntax.ClassDeclaration:
          name = node.declaration.id.name;
          utils.move(node.declaration.range[0], state);
          traverse(node.declaration, path, state);
          utils.append('module.exports.' + name + ' = ' + name + ';', state);
          break;
        default:
          assert(false, "unknown declaration: " + node.declaration.type);
      }
    }

  } else if (node.source) {

    var modID = genID('mod');
    utils.append('var ' + modID + ' = require(' + node.source.raw + ');\n', state);

    // export * from "module"
    if (node.specifiers.length === 1 &&
        node.specifiers[0].type === Syntax.ExportBatchSpecifier) {
      var keyID = genID('key');
      utils.append(
        'for (var ' + keyID + ' in ' + modID + ') ' +
        'module.exports[' + keyID + '] = ' + modID + '[' + keyID + '];',
        state
      );

    // export {name, one as other} from "module"
    } else {
      for (i = 0, len = node.specifiers.length; i < len; i++) {
        specifier = node.specifiers[i];
        name = specifier.name ? specifier.name.name : specifier.id.name;
        utils.append(
          'module.exports.' + name + ' = ' + modID +
          '.' + specifier.id.name + ';',
          state
        );
        if (i !== len - 1) {
          utils.append('\n', state);
        }
      }
    }
    utils.move(node.range[1], state);

  } else if (node.specifiers) {

    // export { name, one as other }
    for (i = 0, len = node.specifiers.length; i < len; i++) {
      specifier = node.specifiers[i];
      name = specifier.name ? specifier.name.name : specifier.id.name;
      utils.append('module.exports.' + name + ' = ' + specifier.id.name + ';', state);
      if (i !== len - 1) {
        utils.append('\n', state);
      }
    }
    utils.move(node.range[1], state);

  } else {

    assert(false, "don't know how to compile export declaration");
  }

  return false;
}

visitExportDeclaration.test = function(node, path, state) {
  return node.type === Syntax.ExportDeclaration;
};

/**
 * Visit ModuleDeclaration.
 *
 * Example:
 *
 *    module name from "module"
 */
function visitModuleDeclaration(traverse, node, path, state) {
  utils.catchup(node.range[0], state);
  utils.append('var ' + node.id.name + ' = require(' + node.source.raw + ');', state);
  utils.move(node.range[1], state);
  return false;
}

visitModuleDeclaration.test = function(node, path, state) {
  return node.type === Syntax.ModuleDeclaration;
};

var num = 0;

/**
 * Generate unique identifier with a given prefix.
 *
 * @private
 */
function genID(prefix) {
  return prefix + '$' + (num++);
}

module.exports.__resetModuleState = function() { num = 0; };

module.exports.visitorList = [
  visitImportDeclaration,
  visitModuleDeclaration,
  visitExportDeclaration
];
<|endoftext|>


<commit_before>/**
 * Created by carlen on 4/9/17.
 */
const { dialog } = require('electron').remote

app.controller('gitController', ['$scope', '$stateParams', '$state', 'localStorageService', 'usSpinnerService',
    'gitService',
    function ($scope, $stateParams, $state, localStorageService, usSpinnerService, gitService) {
        const user = localStorageService.get('user')
        const wesh = msg => console.log(msg)
        const cloneSpinner = 'cloneSpinner'
        const notPath = 'Please choose a folder'
        const cloneError = 'Error while cloning, the repository was not cloned'
        const userNameError = 'Please enter a user name'
        $scope.repoName = $stateParams.repoName
        $scope.gitPath = null
        $scope.cloneError = false
        $scope.errClone = null
        $scope.username = null
        $scope.successClone = false

        $scope.startSpin = id => usSpinnerService.spin(id)
        $scope.stopSpin = id => usSpinnerService.stop(id)

        if (!user) $scope.goToAcl = name => $state.go('home')

        $scope.getDirectory = () => {
            const directory = dialog.showOpenDialog({ properties: [ 'openDirectory' ] })
            if (directory === undefined || directory === null) return
            $scope.gitPath = directory
            if ($scope.errClone === notPath) $scope.cloneError = false
        }

        $scope.gitClone = () => {
            if ($scope.gitPath === undefined || $scope.gitPath === null) {
                $scope.cloneError = true
                $scope.errClone = notPath
                $scope.successClone = false
                return
            }
            if ($scope.username === null || $scope.username === '') {
                $scope.cloneError = true
                $scope.errClone = userNameError
                $scope.successClone = false
                return
            }
            $scope.startSpin(cloneSpinner)
            gitService.clone($scope.repoName, $scope.gitPath, $scope.username)
                .then(_ => {
                    $scope.cloneError = false
                    $scope.stopSpin(cloneSpinner)
                    $scope.successClone = true
                    $scope.$apply()
                })
                .catch(_ => {
                    $scope.stopSpin(cloneSpinner)
                    $scope.cloneError = true
                    $scope.errClone = cloneError
                    $scope.successClone = false
                    $scope.$apply()
                })
        }
    }])<commit_msg>email clone for tek1<commit_after>/**
 * Created by carlen on 4/9/17.
 */
const { dialog } = require('electron').remote

app.controller('gitController', ['$scope', '$stateParams', '$state', 'localStorageService', 'usSpinnerService',
    'gitService',
    function ($scope, $stateParams, $state, localStorageService, usSpinnerService, gitService) {
        const user = localStorageService.get('user')
        const wesh = msg => console.log(msg)
        const cloneSpinner = 'cloneSpinner'
        const notPath = 'Please choose a folder'
        const cloneError = 'Error while cloning, the repository was not cloned'
        const userNameError = 'Please enter a user name'
        $scope.repoName = $stateParams.repoName
        $scope.gitPath = null
        $scope.cloneError = false
        $scope.errClone = null
        $scope.username = user.userName
        $scope.successClone = false

        $scope.startSpin = id => usSpinnerService.spin(id)
        $scope.stopSpin = id => usSpinnerService.stop(id)

        if (!user) $scope.goToAcl = name => $state.go('home')

        $scope.getDirectory = () => {
            const directory = dialog.showOpenDialog({ properties: [ 'openDirectory' ] })
            if (directory === undefined || directory === null) return
            $scope.gitPath = directory
            if ($scope.errClone === notPath) $scope.cloneError = false
        }

        $scope.gitClone = () => {
            if ($scope.gitPath === undefined || $scope.gitPath === null) {
                $scope.cloneError = true
                $scope.errClone = notPath
                $scope.successClone = false
                return
            }
            if ($scope.username === null || $scope.username === '') {
                $scope.cloneError = true
                $scope.errClone = userNameError
                $scope.successClone = false
                return
            }
            $scope.startSpin(cloneSpinner)
            gitService.clone($scope.repoName, $scope.gitPath, $scope.username)
                .then(_ => {
                    $scope.cloneError = false
                    $scope.stopSpin(cloneSpinner)
                    $scope.successClone = true
                    $scope.$apply()
                })
                .catch(_ => {
                    $scope.stopSpin(cloneSpinner)
                    $scope.cloneError = true
                    $scope.errClone = cloneError
                    $scope.successClone = false
                    $scope.$apply()
                })
        }
    }])<|endoftext|>


<commit_before>// # Update Checking Service
//
// Makes a request to Ghost.org to check if there is a new version of Ghost available.
// The service is provided in return for users opting in to anonymous usage data collection
// Blog owners can opt-out of update checks by setting 'updateCheck: false' in their config.js
//
// The data collected is as follows:
// - blog id - a hash of the blog hostname, pathname and dbHash. No identifiable info is stored.
// - ghost version
// - node version
// - npm version
// - env - production or development
// - database type - SQLite, MySQL, PostgreSQL
// - email transport - mail.options.service, or otherwise mail.transport
// - created date - database creation date
// - post count - total number of posts
// - user count - total number of users
// - theme - name of the currently active theme
// - apps - names of any active apps

var crypto   = require('crypto'),
    exec     = require('child_process').exec,
    https    = require('https'),
    moment   = require('moment'),
    semver   = require('semver'),
    Promise  = require('bluebird'),
    _        = require('lodash'),
    url      = require('url'),

    api      = require('./api'),
    config   = require('./config'),
    errors   = require('./errors'),
    packageInfo = require('../../package.json'),

    internal = {context: {internal: true}},
    allowedCheckEnvironments = ['development', 'production'],
    checkEndpoint = 'updates.ghost.org',
    currentVersion = packageInfo.version;

function updateCheckError(error) {
    errors.logError(
        error,
        'Checking for updates failed, your blog will continue to function.',
        'If you get this error repeatedly, please seek help from https://ghost.org/forum.'
    );
}

function updateCheckData() {
    var data = {},
        ops = [],
        mailConfig = config.mail;

    ops.push(api.settings.read(_.extend(internal, {key: 'dbHash'})).catch(errors.rejectError));
    ops.push(api.settings.read(_.extend(internal, {key: 'activeTheme'})).catch(errors.rejectError));
    ops.push(api.settings.read(_.extend(internal, {key: 'activeApps'}))
        .then(function (response) {
            var apps = response.settings[0];
            try {
                apps = JSON.parse(apps.value);
            } catch (e) {
                return errors.rejectError(e);
            }

            return _.reduce(apps, function (memo, item) { return memo === '' ? memo + item : memo + ', ' + item; }, '');
        }).catch(errors.rejectError));
    ops.push(api.posts.browse().catch(errors.rejectError));
    ops.push(api.users.browse(internal).catch(errors.rejectError));
    ops.push(Promise.promisify(exec)('npm -v').catch(errors.rejectError));

    data.ghost_version   = currentVersion;
    data.node_version    = process.versions.node;
    data.env             = process.env.NODE_ENV;
    data.database_type   = config.database.client;
    data.email_transport = mailConfig && (mailConfig.options && mailConfig.options.service ? mailConfig.options.service : mailConfig.transport);

    return Promise.settle(ops).then(function (descriptors) {
        var hash             = descriptors[0].value().settings[0],
            theme            = descriptors[1].value().settings[0],
            apps             = descriptors[2].value(),
            posts            = descriptors[3].value(),
            users            = descriptors[4].value(),
            npm              = descriptors[5].value(),
            blogUrl          = url.parse(config.url),
            blogId           = blogUrl.hostname + blogUrl.pathname.replace(/\//, '') + hash.value;

        data.blog_id         = crypto.createHash('md5').update(blogId).digest('hex');
        data.theme           = theme ? theme.value : '';
        data.apps            = apps || '';
        data.post_count      = posts && posts.meta && posts.meta.pagination ? posts.meta.pagination.total : 0;
        data.user_count      = users && users.users && users.users.length ? users.users.length : 0;
        data.blog_created_at = users && users.users && users.users[0] && users.users[0].created_at ? moment(users.users[0].created_at).unix() : '';
        data.npm_version     = _.isArray(npm) && npm[0] ? npm[0].toString().replace(/\n/, '') : '';

        return data;
    }).catch(updateCheckError);
}

function updateCheckRequest() {
    return updateCheckData().then(function (reqData) {
        var resData = '',
            headers,
            req;

        reqData = JSON.stringify(reqData);

        headers = {
            'Content-Length': reqData.length
        };

        return new Promise(function (resolve, reject) {
            req = https.request({
                hostname: checkEndpoint,
                method: 'POST',
                headers: headers
            }, function (res) {
                res.on('error', function (error) { reject(error); });
                res.on('data', function (chunk) { resData += chunk; });
                res.on('end', function () {
                    try {
                        resData = JSON.parse(resData);
                        resolve(resData);
                    } catch (e) {
                        reject('Unable to decode update response');
                    }
                });
            });

            req.write(reqData);
            req.end();

            req.on('error', function (error) {
                reject(error);
            });
        });
    });
}

// ## Update Check Response
// Handles the response from the update check
// Does two things with the information received:
// 1. Updates the time we can next make a check
// 2. Checks if the version in the response is new, and updates the notification setting
function updateCheckResponse(response) {
    var ops = [];

    ops.push(
        api.settings.edit(
            {settings: [{key: 'nextUpdateCheck', value: response.next_check}]},
            internal
        ).catch(errors.rejectError),
        api.settings.edit(
            {settings: [{key: 'displayUpdateNotification', value: response.version}]},
            internal
        ).catch(errors.rejectError)
    );

    return Promise.settle(ops).then(function (descriptors) {
        descriptors.forEach(function (d) {
            if (d.isRejected()) {
                errors.rejectError(d.reason());
            }
        });
    });
}

function updateCheck() {
    // The check will not happen if:
    // 1. updateCheck is defined as false in config.js
    // 2. we've already done a check this session
    // 3. we're not in production or development mode
    // TODO: need to remove config.updateCheck in favor of config.privacy.updateCheck in future version (it is now deprecated)
    if (config.updateCheck === false || config.isPrivacyDisabled('useUpdateCheck') || _.indexOf(allowedCheckEnvironments, process.env.NODE_ENV) === -1) {
        // No update check
        return Promise.resolve();
    } else {
        return api.settings.read(_.extend(internal, {key: 'nextUpdateCheck'})).then(function (result) {
            var nextUpdateCheck = result.settings[0];

            if (nextUpdateCheck && nextUpdateCheck.value && nextUpdateCheck.value > moment().unix()) {
                // It's not time to check yet
                return;
            } else {
                // We need to do a check
                return updateCheckRequest()
                    .then(updateCheckResponse)
                    .catch(updateCheckError);
            }
        }).catch(updateCheckError);
    }
}

function showUpdateNotification() {
    return api.settings.read(_.extend(internal, {key: 'displayUpdateNotification'})).then(function (response) {
        var display = response.settings[0];

        // Version 0.4 used boolean to indicate the need for an update. This special case is
        // translated to the version string.
        // TODO: remove in future version.
        if (display.value === 'false' || display.value === 'true' || display.value === '1' || display.value === '0') {
            display.value = '0.4.0';
        }

        if (display && display.value && currentVersion && semver.gt(display.value, currentVersion)) {
            return display.value;
        }

        return false;
    });
}

module.exports = updateCheck;
module.exports.showUpdateNotification = showUpdateNotification;
<commit_msg>Delay updateCheck to +24h on error<commit_after>// # Update Checking Service
//
// Makes a request to Ghost.org to check if there is a new version of Ghost available.
// The service is provided in return for users opting in to anonymous usage data collection
// Blog owners can opt-out of update checks by setting 'updateCheck: false' in their config.js
//
// The data collected is as follows:
// - blog id - a hash of the blog hostname, pathname and dbHash. No identifiable info is stored.
// - ghost version
// - node version
// - npm version
// - env - production or development
// - database type - SQLite, MySQL, PostgreSQL
// - email transport - mail.options.service, or otherwise mail.transport
// - created date - database creation date
// - post count - total number of posts
// - user count - total number of users
// - theme - name of the currently active theme
// - apps - names of any active apps

var crypto   = require('crypto'),
    exec     = require('child_process').exec,
    https    = require('https'),
    moment   = require('moment'),
    semver   = require('semver'),
    Promise  = require('bluebird'),
    _        = require('lodash'),
    url      = require('url'),

    api      = require('./api'),
    config   = require('./config'),
    errors   = require('./errors'),
    packageInfo = require('../../package.json'),

    internal = {context: {internal: true}},
    allowedCheckEnvironments = ['development', 'production'],
    checkEndpoint = 'updates.ghost.org',
    currentVersion = packageInfo.version;

function updateCheckError(error) {
    api.settings.edit(
        {settings: [{key: 'nextUpdateCheck', value: Math.round(Date.now() / 1000 + 24 * 3600)}]},
        internal
    ).catch(errors.rejectError);

    errors.logError(
        error,
        'Checking for updates failed, your blog will continue to function.',
        'If you get this error repeatedly, please seek help from https://ghost.org/forum.'
    );
}

function updateCheckData() {
    var data = {},
        ops = [],
        mailConfig = config.mail;

    ops.push(api.settings.read(_.extend(internal, {key: 'dbHash'})).catch(errors.rejectError));
    ops.push(api.settings.read(_.extend(internal, {key: 'activeTheme'})).catch(errors.rejectError));
    ops.push(api.settings.read(_.extend(internal, {key: 'activeApps'}))
        .then(function (response) {
            var apps = response.settings[0];
            try {
                apps = JSON.parse(apps.value);
            } catch (e) {
                return errors.rejectError(e);
            }

            return _.reduce(apps, function (memo, item) { return memo === '' ? memo + item : memo + ', ' + item; }, '');
        }).catch(errors.rejectError));
    ops.push(api.posts.browse().catch(errors.rejectError));
    ops.push(api.users.browse(internal).catch(errors.rejectError));
    ops.push(Promise.promisify(exec)('npm -v').catch(errors.rejectError));

    data.ghost_version   = currentVersion;
    data.node_version    = process.versions.node;
    data.env             = process.env.NODE_ENV;
    data.database_type   = config.database.client;
    data.email_transport = mailConfig && (mailConfig.options && mailConfig.options.service ? mailConfig.options.service : mailConfig.transport);

    return Promise.settle(ops).then(function (descriptors) {
        var hash             = descriptors[0].value().settings[0],
            theme            = descriptors[1].value().settings[0],
            apps             = descriptors[2].value(),
            posts            = descriptors[3].value(),
            users            = descriptors[4].value(),
            npm              = descriptors[5].value(),
            blogUrl          = url.parse(config.url),
            blogId           = blogUrl.hostname + blogUrl.pathname.replace(/\//, '') + hash.value;

        data.blog_id         = crypto.createHash('md5').update(blogId).digest('hex');
        data.theme           = theme ? theme.value : '';
        data.apps            = apps || '';
        data.post_count      = posts && posts.meta && posts.meta.pagination ? posts.meta.pagination.total : 0;
        data.user_count      = users && users.users && users.users.length ? users.users.length : 0;
        data.blog_created_at = users && users.users && users.users[0] && users.users[0].created_at ? moment(users.users[0].created_at).unix() : '';
        data.npm_version     = _.isArray(npm) && npm[0] ? npm[0].toString().replace(/\n/, '') : '';

        return data;
    }).catch(updateCheckError);
}

function updateCheckRequest() {
    return updateCheckData().then(function (reqData) {
        var resData = '',
            headers,
            req;

        reqData = JSON.stringify(reqData);

        headers = {
            'Content-Length': reqData.length
        };

        return new Promise(function (resolve, reject) {
            req = https.request({
                hostname: checkEndpoint,
                method: 'POST',
                headers: headers
            }, function (res) {
                res.on('error', function (error) { reject(error); });
                res.on('data', function (chunk) { resData += chunk; });
                res.on('end', function () {
                    try {
                        resData = JSON.parse(resData);
                        resolve(resData);
                    } catch (e) {
                        reject('Unable to decode update response');
                    }
                });
            });

            req.on('socket', function (socket) {
                // Wait a maximum of 10seconds
                socket.setTimeout(10000);
                socket.on('timeout', function () {
                    req.abort();
                });
            });

            req.on('error', function (error) {
                reject(error);
            });

            req.write(reqData);
            req.end();
        });
    });
}

// ## Update Check Response
// Handles the response from the update check
// Does two things with the information received:
// 1. Updates the time we can next make a check
// 2. Checks if the version in the response is new, and updates the notification setting
function updateCheckResponse(response) {
    var ops = [];

    ops.push(
        api.settings.edit(
            {settings: [{key: 'nextUpdateCheck', value: response.next_check}]},
            internal
        ).catch(errors.rejectError),
        api.settings.edit(
            {settings: [{key: 'displayUpdateNotification', value: response.version}]},
            internal
        ).catch(errors.rejectError)
    );

    return Promise.settle(ops).then(function (descriptors) {
        descriptors.forEach(function (d) {
            if (d.isRejected()) {
                errors.rejectError(d.reason());
            }
        });
    });
}

function updateCheck() {
    // The check will not happen if:
    // 1. updateCheck is defined as false in config.js
    // 2. we've already done a check this session
    // 3. we're not in production or development mode
    // TODO: need to remove config.updateCheck in favor of config.privacy.updateCheck in future version (it is now deprecated)
    if (config.updateCheck === false || config.isPrivacyDisabled('useUpdateCheck') || _.indexOf(allowedCheckEnvironments, process.env.NODE_ENV) === -1) {
        // No update check
        return Promise.resolve();
    } else {
        return api.settings.read(_.extend(internal, {key: 'nextUpdateCheck'})).then(function (result) {
            var nextUpdateCheck = result.settings[0];

            if (nextUpdateCheck && nextUpdateCheck.value && nextUpdateCheck.value > moment().unix()) {
                // It's not time to check yet
                return;
            } else {
                // We need to do a check
                return updateCheckRequest()
                    .then(updateCheckResponse)
                    .catch(updateCheckError);
            }
        }).catch(updateCheckError);
    }
}

function showUpdateNotification() {
    return api.settings.read(_.extend(internal, {key: 'displayUpdateNotification'})).then(function (response) {
        var display = response.settings[0];

        // Version 0.4 used boolean to indicate the need for an update. This special case is
        // translated to the version string.
        // TODO: remove in future version.
        if (display.value === 'false' || display.value === 'true' || display.value === '1' || display.value === '0') {
            display.value = '0.4.0';
        }

        if (display && display.value && currentVersion && semver.gt(display.value, currentVersion)) {
            return display.value;
        }

        return false;
    });
}

module.exports = updateCheck;
module.exports.showUpdateNotification = showUpdateNotification;
<|endoftext|>


<commit_before>console.log('worker:media')

import Bluebird from 'bluebird'
import fs from 'fs'
import path from 'path'
import mime from 'mime'

import config from 'infrastructure/config'
import queue from 'infrastructure/kue'
import {
  getImageSize,
  generatePreview,
  optimizeImage
} from 'services/image'
import {
  createOnlineDir,
  upload
} from 'services/s3'
import {
  create as createMedia,
  getMaxAlias
} from 'services/media'

queue.process('media', (job, done) => {
  const contentType = mime.lookup(job.data.path)
  const basename = path.basename(job.data.path)
  const outPath = path.join(config.uploadDir, '.optimized', basename)
  const onlineDir = createOnlineDir()

  const promises = [
    getImageSize(job.data.path),
    generatePreview(job.data.path),
    upload(`${onlineDir}/${job.data.name}`, job.data.path, {
      contentType: contentType,
      expire: '1m'
    }),
    optimizeImage(job.data.path, outPath).then(optimizedPath => {
      return upload(`${onlineDir}/optimized/${job.data.name}`, job.data.path, {
        contentType: contentType,
        expire: '1m'
      })
    }),
    getMaxAlias()
  ]

  Bluebird.all(promises)
    .spread((size, preview, origin, path, maxAlias) => {
      return createMedia({
        ...size,
        preview,
        origin,
        path,
        storage: 'cloud',
        alias: maxAlias + 1
      })
    }).finally(() => done())
    .catch(err => console.log(err))
})
<commit_msg>delete files after upload<commit_after>console.log('worker:media')

import Bluebird from 'bluebird'
import fs from 'fs'
import path from 'path'
import mime from 'mime'

import config from 'infrastructure/config'
import queue from 'infrastructure/kue'
import {
  getImageSize,
  generatePreview,
  optimizeImage
} from 'services/image'
import {
  createOnlineDir,
  upload
} from 'services/s3'
import {
  create as createMedia,
  getMaxAlias
} from 'services/media'

queue.process('media', (job, done) => {
  const contentType = mime.lookup(job.data.path)
  const basename = path.basename(job.data.path)
  const outPath = path.join(config.uploadDir, '.optimized', basename)
  const onlineDir = createOnlineDir()

  const promises = [
    getImageSize(job.data.path),
    generatePreview(job.data.path),
    upload(`${onlineDir}/${job.data.name}`, job.data.path, {
      contentType: contentType,
      expire: '1m'
    }).finally(() => {
      fs.unlinkSync(job.data.path)
    }),
    optimizeImage(job.data.path, outPath).then(optimizedPath => {
      return upload(`${onlineDir}/optimized/${job.data.name}`, optimizedPath, {
        contentType: contentType,
        expire: '1m'
      })
    }).finally(() => {
      fs.unlinkSync(outPath)
    }),
    getMaxAlias()
  ]

  Bluebird.all(promises)
    .spread((size, preview, origin, path, maxAlias) => {
      return createMedia({
        ...size,
        preview,
        origin,
        path,
        storage: 'cloud',
        alias: maxAlias + 1
      })
    }).finally(() => done())
    .catch(err => console.log(err))
})
<|endoftext|>


<commit_before>if ( window.addEventListener ) {
	window.addEventListener('error', function(e) {
		if ( e.lineno != 0 ) {
			darkSoulsErrorHandler();
		}
	});
} else {
	window.attachEvent('onerror', function(e) {
		if ( e.lineno != 0 ) {
			darkSoulsErrorHandler();
		}
	});
}

function darkSoulsErrorHandler(){
	//Do something dastardly here.
	alert("You Died");
}
<commit_msg>Deleted JS script for now.<commit_after><|endoftext|>


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

    angular.module('chaise.dataEntry', [
        'ERMrest',
        'ngSanitize',
        'chaise.utils',
        'chaise.navbar',
        'chaise.errors',
        'chaise.alerts',
        'chaise.filters',
        'chaise.interceptors',
        'chaise.validators',
        'ui.select',
        'rzModule',
        '720kb.datepicker',
        'ngMessages'
    ])

    // Configure the context info from the URI
    .config(['context', '$httpProvider', function configureContext(context, $httpProvider) {
        $httpProvider.interceptors.push('Interceptors');

        if (chaiseConfig.headTitle !== undefined) {
            document.getElementsByTagName('head')[0].getElementsByTagName('title')[0].innerHTML = chaiseConfig.headTitle;
        }

        // Parse the url
        context.serviceURL = window.location.origin + '/ermrest';
        if (chaiseConfig.ermrestLocation) {
            context.serviceURL = chaiseConfig.ermrestLocation + '/ermrest';
        }

        var hash = window.location.hash;

        if (hash === undefined || hash == '' || hash.length == 1) {
            return;
        }

        var parts = hash.substring(1).split('/');
        context.catalogID = parts[0];
        if (parts[1]) {
            var params = parts[1].split(':');
            if (params.length > 1) {
                context.schemaName = decodeURIComponent(params[0]);
                context.tableName = decodeURIComponent(params[1]);
            } else {
                context.tableName = decodeURIComponent(params[0]);
            }
        }

        // If there are filters appended to the URL, add them to context.js
        if (parts[2]) {
            context.filters = {};
            var filters = parts[2].split('&');
            for (var i = 0, len = filters.length; i < len; i++) {
                var filter = filters[i].split('=');
                if (filter[0] && filter[1]) {
                    context.filters[decodeURIComponent(filter[0])] = decodeURIComponent(filter[1]);
                }
            }
        }
        console.log('Context:',context);
    }])

    .run(['context', 'ermrestServerFactory', 'dataEntryModel', 'AlertsService', 'ErrorService', '$log', function runApp(context, ermrestServerFactory, dataEntryModel, AlertsService, ErrorService, $log) {
        try {
            var server = context.server = ermrestServerFactory.getServer(context.serviceURL);
        } catch (exception) {
            // The domain is typed incorrectly or does not exist ....?
            $log.info(exception);
        }
        server.catalogs.get(context.catalogID).then(function success(catalog) {
            try {
                var schema = catalog.schemas.get(context.schemaName);
                try {
                    var table = schema.tables.get(context.tableName);

                    console.log('Table:', table);
                    dataEntryModel.table = table;

                    // generic try/catch
                    try {
                        var foreignKeys = table.foreignKeys.all();
                        angular.forEach(foreignKeys, function(fkey) {
                            // simple implies one column
                            if (fkey.simple) {
                                var ftable = fkey.key.table;
                                var keyColumn = fkey.key.colset.columns[0];

                                /* FIRST USE CASE: covered by default; display = key column */

                                var pattern = "{" + keyColumn.name + "}";
                                var displayColumns = [keyColumn];

                                /* SECOND USE CASE: conditional if the table is tagged as a vocabulary */

                                try {
                                    try {
                                        var vocabAnnotation = ftable.annotations.get("tag:misd.isi.edu,2015:vocabulary");
                                    // An error being caught means the `vocabulary` annotation is not defined and that's okay
                                    } catch (exception) { }

                                    try {
                                        var displayAnnotation = ftable.annotations.get("tag:misd.isi.edu,2015:display");
                                    // An error being caught means the `display` annotation is not defined and that's okay
                                    } catch (exception) { }

                                    if (vocabAnnotation) {
                                        if (vocabAnnotation.content.term) {
                                            var termColumn = ftable.columns.get(vocabAnnotation.content.term);
                                            displayColumns.push(termColumn); // the array is now [keyColumn, termColumn]
                                        }
                                        // vocabulary term is undefined
                                        else {
                                            try {
                                                var ftableColumns = ftable.columns.all();
                                                for (var i = 0, length = ftableColumns.length; i < length; i++) {
                                                    var uppColumnName = ftableColumns[i].name.toUpperCase();
                                                    if (uppColumnName == 'TERM' || uppColumnName == 'NAME') {
                                                        displayColumns.push(ftableColumns[i]);
                                                        break;
                                                    }
                                                } /* term undefined */
                                            } catch (exception) {
                                                // ftable.columns.all() should not fail
                                                $log.info(exception);
                                            }
                                        }
                                        if (displayColumns.length > 1) {
                                            pattern = "{" + displayColumns[1].name + "}";
                                        }
                                        /* END USE CASE 2 */
                                    }
                                    /* THIRD USE CASE: not a vocabulary but it has a “display : row name” annotation */
                                    /* Git issue #358 */
                                    else if (displayAnnotation) {
                                        if (displayAnnotation.content.row_name) {
                                            // TODO
                                            // var array_of_col_names = REGEX THE array of column_name strings from “ … `{` column_name `}` …” patterns
                                            // angular.forEach(array_of_col_names, function(column_name) {
                                            //     displayColumns.push(table.columns.get(column_name));
                                            // });
                                            //
                                            // pattern = displayAnnotation.row_name;
                                        }
                                    }
                                } finally {
                                    (function(fkey) {
                                        ftable.entity.get(null, null, displayColumns).then(function success(rowset) {
                                            var domainValues = dataEntryModel.domainValues[fkey.colset.columns[0].name] = [];
                                            var displayColumnName = (displayColumns[1] ? displayColumns[1].name : keyColumn.name);

                                            angular.forEach(rowset.data, function(column) {
                                                domainValues.push( {key: column[keyColumn.name], display: column[displayColumnName]/*Util.patternExpansion( pattern, column.data )*/} );
                                            });
                                        }, function error(response) {
                                            // shouldn't error out
                                            $log.info(response);
                                        });
                                    })(fkey);
                                }
                            }
                        });
                    } catch (exception) { // catches table.foreignKays.all()
                        // this shouldn't error out
                        $log.info(exception);
                    }

                    // If there are filters, populate the model with existing records' column values
                    if (context.filters) {
                        var path = new ERMrest.DataPath(table);
                        var filters = [];
                        angular.forEach(context.filters, function(value, key) {
                            try {
                                var column = path.context.columns.get(key);
                                filters.push(new ERMrest.BinaryPredicate(column, ERMrest.OPERATOR.EQUAL, value));
                            } catch (exception) {
                                // handle error
                            }
                        });
                        // TODO: Store filters in URI form in model to use later on form submission
                        var filterString = new ERMrest.Conjunction(filters);
                        // dataEntryModel.filterUri = filterString.toUri();

                        var path = path.filter(filterString);
                        path.entity.get().then(function success(entity) {
                            if (entity.length === 0) {
                                AlertsService.addAlert({type: 'error', message: 'Sorry, the requested record was not found. Please check the URL and refresh the page.' });
                                console.log('The requested record in schema ' + context.schemaName + ', table ' + context.tableName + ' with the following attributes: ' + context.filters + ' was not found.');
                            }

                            angular.forEach(entity[0], function(value, colName) {
                                try {
                                    var pathColumnType = path.context.columns.get(colName).column.type.name;
                                    if (pathColumnType == 'date' || pathColumnType == 'timestamptz') {
                                        // Must transform the value into a Date so that
                                        // Angular won't complain when putting the value
                                        // in an input of type "date" in the view
                                        value = new Date(value);
                                    }
                                } catch (exception) {
                                    // should not error out
                                }
                                dataEntryModel.rows[dataEntryModel.rows.length - 1][colName] = value;
                            });
                        });
                    }
                    console.log('Model:',dataEntryModel);

                } catch (exception) { // catches schema.tables.get(table name)
                    console.log(exception);
                    if (exception instanceof Errors.NotFoundError) {
                        ErrorService.tableNotFound(context.tableName, exception);
                    }
                }
            } catch (exception) { // catches catalog.schemas.get(schema name)
                if (exception instanceof Errors.NotFoundError) {
                    ErrorService.schemaNotFound(context.schemaName, exception);
                }
            }
        }, function error(response) { // error promise for server.catalogs.get()
            console.log("Go auth spot:", response);
            // TODO verify this is handled via an interceptor by the function in the ErrorService
            // If the interceptor handles this, do nothing here
            // 401 should not be caught here.
            if (response.code == 401) {
                UriUtils.getGoauth(UriUtils.fixedEncodeURIComponent(window.location.href));
                $log.info(response);
            }

            // Not sure why this is getting an error promise instead of being caught by the try/catch
            if (response.code == 404) {
                ErrorService.catalogNotFound(context.catalogID, response);
            }
        });
    }]);

    // Refresh the page when the window's hash changes. Needed because Angular
    // normally doesn't refresh page when hash changes.
    window.onhashchange = function() {
        if (window.location.hash != '#undefined') {
            location.reload();
        } else {
            history.replaceState("", document.title, window.location.pathname);
            location.reload();
        }
        function goBack() {
            window.location.hash = window.location.lasthash[window.location.lasthash.length-1];
            window.location.lasthash.pop();
        }
    }
})();
<commit_msg>generic try/catch added and removed some uneccessary ones. Found out try catches break if code is run after a digest cycle and then throws an exception.<commit_after>(function() {
    'use strict';

    angular.module('chaise.dataEntry', [
        'ERMrest',
        'ngSanitize',
        'chaise.utils',
        'chaise.navbar',
        'chaise.errors',
        'chaise.alerts',
        'chaise.filters',
        'chaise.interceptors',
        'chaise.validators',
        'ui.select',
        'rzModule',
        '720kb.datepicker',
        'ngMessages'
    ])

    // Configure the context info from the URI
    .config(['context', '$httpProvider', function configureContext(context, $httpProvider) {
        $httpProvider.interceptors.push('Interceptors');

        if (chaiseConfig.headTitle !== undefined) {
            document.getElementsByTagName('head')[0].getElementsByTagName('title')[0].innerHTML = chaiseConfig.headTitle;
        }

        // Parse the url
        context.serviceURL = window.location.origin + '/ermrest';
        if (chaiseConfig.ermrestLocation) {
            context.serviceURL = chaiseConfig.ermrestLocation + '/ermrest';
        }

        var hash = window.location.hash;

        if (hash === undefined || hash == '' || hash.length == 1) {
            return;
        }

        var parts = hash.substring(1).split('/');
        context.catalogID = parts[0];
        if (parts[1]) {
            var params = parts[1].split(':');
            if (params.length > 1) {
                context.schemaName = decodeURIComponent(params[0]);
                context.tableName = decodeURIComponent(params[1]);
            } else {
                context.tableName = decodeURIComponent(params[0]);
            }
        }

        // If there are filters appended to the URL, add them to context.js
        if (parts[2]) {
            context.filters = {};
            var filters = parts[2].split('&');
            for (var i = 0, len = filters.length; i < len; i++) {
                var filter = filters[i].split('=');
                if (filter[0] && filter[1]) {
                    context.filters[decodeURIComponent(filter[0])] = decodeURIComponent(filter[1]);
                }
            }
        }
        console.log('Context:',context);
    }])

    .run(['context', 'ermrestServerFactory', 'dataEntryModel', 'AlertsService', 'ErrorService', '$log', function runApp(context, ermrestServerFactory, dataEntryModel, AlertsService, ErrorService, $log) {
        // generic try/catch
        try {
            var server = context.server = ermrestServerFactory.getServer(context.serviceURL); // caught by generic exception case
            server.catalogs.get(context.catalogID).then(function success(catalog) {
                var schema = catalog.schemas.get(context.schemaName); // caught by generic exception case
                var table = schema.tables.get(context.tableName); // caught by generic exception case

                console.log('Table:', table);
                dataEntryModel.table = table;

                var foreignKeys = table.foreignKeys.all(); // caught by generic exception case
                angular.forEach(foreignKeys, function(fkey) {
                    // simple implies one column
                    if (fkey.simple) {
                        var ftable = fkey.key.table;
                        var keyColumn = fkey.key.colset.columns[0];

                        /* FIRST USE CASE: covered by default; display = key column */

                        var pattern = "{" + keyColumn.name + "}";
                        var displayColumns = [keyColumn];

                        /* SECOND USE CASE: conditional if the table is tagged as a vocabulary */

                        try {

                            try {
                                var vocabAnnotation = ftable.annotations.get("tag:misd.isi.edu,2015:vocabulary");
                                // An error being caught means the `vocabulary` annotation is not defined and that's okay
                            } catch (exception) { }

                            try {
                                var displayAnnotation = ftable.annotations.get("tag:misd.isi.edu,2015:display");
                                // An error being caught means the `display` annotation is not defined and that's okay
                            } catch (exception) { }

                            if (vocabAnnotation) {
                                if (vocabAnnotation.content.term) {
                                    var termColumn = ftable.columns.get(vocabAnnotation.content.term); // caught by generic exception case
                                    displayColumns.push(termColumn); // the array is now [keyColumn, termColumn]
                                }
                                // vocabulary term is undefined
                                else {
                                    var ftableColumns = ftable.columns.all(); // caught by generic exception case
                                    for (var i = 0, length = ftableColumns.length; i < length; i++) {
                                        var uppColumnName = ftableColumns[i].name.toUpperCase();
                                        if (uppColumnName == 'TERM' || uppColumnName == 'NAME') {
                                            displayColumns.push(ftableColumns[i]);
                                            break;
                                        }
                                    } /* term undefined */
                                }
                                if (displayColumns.length > 1) {
                                    pattern = "{" + displayColumns[1].name + "}";
                                }
                                /* END USE CASE 2 */
                            }
                            /* THIRD USE CASE: not a vocabulary but it has a “display : row name” annotation */
                            /* Git issue #358 */
                            else if (displayAnnotation) {
                                if (displayAnnotation.content.row_name) {
                                    // TODO
                                    // var array_of_col_names = REGEX THE array of column_name strings from “ … `{` column_name `}` …” patterns
                                    // angular.forEach(array_of_col_names, function(column_name) {
                                    //     displayColumns.push(table.columns.get(column_name));
                                    // });
                                    //
                                    // pattern = displayAnnotation.row_name;
                                }
                            }
                        } finally {
                            (function(fkey) {
                                ftable.entity.get(null, null, displayColumns).then(function success(rowset) {
                                    var domainValues = dataEntryModel.domainValues[fkey.colset.columns[0].name] = [];
                                    var displayColumnName = (displayColumns[1] ? displayColumns[1].name : keyColumn.name);

                                    angular.forEach(rowset.data, function(column) {
                                        domainValues.push( {key: column[keyColumn.name], display: column[displayColumnName]/*Util.patternExpansion( pattern, column.data )*/} );
                                    });
                                }, function error(response) {
                                    // shouldn't error out
                                    $log.info(response);
                                });
                            })(fkey);
                        }
                    }
                });

                // If there are filters, populate the model with existing records' column values
                if (context.filters) {
                    var path = new ERMrest.DataPath(table);
                    var filters = [];
                    angular.forEach(context.filters, function(value, key) {
                        var column = path.context.columns.get(key); // caught by generic exception case
                        filters.push(new ERMrest.BinaryPredicate(column, ERMrest.OPERATOR.EQUAL, value));
                    });
                    // TODO: Store filters in URI form in model to use later on form submission
                    var filterString = new ERMrest.Conjunction(filters);
                    // dataEntryModel.filterUri = filterString.toUri();

                    var path = path.filter(filterString);
                    path.entity.get().then(function success(entity) {
                        if (entity.length === 0) {
                            AlertsService.addAlert({type: 'error', message: 'Sorry, the requested record was not found. Please check the URL and refresh the page.' });
                            console.log('The requested record in schema ' + context.schemaName + ', table ' + context.tableName + ' with the following attributes: ' + context.filters + ' was not found.');
                        }

                        angular.forEach(entity[0], function(value, colName) {
                            var pathColumnType = path.context.columns.get(colName).column.type.name; // caught by generic exception case
                            if (pathColumnType == 'date' || pathColumnType == 'timestamptz') {
                                // Must transform the value into a Date so that
                                // Angular won't complain when putting the value
                                // in an input of type "date" in the view
                                value = new Date(value);
                            }
                            dataEntryModel.rows[dataEntryModel.rows.length - 1][colName] = value;
                        });
                    });
                }
                console.log('Model:',dataEntryModel);

            }, function error(response) { // error promise for server.catalogs.get()
                console.log("Go auth spot:", response);
                // TODO verify this is handled via an interceptor by the function in the ErrorService
                // If the interceptor handles this, do nothing here
                // 401 should not be caught here.
                if (response.code == 401) {
                    UriUtils.getGoauth(UriUtils.fixedEncodeURIComponent(window.location.href));
                    $log.info(response);
                }

                // Not sure why this is getting an error promise instead of being caught by the try/catch
                if (response.code == 404) {
                    ErrorService.catalogNotFound(context.catalogID, response);
                }
            });
        } catch (exception) {
            // TODO: implement hierarchies of exceptions in ermrestJS and use that hierarchy to conditionally check for certain exceptions
            // handle generic catch

            // if (exception instanceof Errors.TableNotFoundError) {
            //     ErrorService.tableNotFound(context.tableName);
            // } else if (exception instanceof Errors.SchemaNotFoundError) {
            //     ErrorService.schemaNotFound(context.schemaName);
            // } else if (exception instanceof Errors.ServerNotFoundError) {
            //     ErrorService.serverNotFound(context.serviceURL);
            // }
            AlertsService.addAlert({type: 'error', message: exception.message});
            $log.info(exception);
        }
    }]);

    // Refresh the page when the window's hash changes. Needed because Angular
    // normally doesn't refresh page when hash changes.
    window.onhashchange = function() {
        if (window.location.hash != '#undefined') {
            location.reload();
        } else {
            history.replaceState("", document.title, window.location.pathname);
            location.reload();
        }
        function goBack() {
            window.location.hash = window.location.lasthash[window.location.lasthash.length-1];
            window.location.lasthash.pop();
        }
    }
})();
<|endoftext|>


<commit_before>/* Copyright (c) 2015-2016 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */

/* global define, Handlebars, isNode */
define(function(require, exports, module) {
  'use strict';
  console.log('Loading audiorecorder.ui.js ...');
  var TSCORE = require('tscore');
  require("webaudiorecording");
  var fileContent;
  var fileType;

  var initUI = function() {

    $('#audioRecordingConfirmButton').click(function() {
      saveRecording();
    });

  };

  function saveAudioVideoFile(blob) {
    console.debug(blob);
    var fileTags = '';
    var rawTags = $('#newFileNameTagsAudioRecorder').val().split(',');
    rawTags.forEach(function(value, index) {
      if (index === 0) {
        fileTags = value;
      } else {
        fileTags = fileTags + TSCORE.Config.getTagDelimiter() + value;
      }
    });
    //if ($('#tagWithCurrentDate').prop('checked')) {
    //  if (fileTags.length < 1) {
    //    fileTags = TSCORE.TagUtils.formatDateTime4Tag(new Date());
    //  } else {
    //    fileTags = fileTags + TSCORE.Config.getTagDelimiter() + TSCORE.TagUtils.formatDateTime4Tag(new Date());
    //  }
    //}
    if (fileTags.length > 0) {
      fileTags = TSCORE.TagUtils.beginTagContainer + fileTags + TSCORE.TagUtils.endTagContainer;
    }

    var filePath = TSCORE.currentPath + TSCORE.dirSeparator + $('#newFileNameAudioRecorder').val() + fileTags + '.' + fileType;
    TSCORE.IO.saveBinaryFilePromise(filePath, blob).then(function() {
      TSCORE.showSuccessDialog("File saved successfully.");

    }, function(error) {
      TSCORE.hideLoadingAnimation();
      TSCORE.showAlertDialog("Saving " + filePath + " failed.");
      console.error("Save to file " + filePath + " failed " + error);
    });
  }

  // Navigator.getUserMedia shim
  navigator.getUserMedia =
          navigator.getUserMedia ||
          navigator.webkitGetUserMedia ||
          navigator.mozGetUserMedia ||
          navigator.msGetUserMedia;

  // URL shim
  window.URL = window.URL || window.webkitURL;

  // audio context + .createScriptProcessor shim
  var audioContext = new AudioContext;
  if (audioContext.createScriptProcessor == null) {
    audioContext.createScriptProcessor = audioContext.createJavaScriptNode;
  }

  // Elements (jQuery objects)
  var $testToneLevel = $('#testToneLevel'),
          $microphone = $('#microphone'),
          $microphoneLevel = $('#microphoneLevel'),
  //$timeLimit = $('#time-limit'),
          $encoding = $('input[name="encoding"]'),
          $encodingOption = $('#encoding-option'),
  //$encodingProcess = $('input[name="encoding-process"]'),
  //$reportInterval = $('#report-interval'),
  //$bufferSize = $('#buffer-size'),
          $recording = $('#recording'),
          $timeDisplay = $('#time-display'),
          $record = $('#record'),
          $cancel = $('#cancel'),
          $dateTime = $('#date-time'),
          $recordingList = $('#recordingList'),
          $modalLoading = $('#modal-loading'),
          $modalProgress = $('#modal-progress'),
          $modalError = $('#modal-error');

  // Initialize input element states (required for reloading page on Firefox)
  $testToneLevel.attr('disabled', false);
  $testToneLevel[0].valueAsNumber = 0;
  $microphone.attr('disabled', false);
  $microphone[0].checked = false;
  $microphoneLevel.attr('disabled', false);
  $microphoneLevel[0].valueAsNumber = 0;
//  $timeLimit.attr('disabled', false);
//  $timeLimit[0].valueAsNumber = 3;
  $encoding.attr('disabled', false);
  $encoding[0].checked = true;
  //$encodingProcess.attr('disabled', false);
  //$encodingProcess[0].checked = true;
  //$reportInterval.attr('disabled', false);
  //$reportInterval[0].valueAsNumber = 1;
  //$bufferSize.attr('disabled', false);

  var testTone = (function() {
    var osc = audioContext.createOscillator(),
            lfo = audioContext.createOscillator(),
            ampMod = audioContext.createGain(),
            output = audioContext.createGain();
    lfo.type = 'square';
    lfo.frequency.value = 2;
    osc.connect(ampMod);
    lfo.connect(ampMod.gain);
    output.gain.value = 0.5;
    ampMod.connect(output);
    osc.start();
    lfo.start();
    return output;
  })();

  var testToneLevel = audioContext.createGain(),
          microphone = undefined,     // obtained by user click
          microphoneLevel = audioContext.createGain(),
          mixer = audioContext.createGain();
  testTone.connect(testToneLevel);
  testToneLevel.gain.value = 0;
  testToneLevel.connect(mixer);
  microphoneLevel.gain.value = 0;
  microphoneLevel.connect(mixer);
  mixer.connect(audioContext.destination);

  // Audio recorder object
  var audioRecorder = new WebAudioRecorder(mixer, {
    workerDir: 'libs/audio-record/',
    onEncoderLoading: function(recorder, encoding) {
      $modalLoading.find('.modal-title').html("Loading " + encoding.toUpperCase() + " encoder ...");
      $modalLoading.modal('show');
    },
    onEncoderLoaded: function() {
      $modalLoading.modal('hide');
    }
  });

  // Mixer levels
  $testToneLevel.on('input', function() {
    var level = $testToneLevel[0].valueAsNumber / 100;
    testToneLevel.gain.value = level * level;
  });

  $microphoneLevel.on('input', function() {
    var level = $microphoneLevel[0].valueAsNumber / 100;
    microphoneLevel.gain.value = level * level;
  });

  // Obtaining microphone input
  $microphone.click(function() {
    if (microphone == null)
      navigator.getUserMedia({audio: true},
              function(stream) {
                microphone = audioContext.createMediaStreamSource(stream);
                microphone.connect(microphoneLevel);
                $microphone.attr('disabled', true);
                $microphoneLevel.removeClass('hidden');
              },
              function(error) {
                $microphone[0].checked = false;
                audioRecorder.onError(audioRecorder, "Could not get audio input.");
              });
  });

  // Recording time limit
  function plural(n) {
    return n > 1 ? "s" : "";
  }

  /*$timeLimit.on('input', function() {
   var min = $timeLimit[0].valueAsNumber;
   $('#time-limit-text').html("" + min + " minute" + plural(min));
   });*/

  // Encoding selector + encoding options
  var OGG_QUALITY = [-0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1],
          OGG_KBPS = [45, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 500],
          MP3_BIT_RATE = [64, 80, 96, 112, 128, 160, 192, 224, 256, 320],
          ENCODING_OPTION = {
            wav: {
              label: '',
              hidden: true,
              max: 1,
              text: function(val) {
                return '';
              }
            },
            ogg: {
              label: 'Quality',
              hidden: false,
              max: OGG_QUALITY.length - 1,
              text: function(val) {
                return OGG_QUALITY[val].toFixed(1) +
                        " (~" + OGG_KBPS[val] + "kbps)";
              }
            },
            mp3: {
              label: 'Bit rate',
              hidden: false,
              max: MP3_BIT_RATE.length - 1,
              text: function(val) {
                return "" + MP3_BIT_RATE[val] + "kbps";
              }
            }
          },
          optionValue = {
            wav: null,
            ogg: 6,
            mp3: 5
          };

  $encoding.click(function(event) {
    var encoding = $(event.target).attr('encoding'),
            option = ENCODING_OPTION[encoding];
    audioRecorder.setEncoding(encoding);
    $('#encoding-option-label').html(option.label);
    $('#encoding-option-text').html(option.text(optionValue[encoding]));
    $encodingOption.toggleClass('hidden', option.hidden).attr('max', option.max);
    $encodingOption[0].valueAsNumber = optionValue[encoding];
  });

//  $encodingOption.on('input', function() {
//    var encoding = audioRecorder.encoding,
//            option = ENCODING_OPTION[encoding];
//    optionValue[encoding] = $encodingOption[0].value;
//    $('#encoding-option-text').html(option.text(optionValue[encoding]));
//  });
//
//// encoding process selector
//  var encodingProcess = 'background';
//
//  $encodingProcess.click(function(event) {
//    encodingProcess = $(event.target).attr('mode');
//    var hidden = encodingProcess === 'background';
//    $('#report-interval-label').toggleClass('hidden', hidden);
//    //$reportInterval.toggleClass('hidden', hidden);
//    $('#report-interval-text').toggleClass('hidden', hidden);
//  });

  /*$reportInterval.on('input', function() {
   var sec = $reportInterval[0].valueAsNumber;
   $('#report-interval-text').html("" + sec + " second" + (plural(sec)));
   });*/

  // Processor buffer size
  var BUFFER_SIZE = [256, 512, 1024, 2048, 4096, 8192, 16384];

  var defaultBufSz = (function() {
    var processor = audioContext.createScriptProcessor(undefined, 2, 2);
    return processor.bufferSize;
  })();

  var iDefBufSz = BUFFER_SIZE.indexOf(defaultBufSz);

  //$bufferSize[0].valueAsNumber = iDefBufSz;   // initialize with browser default

  function updateBufferSizeText() {
    //var iBufSz = $bufferSize[0].valueAsNumber, text = "" + BUFFER_SIZE[iBufSz];
    var iBufSz = iDefBufSz;
    var text = "" + BUFFER_SIZE[iBufSz];
    if (iBufSz === iDefBufSz)
      text += ' (browser default)';
    $('#buffer-size-text').html(text);
  }

  updateBufferSizeText();         // initialize text

  /*$bufferSize.on('input', function() {
   updateBufferSizeText();
   });*/

  // Save/Delete recording
  function saveRecording(blob, encoding) {
    var time = new Date();
    var url = URL.createObjectURL(blob);
    //var html = "
"+
    //        "<audio controls src='" + url + "'></audio> " +//" ("+encoding.toUpperCase()+")"+time
    //        " Save " +
    //        "<button class='btn btn-danger' style='margin-top:-15px' recording='" + url + "'>Delete</button>"+"
";
    //
    //if ($recordingList.empty()) {
    //  $recordingList.append($(html));
    //} else {
    //  $recordingList.removeAttribute(html);
    //}

    $('#recordingUrl').prop('recording', url);
    $('#formFileCreateAudioRecorder').prop('recording', url);
    $('#audioRecordingUrl').attr('src', url);
    $('#deleteAudioRecording').prop('recording', url);

    //fileContent = TSCORE.Config.getNewTextFileContent();
    // Default new file in text file
    fileType = 'wav' || 'ogg';
    $('#newFileNameTagsAudioRecorder').select2('data', null);
    $('#newFileNameTagsAudioRecorder').select2({
      multiple: true,
      tags: TSCORE.Config.getAllTags(),
      tokenSeparators: [
        ',',
        ' '
      ],
      minimumInputLength: 1,
      selectOnBlur: true
    });
    $('#newFileNameAudioRecorder').val('');
    //$('#tagWithCurrentDate').prop('checked', false);
    $('#txtFileTypeButtonAudioRecorder').button('toggle');
    $('#formFileCreateAudioRecorder').validator();
    $('#formFileCreateAudioRecorder').submit(function(e) {
      e.preventDefault();
    });
    $('#formFileCreateAudioRecorder').on('invalid.bs.validator', function() {
      $('#audioRecordingConfirmButton').prop('disabled', true);
    });
    $('#formFileCreateAudioRecorder').on('valid.bs.validator', function() {
      $('#audioRecordingConfirmButton').prop('disabled', false);
    });
    $('#audioRecordingDialog').on('shown.bs.modal', function() {
      $('#newFileNameAudioRecorder').select2().focus();
    });
    console.debug(blob);
    var fileTags = '';
    var rawTags = $('#newFileNameTagsAudioRecorder').val().split(',');
    rawTags.forEach(function(value, index) {
      if (index === 0) {
        fileTags = value;
      } else {
        fileTags = fileTags + TSCORE.Config.getTagDelimiter() + value;
      }
    });
    //if ($('#tagWithCurrentDate').prop('checked')) {
    //  if (fileTags.length < 1) {
    //    fileTags = TSCORE.TagUtils.formatDateTime4Tag(new Date());
    //  } else {
    //    fileTags = fileTags + TSCORE.Config.getTagDelimiter() + TSCORE.TagUtils.formatDateTime4Tag(new Date());
    //  }
    //}
    if (fileTags.length > 0) {
      fileTags = TSCORE.TagUtils.beginTagContainer + fileTags + TSCORE.TagUtils.endTagContainer;
    }

    var filePath = TSCORE.currentPath + TSCORE.dirSeparator + $('#newFileNameAudioRecorder').val() + fileTags + '.' + fileType;
    TSCORE.IO.saveBinaryFilePromise(filePath, blob).then(function() {
      TSCORE.showSuccessDialog("File saved successfully.");

    }, function(error) {
      TSCORE.hideLoadingAnimation();
      TSCORE.showAlertDialog("Saving " + filePath + " failed.");
      console.error("Save to file " + filePath + " failed " + error);
    });
  }

  $recordingList.on('click', 'button', function(event) {
    var url = $(event.target).attr('recording');
    $("p[recording='" + url + "']").remove();
    URL.revokeObjectURL(url);
  });

  // Time indicator
  function minSecStr(n) {
    return (n < 10 ? "0" : "") + n;
  }

  function updateDateTime() {
    var sec = audioRecorder.recordingTime() | 0;
    $timeDisplay.html(minSecStr(sec / 60 | 0) + ":" + minSecStr(sec % 60));
    $dateTime.html((new Date).toString());
  }

  window.setInterval(updateDateTime, 200);

  // Encoding progress report modal
  var progressComplete = false;

  function setProgress(progress) {
    var percent = (progress * 100).toFixed(1) + "%";
    $modalProgress.find('.progress-bar').attr('style', "width: " + percent + ";");
    $modalProgress.find('.text-center').html(percent);
    progressComplete = progress === 1;
  }

  $modalProgress.on("hide.bs.modal", function() {
    if (!progressComplete)
      audioRecorder.cancelEncoding();
  });

  // record | stop | cancel buttons
  function disableControlsOnRecord(disabled) {
    if (microphone == null)
      $microphone.attr('disabled', disabled);
    //$timeLimit.attr('disabled', disabled);
    $encoding.attr('disabled', disabled);
    $encodingOption.attr('disabled', disabled);
    //$encodingProcess.attr('disabled', disabled);
    //$reportInterval.attr('disabled', disabled);
    //$bufferSize.attr('disabled', disabled);
  }

  function startRecording() {
    $recording.removeClass('hidden');
    $record.html('STOP');
    $cancel.removeClass('hidden');
    disableControlsOnRecord(true);
    audioRecorder.setOptions({
      //timeLimit: $timeLimit[0].valueAsNumber * 60,
      //encodeAfterRecord: encodingProcess === 'separate',
      //progressInterval: $reportInterval[0].valueAsNumber * 1000,
      ogg: {quality: OGG_QUALITY[optionValue.ogg]},
    });
    audioRecorder.startRecording();
    setProgress(0);
  }

  function stopRecording(finish) {
    $recording.addClass('hidden');
    $record.html('RECORD');
    $cancel.addClass('hidden');
    disableControlsOnRecord(false);
    if (finish) {
      audioRecorder.finishRecording();
      if (audioRecorder.options.encodeAfterRecord) {
        $modalProgress.find('.modal-title').html("Encoding " + audioRecorder.encoding.toUpperCase());
        $modalProgress.modal('show');
      }
    } else
      audioRecorder.cancelRecording();
  }

  $record.click(function() {
    if (audioRecorder.isRecording())
      stopRecording(true);
    else
      startRecording();
  });

  $cancel.click(function() {
    stopRecording(false);
  });

  // Event handlers
  audioRecorder.onTimeout = function(recorder) {
    stopRecording(true);
  };

  audioRecorder.onEncodingProgress = function(recorder, progress) {
    setProgress(progress);
  };

  audioRecorder.onComplete = function(recorder, blob) {
    if (recorder.options.encodeAfterRecord)
      $modalProgress.modal('hide');
    saveRecording(blob, recorder.encoding);
  };

  audioRecorder.onError = function(recorder, message) {
    $modalError.find('.alert').html(message);
    $modalError.modal('show');
  };

  // Public API definition
  exports.initUI = initUI;

});
<commit_msg>cleaning up<commit_after>/* Copyright (c) 2015-2016 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */

/* global define, Handlebars, isNode */
define(function(require, exports, module) {
  'use strict';
  console.log('Loading audiorecorder.ui.js ...');
  var TSCORE = require('tscore');
  require("webaudiorecording");
  var fileContent;
  var fileType;

  var initUI = function() {

    $('#audioRecordingConfirmButton').click(function() {
      saveAudioVideoFile();
    });

  };

  function saveAudioVideoFile() {
    var fileTags = '';
    var rawTags = $('#newFileNameTagsAudioRecorder').val().split(',');
    rawTags.forEach(function(value, index) {
      if (index === 0) {
        fileTags = value;
      } else {
        fileTags = fileTags + TSCORE.Config.getTagDelimiter() + value;
      }
    });
    if (fileTags.length > 0) {
      fileTags = TSCORE.TagUtils.beginTagContainer + fileTags + TSCORE.TagUtils.endTagContainer;
    }

    var filePath = TSCORE.currentPath + TSCORE.dirSeparator + $('#newFileNameAudioRecorder').val() + fileTags + '.' + fileType;
    TSCORE.IO.saveBinaryFilePromise(filePath, blob).then(function() {
      TSCORE.showSuccessDialog("File saved successfully.");

    }, function(error) {
      TSCORE.hideLoadingAnimation();
      TSCORE.showAlertDialog("Saving " + filePath + " failed.");
      console.error("Save to file " + filePath + " failed " + error);
    });
  }

  // Navigator.getUserMedia shim
  navigator.getUserMedia =
          navigator.getUserMedia ||
          navigator.webkitGetUserMedia ||
          navigator.mozGetUserMedia ||
          navigator.msGetUserMedia;

  // URL shim
  window.URL = window.URL || window.webkitURL;

  // audio context + .createScriptProcessor shim
  var audioContext = new AudioContext;
  if (audioContext.createScriptProcessor == null) {
    audioContext.createScriptProcessor = audioContext.createJavaScriptNode;
  }

  // Elements (jQuery objects)
  var $testToneLevel = $('#testToneLevel'),
          $microphone = $('#microphone'),
          $microphoneLevel = $('#microphoneLevel'),
  //$timeLimit = $('#time-limit'),
          $encoding = $('input[name="encoding"]'),
          $encodingOption = $('#encoding-option'),
  //$encodingProcess = $('input[name="encoding-process"]'),
  //$reportInterval = $('#report-interval'),
  //$bufferSize = $('#buffer-size'),
          $recording = $('#recording'),
          $timeDisplay = $('#time-display'),
          $record = $('#record'),
          $cancel = $('#cancel'),
          $dateTime = $('#date-time'),
          $recordingList = $('#recordingList'),
          $modalLoading = $('#modal-loading'),
          $modalProgress = $('#modal-progress'),
          $modalError = $('#modal-error');

  // Initialize input element states (required for reloading page on Firefox)
  $testToneLevel.attr('disabled', false);
  $testToneLevel[0].valueAsNumber = 0;
  $microphone.attr('disabled', false);
  $microphone[0].checked = false;
  $microphoneLevel.attr('disabled', false);
  $microphoneLevel[0].valueAsNumber = 0;
//  $timeLimit.attr('disabled', false);
//  $timeLimit[0].valueAsNumber = 3;
  $encoding.attr('disabled', false);
  $encoding[0].checked = true;
  //$encodingProcess.attr('disabled', false);
  //$encodingProcess[0].checked = true;
  //$reportInterval.attr('disabled', false);
  //$reportInterval[0].valueAsNumber = 1;
  //$bufferSize.attr('disabled', false);

  var testTone = (function() {
    var osc = audioContext.createOscillator(),
            lfo = audioContext.createOscillator(),
            ampMod = audioContext.createGain(),
            output = audioContext.createGain();
    lfo.type = 'square';
    lfo.frequency.value = 2;
    osc.connect(ampMod);
    lfo.connect(ampMod.gain);
    output.gain.value = 0.5;
    ampMod.connect(output);
    osc.start();
    lfo.start();
    return output;
  })();

  var testToneLevel = audioContext.createGain(),
          microphone = undefined,     // obtained by user click
          microphoneLevel = audioContext.createGain(),
          mixer = audioContext.createGain();
  testTone.connect(testToneLevel);
  testToneLevel.gain.value = 0;
  testToneLevel.connect(mixer);
  microphoneLevel.gain.value = 0;
  microphoneLevel.connect(mixer);
  mixer.connect(audioContext.destination);

  // Audio recorder object
  var audioRecorder = new WebAudioRecorder(mixer, {
    workerDir: 'libs/audio-record/',
    onEncoderLoading: function(recorder, encoding) {
      $modalLoading.find('.modal-title').html("Loading " + encoding.toUpperCase() + " encoder ...");
      $modalLoading.modal('show');
    },
    onEncoderLoaded: function() {
      $modalLoading.modal('hide');
    }
  });

  // Mixer levels
  $testToneLevel.on('input', function() {
    var level = $testToneLevel[0].valueAsNumber / 100;
    testToneLevel.gain.value = level * level;
  });

  $microphoneLevel.on('input', function() {
    var level = $microphoneLevel[0].valueAsNumber / 100;
    microphoneLevel.gain.value = level * level;
  });

  // Obtaining microphone input
  $microphone.click(function() {
    if (microphone == null)
      navigator.getUserMedia({audio: true},
              function(stream) {
                microphone = audioContext.createMediaStreamSource(stream);
                microphone.connect(microphoneLevel);
                $microphone.attr('disabled', true);
                $microphoneLevel.removeClass('hidden');
              },
              function(error) {
                $microphone[0].checked = false;
                audioRecorder.onError(audioRecorder, "Could not get audio input.");
              });
  });

  // Recording time limit
  function plural(n) {
    return n > 1 ? "s" : "";
  }

  /*$timeLimit.on('input', function() {
   var min = $timeLimit[0].valueAsNumber;
   $('#time-limit-text').html("" + min + " minute" + plural(min));
   });*/

  // Encoding selector + encoding options
  var OGG_QUALITY = [-0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1],
          OGG_KBPS = [45, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 500],
          MP3_BIT_RATE = [64, 80, 96, 112, 128, 160, 192, 224, 256, 320],
          ENCODING_OPTION = {
            wav: {
              label: '',
              hidden: true,
              max: 1,
              text: function(val) {
                return '';
              }
            },
            ogg: {
              label: 'Quality',
              hidden: false,
              max: OGG_QUALITY.length - 1,
              text: function(val) {
                return OGG_QUALITY[val].toFixed(1) +
                        " (~" + OGG_KBPS[val] + "kbps)";
              }
            },
          },
          optionValue = {
            wav: null,
            ogg: 6,
            mp3: 5
          };

  $encoding.click(function(event) {
    var encoding = $(event.target).attr('encoding'),
            option = ENCODING_OPTION[encoding];
    audioRecorder.setEncoding(encoding);
    $('#encoding-option-label').html(option.label);
    $('#encoding-option-text').html(option.text(optionValue[encoding]));
    $encodingOption.toggleClass('hidden', option.hidden).attr('max', option.max);
    $encodingOption[0].valueAsNumber = optionValue[encoding];
  });

//  $encodingOption.on('input', function() {
//    var encoding = audioRecorder.encoding,
//            option = ENCODING_OPTION[encoding];
//    optionValue[encoding] = $encodingOption[0].value;
//    $('#encoding-option-text').html(option.text(optionValue[encoding]));
//  });
//
//// encoding process selector
//  var encodingProcess = 'background';
//
//  $encodingProcess.click(function(event) {
//    encodingProcess = $(event.target).attr('mode');
//    var hidden = encodingProcess === 'background';
//    $('#report-interval-label').toggleClass('hidden', hidden);
//    //$reportInterval.toggleClass('hidden', hidden);
//    $('#report-interval-text').toggleClass('hidden', hidden);
//  });

  /*$reportInterval.on('input', function() {
   var sec = $reportInterval[0].valueAsNumber;
   $('#report-interval-text').html("" + sec + " second" + (plural(sec)));
   });*/

  // Processor buffer size
  var BUFFER_SIZE = [256, 512, 1024, 2048, 4096, 8192, 16384];

  var defaultBufSz = (function() {
    var processor = audioContext.createScriptProcessor(undefined, 2, 2);
    return processor.bufferSize;
  })();

  var iDefBufSz = BUFFER_SIZE.indexOf(defaultBufSz);

  //$bufferSize[0].valueAsNumber = iDefBufSz;   // initialize with browser default

  function updateBufferSizeText() {
    //var iBufSz = $bufferSize[0].valueAsNumber, text = "" + BUFFER_SIZE[iBufSz];
    var iBufSz = iDefBufSz;
    var text = "" + BUFFER_SIZE[iBufSz];
    if (iBufSz === iDefBufSz)
      text += ' (browser default)';
    $('#buffer-size-text').html(text);
  }

  updateBufferSizeText();         // initialize text

  /*$bufferSize.on('input', function() {
   updateBufferSizeText();
   });*/

  var audioBlob;

  // Save/Delete recording
  function saveRecording(blob, encoding) {
    var time = new Date();
    var url = URL.createObjectURL(blob);

    audioBlob = blob;

    //var html = "
"+
    //        "<audio controls src='" + url + "'></audio> " +//" ("+encoding.toUpperCase()+")"+time
    //        " Save " +
    //        "<button class='btn btn-danger' style='margin-top:-15px' recording='" + url + "'>Delete</button>"+"
";
    //
    //if ($recordingList.empty()) {
    //  $recordingList.append($(html));
    //} else {
    //  $recordingList.removeAttribute(html);
    //}

    $('#recordingUrl').prop('recording', url);
    $('#formFileCreateAudioRecorder').prop('recording', url);
    $('#audioRecordingUrl').attr('src', url);
    $('#deleteAudioRecording').prop('recording', url);

    //fileContent = TSCORE.Config.getNewTextFileContent();
    // Default new file in text file
    fileType = 'wav' || 'ogg';
    $('#newFileNameTagsAudioRecorder').select2('data', null);
    $('#newFileNameTagsAudioRecorder').select2({
      multiple: true,
      tags: TSCORE.Config.getAllTags(),
      tokenSeparators: [
        ',',
        ' '
      ],
      minimumInputLength: 1,
      selectOnBlur: true
    });

    $('#newFileNameAudioRecorder').val('');
    //$('#tagWithCurrentDate').prop('checked', false);
    $('#txtFileTypeButtonAudioRecorder').button('toggle');
    $('#formFileCreateAudioRecorder').validator();
    $('#formFileCreateAudioRecorder').submit(function(e) {
      e.preventDefault();
    });
    $('#formFileCreateAudioRecorder').on('invalid.bs.validator', function() {
      $('#audioRecordingConfirmButton').prop('disabled', true);
    });
    $('#formFileCreateAudioRecorder').on('valid.bs.validator', function() {
      $('#audioRecordingConfirmButton').prop('disabled', false);
    });
    $('#audioRecordingDialog').on('shown.bs.modal', function() {
      $('#newFileNameAudioRecorder').select2().focus();
    });
    console.debug(blob);
  }

  $recordingList.on('click', 'button', function(event) {
    var url = $(event.target).attr('recording');
    $("p[recording='" + url + "']").remove();
    URL.revokeObjectURL(url);
  });

  // Time indicator
  function minSecStr(n) {
    return (n < 10 ? "0" : "") + n;
  }

  function updateDateTime() {
    var sec = audioRecorder.recordingTime() | 0;
    $timeDisplay.html(minSecStr(sec / 60 | 0) + ":" + minSecStr(sec % 60));
    $dateTime.html((new Date).toString());
  }

  window.setInterval(updateDateTime, 200);

  // Encoding progress report modal
  var progressComplete = false;

  function setProgress(progress) {
    var percent = (progress * 100).toFixed(1) + "%";
    $modalProgress.find('.progress-bar').attr('style', "width: " + percent + ";");
    $modalProgress.find('.text-center').html(percent);
    progressComplete = progress === 1;
  }

  $modalProgress.on("hide.bs.modal", function() {
    if (!progressComplete)
      audioRecorder.cancelEncoding();
  });

  // record | stop | cancel buttons
  function disableControlsOnRecord(disabled) {
    if (microphone == null)
      $microphone.attr('disabled', disabled);
    //$timeLimit.attr('disabled', disabled);
    $encoding.attr('disabled', disabled);
    $encodingOption.attr('disabled', disabled);
    //$encodingProcess.attr('disabled', disabled);
    //$reportInterval.attr('disabled', disabled);
    //$bufferSize.attr('disabled', disabled);
  }

  function startRecording() {
    $recording.removeClass('hidden');
    $record.html('STOP');
    $cancel.removeClass('hidden');
    disableControlsOnRecord(true);
    audioRecorder.setOptions({
      //timeLimit: $timeLimit[0].valueAsNumber * 60,
      //encodeAfterRecord: encodingProcess === 'separate',
      //progressInterval: $reportInterval[0].valueAsNumber * 1000,
      ogg: {quality: OGG_QUALITY[optionValue.ogg]},
    });
    audioRecorder.startRecording();
    setProgress(0);
  }

  function stopRecording(finish) {
    $recording.addClass('hidden');
    $record.html('RECORD');
    $cancel.addClass('hidden');
    disableControlsOnRecord(false);
    if (finish) {
      audioRecorder.finishRecording();
      if (audioRecorder.options.encodeAfterRecord) {
        $modalProgress.find('.modal-title').html("Encoding " + audioRecorder.encoding.toUpperCase());
        $modalProgress.modal('show');
      }
    } else
      audioRecorder.cancelRecording();
  }

  $record.click(function() {
    if (audioRecorder.isRecording())
      stopRecording(true);
    else
      startRecording();
  });

  $cancel.click(function() {
    stopRecording(false);
  });

  // Event handlers
  audioRecorder.onTimeout = function(recorder) {
    stopRecording(true);
  };

  audioRecorder.onEncodingProgress = function(recorder, progress) {
    setProgress(progress);
  };

  audioRecorder.onComplete = function(recorder, blob) {
    if (recorder.options.encodeAfterRecord)
      $modalProgress.modal('hide');
    saveRecording(blob, recorder.encoding);
  };

  audioRecorder.onError = function(recorder, message) {
    $modalError.find('.alert').html(message);
    $modalError.modal('show');
  };

  // Public API definition
  exports.initUI = initUI;
});
<|endoftext|>