<commit_before>const regl = require('../regl')()
const mat4 = require('gl-mat4')
const hsv2rgb = require('hsv2rgb')

const NUM_POINTS = 1e4
const VERT_SIZE = 4 * (4 + 4 + 3)

const pointBuffer = regl.buffer(Array(NUM_POINTS).fill().map(function () {
  const color = hsv2rgb(Math.random() * 360, 0.6, 1)
  return [
    // freq
    Math.random() * 10,
    Math.random() * 10,
    Math.random() * 10,
    Math.random() * 10,
    // phase
    2.0 * Math.PI * Math.random(),
    2.0 * Math.PI * Math.random(),
    2.0 * Math.PI * Math.random(),
    2.0 * Math.PI * Math.random(),
    // color
    color[0] / 255, color[1] / 255, color[2] / 255
  ]
}))

const drawParticles = regl({
  vert: `
  precision mediump float;
  attribute vec4 freq, phase;
  attribute vec3 color;
  uniform float time;
  uniform mat4 view, projection;
  varying vec3 fragColor;
  void main() {
    vec3 position = 8.0 * cos(freq.xyz * time + phase.xyz);
    gl_PointSize = 5.0 * (1.0 + cos(freq.w * time + phase.w));
    gl_Position = projection * view * vec4(position, 1);
    fragColor = color;
  }`,

  frag: `
  precision lowp float;
  varying vec3 fragColor;
  void main() {
    if (length(gl_PointCoord.xy - 0.5) > 0.5) {
      discard;
    }
    gl_FragColor = vec4(fragColor, 1);
  }`,

  attributes: {
    freq: {
      buffer: pointBuffer,
      stride: VERT_SIZE,
      offset: 0
    },
    phase: {
      buffer: pointBuffer,
      stride: VERT_SIZE,
      offset: 16
    },
    color: {
      buffer: pointBuffer,
      stride: VERT_SIZE,
      offset: 32
    }
  },

  uniforms: {
    view: (props, {count}) => {
      const t = 0.01 * count
      return mat4.lookAt([],
        [30 * Math.cos(t), 2.5, 30 * Math.sin(t)],
        [0, 0, 0],
        [0, 1, 0])
    },
    projection: (props, {viewportWidth, viewportHeight}) => {
      return mat4.perspective([],
        Math.PI / 4,
        viewportWidth / viewportHeight,
        0.01,
        1000)
    },
    time: (props, {count}) => {
      return count * 0.001
    }
  },

  count: NUM_POINTS,

  primitive: 'points'
})

regl.frame((props, context) => {
  regl.clear({
    depth: 1,
    color: [0, 0, 0, 1]
  })

  drawParticles()
})
<commit_msg>update particle example<commit_after>const regl = require('../regl')()
const mat4 = require('gl-mat4')
const hsv2rgb = require('hsv2rgb')

const NUM_POINTS = 1e4
const VERT_SIZE = 4 * (4 + 4 + 3)

const pointBuffer = regl.buffer(Array(NUM_POINTS).fill().map(function () {
  const color = hsv2rgb(Math.random() * 360, 0.6, 1)
  return [
    // freq
    Math.random() * 10,
    Math.random() * 10,
    Math.random() * 10,
    Math.random() * 10,
    // phase
    2.0 * Math.PI * Math.random(),
    2.0 * Math.PI * Math.random(),
    2.0 * Math.PI * Math.random(),
    2.0 * Math.PI * Math.random(),
    // color
    color[0] / 255, color[1] / 255, color[2] / 255
  ]
}))

const drawParticles = regl({
  vert: `
  precision mediump float;
  attribute vec4 freq, phase;
  attribute vec3 color;
  uniform float time;
  uniform mat4 view, projection;
  varying vec3 fragColor;
  void main() {
    vec3 position = 8.0 * cos(freq.xyz * time + phase.xyz);
    gl_PointSize = 5.0 * (1.0 + cos(freq.w * time + phase.w));
    gl_Position = projection * view * vec4(position, 1);
    fragColor = color;
  }`,

  frag: `
  precision lowp float;
  varying vec3 fragColor;
  void main() {
    if (length(gl_PointCoord.xy - 0.5) > 0.5) {
      discard;
    }
    gl_FragColor = vec4(fragColor, 1);
  }`,

  attributes: {
    freq: {
      buffer: pointBuffer,
      stride: VERT_SIZE,
      offset: 0
    },
    phase: {
      buffer: pointBuffer,
      stride: VERT_SIZE,
      offset: 16
    },
    color: {
      buffer: pointBuffer,
      stride: VERT_SIZE,
      offset: 32
    }
  },

  uniforms: {
    view: ({count}) => {
      const t = 0.01 * count
      return mat4.lookAt([],
        [30 * Math.cos(t), 2.5, 30 * Math.sin(t)],
        [0, 0, 0],
        [0, 1, 0])
    },
    projection: ({viewportWidth, viewportHeight}) =>
      mat4.perspective([],
        Math.PI / 4,
        viewportWidth / viewportHeight,
        0.01,
        1000),
    time: ({count}) => count * 0.001
  },

  count: NUM_POINTS,

  primitive: 'points'
})

regl.frame(() => {
  regl.clear({
    depth: 1,
    color: [0, 0, 0, 1]
  })

  drawParticles()
})
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  client: {
    lib: {
      css: [
        'public/lib/bootstrap/dist/css/bootstrap.css',
        'public/lib/bootstrap/dist/css/bootstrap-theme.css',
        'public/lib/fullcalendar/dist/fullcalendar.css'

      ],
      js: [
        'public/lib/angular/angular.js',
        'public/lib/angular-resource/angular-resource.js',
        'public/lib/angular-animate/angular-animate.js',
        'public/lib/angular-messages/angular-messages.js',
        'public/lib/angular-ui-router/release/angular-ui-router.js',
        'public/lib/angular-ui-utils/ui-utils.js',
        'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
        'public/lib/angular-file-upload/angular-file-upload.js',
        'public/lib/owasp-password-strength-test/owasp-password-strength-test.js',
        'public/lib/jquery/dist/jquery.min.js',
        'public/lib/moment/min/moment.min.js',
        'public/lib/angular-ui-calendar/src/calendar.js',
        'public/lib/fullcalendar/dist/fullcalendar.min.js',
        'public/lib/fullcalendar/dist/gcal.js',

        'https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places,geometry',
        'public/lib/ngmap/build/scripts/ng-map.min.js',
        //'public/lib/aws-sdk/dist/aws-sdk.min.js',
        'public/lib/aws-sdk-js/dist/aws-sdk.min.js',

        'public/lib/socket.io-client/socket.io.js',
        'public/lib/angular-socket-io/socket.js',

      ],
      tests: ['public/lib/angular-mocks/angular-mocks.js']
    },
    css: [
      'modules/*/client/css/*.css'
    ],
    less: [
      'modules/*/client/less/*.less'
    ],
    sass: [
      'modules/*/client/scss/*.scss'
    ],
    js: [
      'modules/core/client/app/config.js',
      'modules/core/client/app/init.js',
      'modules/*/client/*.js',
      'modules/*/client/**/*.js'
    ],
    img: [
      'modules/**/*/img/**/*.jpg',
      'modules/**/*/img/**/*.png',
      'modules/**/*/img/**/*.gif',
      'modules/**/*/img/**/*.svg'
    ],
    views: ['modules/*/client/views/**/*.html'],
    templates: ['build/templates.js']
  },
  server: {
    gruntConfig: ['gruntfile.js'],
    gulpConfig: ['gulpfile.js'],
    allJS: ['server.js', 'config/**/*.js', 'modules/*/server/**/*.js'],
    models: 'modules/*/server/models/**/*.js',
    routes: ['modules/!(core)/server/routes/**/*.js', 'modules/core/server/routes/**/*.js'],
    sockets: 'modules/*/server/sockets/**/*.js',
    config: ['modules/*/server/config/*.js'],
    policies: 'modules/*/server/policies/*.js',
    views: ['modules/*/server/views/*.html']
  }
};
<commit_msg>add aws js<commit_after>'use strict';

module.exports = {
  client: {
    lib: {
      css: [
        'public/lib/bootstrap/dist/css/bootstrap.css',
        'public/lib/bootstrap/dist/css/bootstrap-theme.css',
        'public/lib/fullcalendar/dist/fullcalendar.css'

      ],
      js: [

        'public/lib/angular/angular.js',
        'public/lib/angular-resource/angular-resource.js',
        'public/lib/angular-animate/angular-animate.js',
        'public/lib/angular-messages/angular-messages.js',
        'public/lib/angular-ui-router/release/angular-ui-router.js',
        'public/lib/angular-ui-utils/ui-utils.js',
        'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
        'public/lib/angular-file-upload/angular-file-upload.js',
        'public/lib/owasp-password-strength-test/owasp-password-strength-test.js',
        'public/lib/jquery/dist/jquery.min.js',
        'public/lib/moment/min/moment.min.js',
        'public/lib/angular-ui-calendar/src/calendar.js',
        'public/lib/fullcalendar/dist/fullcalendar.min.js',
        'public/lib/fullcalendar/dist/gcal.js',

        'https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places,geometry',
        'public/lib/ngmap/build/scripts/ng-map.min.js',
        //'public/lib/aws-sdk/dist/aws-sdk.min.js',
        'public/lib/aws-sdk-js/dist/aws-sdk.min.js',

        'public/lib/socket.io-client/socket.io.js',
        'public/lib/angular-socket-io/socket.js',

      ],
      tests: ['public/lib/angular-mocks/angular-mocks.js']
    },
    css: [
      'modules/*/client/css/*.css'
    ],
    less: [
      'modules/*/client/less/*.less'
    ],
    sass: [
      'modules/*/client/scss/*.scss'
    ],
    js: [
      'modules/core/client/app/config.js',
      'modules/core/client/app/init.js',
      'modules/*/client/*.js',
      'modules/*/client/**/*.js'
    ],
    img: [
      'modules/**/*/img/**/*.jpg',
      'modules/**/*/img/**/*.png',
      'modules/**/*/img/**/*.gif',
      'modules/**/*/img/**/*.svg'
    ],
    views: ['modules/*/client/views/**/*.html'],
    templates: ['build/templates.js']
  },
  server: {
    gruntConfig: ['gruntfile.js'],
    gulpConfig: ['gulpfile.js'],
    allJS: ['server.js', 'config/**/*.js', 'modules/*/server/**/*.js'],
    models: 'modules/*/server/models/**/*.js',
    routes: ['modules/!(core)/server/routes/**/*.js', 'modules/core/server/routes/**/*.js'],
    sockets: 'modules/*/server/sockets/**/*.js',
    config: ['modules/*/server/config/*.js'],
    policies: 'modules/*/server/policies/*.js',
    views: ['modules/*/server/views/*.html']
  }
};
<|endoftext|>


<commit_before>var EntityBase = require('./EntityBase');

var PayInTemplateURLOptions = EntityBase.extend({
    defaults: {
        PAYLINE: null
    }
});

module.exports = PayInTemplateURLOptions;<commit_msg>Add PAYLINEV2 parameter on TemplateURLOptions<commit_after>var EntityBase = require('./EntityBase');

var PayInTemplateURLOptions = EntityBase.extend({
    defaults: {
        PAYLINE: null,
        PAYLINEV2: null
    }
});

module.exports = PayInTemplateURLOptions;
<|endoftext|>


<commit_before>import _ from 'lodash';
import jsonPatch from 'fast-json-patch';

import Keys from '/imports/api/keys/Keys';
import Changes from '/imports/api/changes/Changes';

import ChangeEmailNotification from '/imports/api/notifications/ChangeEmailNotification';

import addKeyCharacters from '/imports/api/characters/addKeyCharacters';

// TODO: Break this up further
const handleChanges = async (keyID, error, result) => {
  // Create array to hold all changes to key since last check
  const ignoredErrors = ['CONNERR', 'INTERNAL'];
  const newChanges = [];

  // Build out the newChanges array
  if (error) {
    if (error.apiError) {
      console.log(`${error.code}: ${error.apiError}`);

      // TODO: Give feedback to user for ignored errors
      // FIXME: This doesn't actually ignore the error
      // Connection errors etc are logged to console and ignored
      // Push the error if it's not on the ignoredErrors list
      if (!(ignoredErrors.indexOf(error.apiError) > -1)) {
        newChanges.push({ changeType: error.apiError, severity: 'ERROR' });
      }
    } else {
      // Handle corporation check failures; all failed checks are iterated over and each represents a separate change
      error.flags.forEach(flag => newChanges.push({ changeType: flag, severity: 'ERROR' }));
    }
  } else {
    // Handle changes that don't invalidate the key
    const oldRecord = Keys.findOne({ keyID }).resultBody.characters;
    const newRecord = result.characters;
    if (keyID == null) {
      console.error('keyID is null in handleChanges');
    }
    if (result == null) {
      console.error('result is null in handleChanges');
    }
    const diff = jsonPatch.compare(oldRecord, newRecord);

    // Iterate over the diff array, handling every possible change of importance to the corp
    diff.forEach((change, index) => {
      // 'replace' ops can only logically happen inside a single character(#) object
      if (change.op === 'replace') {
        // RegEx to catch changes to corporationID or allianceID
        const charChangePattern = /\/(\d+)\/(corporationID|allianceID)/;
        // After test, charChangeTest will hold remembered values for characterID and changed field
        // exec() returns an array where first item is the matched string, all other items are remembered values
        const charChangeTest = charChangePattern.exec(diff[index].path);
        // Make sure that the test was successful and if so, pull out remembered values
        if (charChangeTest) {
          let curChangeType = '';
          const curCharID = charChangeTest[1];
          const curFieldName = charChangeTest[2];
          const oldValue = oldRecord[curCharID][curFieldName];
          const newValue = change.value;
          const npcCorpPattern = /1000(?:165|166|077|044|045|167|169|168|115|172|170|171)/;

          if (curFieldName === 'corporationID' && npcCorpPattern.test(newValue)) curChangeType = 'leaveCorp';
          else if (curFieldName === 'corporationID' && npcCorpPattern.test(oldValue)) curChangeType = 'joinCorp';
          else if (curFieldName === 'corporationID') curChangeType = 'switchCorp';
          else if (curFieldName === 'allianceID' && newValue === '0') curChangeType = 'leaveAlliance';
          else if (curFieldName === 'allianceID' && oldValue === '0') curChangeType = 'joinAlliance';
          else if (curFieldName === 'allianceID') curChangeType = 'switchAlliance';

          newChanges.push({
            changeType: curChangeType,
            oldValueStr: oldValue,
            newValueStr: newValue,
            severity: 'WARNING',
            context: {
              charID: curCharID,
              charName: oldRecord[curCharID].characterName,
              oldName: oldRecord[curCharID][curFieldName.replace('ID', 'Name')],
              newName: newRecord[curCharID][curFieldName.replace('ID', 'Name')],
            },
          });
        }
      } else if (change.op === 'add' || change.op === 'remove') {
        // 'add' and 'remove' ops can only logically happen at the 'characters' level
        // The following works very similarly to the "if" block above. Look there for more help.
        const charAddRemovePattern = /\/(\d+)/;
        const charAddRemoveTest = charAddRemovePattern.exec(diff[index].path);
        if (charAddRemoveTest && charAddRemoveTest[0]) {
          const curCharID = charAddRemoveTest[1];

          newChanges.push({
            changeType: `${change.op}Character`,
            // Depending on which type of operation, either 'old'('add' op) or 'new'('remove' op) will be undefined
            oldValueObj: oldRecord[curCharID],
            newValueObj: change.value,
            severity: 'WARNING',
          });
        }
      }
    });

    if (diff.length !== 0) {
      Keys.update(Keys.findOne({ keyID })._id, {
        $set: {
          'resultBody.characters': result.characters,
        },
      });

      await addKeyCharacters(keyID);
    }
  }
  if (newChanges.length) {
    console.log('New changes:', newChanges);

    Changes.update(
      { keyID },
      {
        $set: {
          keyID,
        },
        $push: {
          log: {
            changes: newChanges,
            createdAt: new Date(),
          },
        },
      },
      {
        upsert: true,
      }
    );

    let highestSeverity = 'WARNING';
    for (let i = 0; i < newChanges.length; i++) {
      const change = newChanges[i];
      if (change.severity === 'ERROR') {
        highestSeverity = change.severity;
        break;
      }
    }

    Keys.update(Keys.findOne({ keyID })._id, {
      $set: {
        status: highestSeverity,
      },
    });

    let shouldNotify = false;
    for (const change of newChanges) {
      if (!_.includes(['leaveAlliance', 'joinAlliance', 'switchAlliance'], change.changeType)) {
        shouldNotify = true;
      }
    }

    // TODO: Remove or use highestSeverity
    if (shouldNotify) {
      const primaryChar = Keys.findOne({ keyID }).primaryChar;
      const email = new ChangeEmailNotification(newChanges, keyID, primaryChar);
      email.send();
    }
  } else {
    console.log('No new changes');
  }
};

export default handleChanges;
<commit_msg>Fix API errors and flags always being reported as new changes<commit_after>import _ from 'lodash';
import jsonPatch from 'fast-json-patch';

import Keys from '/imports/api/keys/Keys';
import Changes from '/imports/api/changes/Changes';

import ChangeEmailNotification from '/imports/api/notifications/ChangeEmailNotification';

import addKeyCharacters from '/imports/api/characters/addKeyCharacters';

const getLastChanges = async (keyID) => {
  const c = await Changes.findOne({ keyID });
  if (c == null || !c.log.length) return [];
  return c.log[c.log.length - 1].changes;
};

// TODO: Break this up further
const handleChanges = async (keyID, error, result) => {
  // Create array to hold all changes to key since last check
  const ignoredErrors = ['CONNERR', 'INTERNAL'];
  const newChanges = [];

  // Build out the newChanges array
  if (error) {
    const lastChanges = await getLastChanges(keyID);
    if (error.apiError) {
      console.log(`${error.code}: ${error.apiError}`);

      // TODO: Give feedback to user for ignored errors
      // Connection errors etc are logged to console and ignored
      // Push the error if it's not on the ignoredErrors list
      if (!(ignoredErrors.indexOf(error.apiError) > -1)) {
        const newChange = { changeType: error.apiError, severity: 'ERROR' };
        // Push the change if it's new
        if (!_.some(lastChanges, newChange)) {
          newChanges.push(newChange);
        }
      }
    } else {
      // Handle corporation check failures; all failed checks are iterated over and each represents a separate change
      error.flags.forEach((flag) => {
        const newChange = { changeType: flag, severity: 'ERROR' };
        // Push the change if it's new
        if (!_.some(lastChanges, newChange)) {
          newChanges.push(newChange);
        }
      });
    }
  } else {
    // Handle changes that don't invalidate the key
    const oldRecord = Keys.findOne({ keyID }).resultBody.characters;
    const newRecord = result.characters;
    if (keyID == null) {
      console.error('keyID is null in handleChanges');
    }
    if (result == null) {
      console.error('result is null in handleChanges');
    }
    const diff = jsonPatch.compare(oldRecord, newRecord);

    // Iterate over the diff array, handling every possible change of importance to the corp
    diff.forEach((change, index) => {
      // 'replace' ops can only logically happen inside a single character(#) object
      if (change.op === 'replace') {
        // RegEx to catch changes to corporationID or allianceID
        const charChangePattern = /\/(\d+)\/(corporationID|allianceID)/;
        // After test, charChangeTest will hold remembered values for characterID and changed field
        // exec() returns an array where first item is the matched string, all other items are remembered values
        const charChangeTest = charChangePattern.exec(diff[index].path);
        // Make sure that the test was successful and if so, pull out remembered values
        if (charChangeTest) {
          let curChangeType = '';
          const curCharID = charChangeTest[1];
          const curFieldName = charChangeTest[2];
          const oldValue = oldRecord[curCharID][curFieldName];
          const newValue = change.value;
          const npcCorpPattern = /1000(?:165|166|077|044|045|167|169|168|115|172|170|171)/;

          if (curFieldName === 'corporationID' && npcCorpPattern.test(newValue)) curChangeType = 'leaveCorp';
          else if (curFieldName === 'corporationID' && npcCorpPattern.test(oldValue)) curChangeType = 'joinCorp';
          else if (curFieldName === 'corporationID') curChangeType = 'switchCorp';
          else if (curFieldName === 'allianceID' && newValue === '0') curChangeType = 'leaveAlliance';
          else if (curFieldName === 'allianceID' && oldValue === '0') curChangeType = 'joinAlliance';
          else if (curFieldName === 'allianceID') curChangeType = 'switchAlliance';

          newChanges.push({
            changeType: curChangeType,
            oldValueStr: oldValue,
            newValueStr: newValue,
            severity: 'WARNING',
            context: {
              charID: curCharID,
              charName: oldRecord[curCharID].characterName,
              oldName: oldRecord[curCharID][curFieldName.replace('ID', 'Name')],
              newName: newRecord[curCharID][curFieldName.replace('ID', 'Name')],
            },
          });
        }
      } else if (change.op === 'add' || change.op === 'remove') {
        // 'add' and 'remove' ops can only logically happen at the 'characters' level
        // The following works very similarly to the "if" block above. Look there for more help.
        const charAddRemovePattern = /\/(\d+)/;
        const charAddRemoveTest = charAddRemovePattern.exec(diff[index].path);
        if (charAddRemoveTest && charAddRemoveTest[0]) {
          const curCharID = charAddRemoveTest[1];

          newChanges.push({
            changeType: `${change.op}Character`,
            // Depending on which type of operation, either 'old'('add' op) or 'new'('remove' op) will be undefined
            oldValueObj: oldRecord[curCharID],
            newValueObj: change.value,
            severity: 'WARNING',
          });
        }
      }
    });

    if (diff.length !== 0) {
      Keys.update(Keys.findOne({ keyID })._id, {
        $set: {
          'resultBody.characters': result.characters,
        },
      });

      await addKeyCharacters(keyID);
    }
  }
  if (newChanges.length) {
    console.log('New changes:', newChanges);

    Changes.update(
      { keyID },
      {
        $set: {
          keyID,
        },
        $push: {
          log: {
            changes: newChanges,
            createdAt: new Date(),
          },
        },
      },
      {
        upsert: true,
      }
    );

    let highestSeverity = 'WARNING';
    for (let i = 0; i < newChanges.length; i++) {
      const change = newChanges[i];
      if (change.severity === 'ERROR') {
        highestSeverity = change.severity;
        break;
      }
    }

    Keys.update(Keys.findOne({ keyID })._id, {
      $set: {
        status: highestSeverity,
      },
    });

    let shouldNotify = false;
    for (const change of newChanges) {
      if (!_.includes(['leaveAlliance', 'joinAlliance', 'switchAlliance'], change.changeType)) {
        shouldNotify = true;
      }
    }

    // TODO: Remove or use highestSeverity
    if (shouldNotify) {
      const primaryChar = Keys.findOne({ keyID }).primaryChar;
      const email = new ChangeEmailNotification(newChanges, keyID, primaryChar);
      email.send();
    }
  } else {
    console.log('No new changes');
  }
};

export default handleChanges;
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  client: {
    lib: {
      css: [
        'public/lib/bootstrap/dist/css/bootstrap.css',
        'public/lib/bootstrap-additions/dist/bootstrap-additions.css',
        'public/lib/angular-material/angular-material.css',
        'public/lib/components-font-awesome/css/font-awesome.css',
        'public/lib/ng-tags-input/ng-tags-input.css',
        'public/lib/angular-moment-picker/dist/angular-moment-picker.css',
        'public/lib/textAngular/dist/textAngular.css',
        'public/lib/angular-toasty/dist/angular-toasty.css',
        'public/lib/angular-toastr/dist/angular-toastr.css',
        'public/lib/ng-dialog/css/ngDialog.min.css'
      ],
      js: [
        'public/lib/angular/angular.js',
        'public/lib/angular-resource/angular-resource.js',
        'public/lib/angular-animate/angular-animate.js',
        'public/lib/angular-messages/angular-messages.js',
        'public/lib/angular-sanitize/angular-sanitize.js',
        'public/lib/angular-socket-io/socket.js',
        'public/lib/angular-touch/angular-touch.js',
        'public/lib/angular-ui-router/release/angular-ui-router.js',
        'public/lib/angular-ui-utils/ui-utils.js',
        'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
        'public/lib/angular-bootstrap/ui.bootstrap.materialPicker.js',
        'public/lib/angular-strap/dist/angular-strap.js',
        'public/lib/angular-strap/dist/angular-strap.tpl.js',
        'public/lib/angular-strap/dist/angular-strap.compat.js',
        'public/lib/angular-file-upload/angular-file-upload.js',
        'public/lib/angular-aria/angular-aria.js',
        'public/lib/angular-material/angular-material.js',
        'public/lib/angular-ui-switch/angular-ui-switch.js',
        'public/lib/angular-elastic/elastic.js',
        'public/lib/chart.js/dist/Chart.js',
        'public/lib/angular-chart.js/dist/angular-chart.js',
        'public/lib/ng-tags-input/ng-tags-input.js',
        'public/lib/underscore/underscore.js',
        'public/lib/moment/moment.js',
        'public/lib/angular-moment/angular-moment.js',
        'public/lib/angular-moment-picker/dist/angular-moment-picker.js',
        'public/lib/owasp-password-strength-test/owasp-password-strength-test.js',
        'public/lib/ngInfiniteScroll/build/ng-infinite-scroll.js',
        'public/lib/textAngular/dist/textAngular-rangy.min.js',
        'public/lib/textAngular/dist/textAngular-sanitize.min.js',
        'public/lib/textAngular/dist/textAngular.js',
        'public/lib/textAngular/dist/textAngularSetup.js',
        'public/lib/angular-toasty/dist/angular-toasty.js',
        'public/lib/angular-toastr/dist/angular-toastr.tpls.js',
        'public/lib/ng-dialog/js/ngDialog.min.js'
      ],
      tests: ['public/lib/angular-mocks/angular-mocks.js']
    },
    css: [
      'modules/*/client/css/*.css'
    ],
    less: [
      'modules/*/client/less/*.less'
    ],
    sass: [
      'modules/*/client/scss/*.scss'
    ],
    js: [
      'modules/core/client/app/config.js',
      'modules/core/client/app/init.js',
      'modules/*/client/*.js',
      'modules/*/client/**/*.js',
      'modules/*/client/**/**/*.js',
    ],
    views: ['modules/*/client/views/**/*.html'],
    templates: ['build/templates.js']
  },
  server: {
    gruntConfig: 'gruntfile.js',
    gulpConfig: 'gulpfile.js',
    allJS: ['server.js', 'config/**/*.js', 'modules/*/server/**/*.js'],
    models: 'modules/*/server/models/**/*.js',
    routes: ['modules/!(core)/server/routes/**/*.js', 'modules/core/server/routes/**/*.js'],
    sockets: 'modules/*/server/sockets/**/*.js',
    config: 'modules/*/server/config/*.js',
    policies: 'modules/*/server/policies/*.js',
    views: 'modules/*/server/views/*.html'
  }
};
<commit_msg>Commited from HaNhatLenh at Sat, Jul 08, 2017 11:28:46 AM<commit_after>'use strict';

module.exports = {
  client: {
    lib: {
      css: [
        'public/lib/bootstrap/dist/css/bootstrap.css',
        'public/lib/bootstrap-additions/dist/bootstrap-additions.css',
        'public/lib/angular-material/angular-material.css',
        'public/lib/components-font-awesome/css/font-awesome.css',
        'public/lib/ng-tags-input/ng-tags-input.css',
        'public/lib/angular-moment-picker/dist/angular-moment-picker.css',
        'public/lib/textAngular/dist/textAngular.css',
        'public/lib/angular-toasty/dist/angular-toasty.css',
        'public/lib/angular-toastr/dist/angular-toastr.css',
        'public/lib/ng-dialog/css/ngDialog.min.css',
        'public/lib/ng-dialog/css/ngDialog-theme-default.min.css'
      ],
      js: [
        'public/lib/angular/angular.js',
        'public/lib/angular-resource/angular-resource.js',
        'public/lib/angular-animate/angular-animate.js',
        'public/lib/angular-messages/angular-messages.js',
        'public/lib/angular-sanitize/angular-sanitize.js',
        'public/lib/angular-socket-io/socket.js',
        'public/lib/angular-touch/angular-touch.js',
        'public/lib/angular-ui-router/release/angular-ui-router.js',
        'public/lib/angular-ui-utils/ui-utils.js',
        'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
        'public/lib/angular-bootstrap/ui.bootstrap.materialPicker.js',
        'public/lib/angular-strap/dist/angular-strap.js',
        'public/lib/angular-strap/dist/angular-strap.tpl.js',
        'public/lib/angular-strap/dist/angular-strap.compat.js',
        'public/lib/angular-file-upload/angular-file-upload.js',
        'public/lib/angular-aria/angular-aria.js',
        'public/lib/angular-material/angular-material.js',
        'public/lib/angular-ui-switch/angular-ui-switch.js',
        'public/lib/angular-elastic/elastic.js',
        'public/lib/chart.js/dist/Chart.js',
        'public/lib/angular-chart.js/dist/angular-chart.js',
        'public/lib/ng-tags-input/ng-tags-input.js',
        'public/lib/underscore/underscore.js',
        'public/lib/moment/moment.js',
        'public/lib/angular-moment/angular-moment.js',
        'public/lib/angular-moment-picker/dist/angular-moment-picker.js',
        'public/lib/owasp-password-strength-test/owasp-password-strength-test.js',
        'public/lib/ngInfiniteScroll/build/ng-infinite-scroll.js',
        'public/lib/textAngular/dist/textAngular-rangy.min.js',
        'public/lib/textAngular/dist/textAngular-sanitize.min.js',
        'public/lib/textAngular/dist/textAngular.js',
        'public/lib/textAngular/dist/textAngularSetup.js',
        'public/lib/angular-toasty/dist/angular-toasty.js',
        'public/lib/angular-toastr/dist/angular-toastr.tpls.js',
        'public/lib/ng-dialog/js/ngDialog.min.js'
      ],
      tests: ['public/lib/angular-mocks/angular-mocks.js']
    },
    css: [
      'modules/*/client/css/*.css'
    ],
    less: [
      'modules/*/client/less/*.less'
    ],
    sass: [
      'modules/*/client/scss/*.scss'
    ],
    js: [
      'modules/core/client/app/config.js',
      'modules/core/client/app/init.js',
      'modules/*/client/*.js',
      'modules/*/client/**/*.js',
      'modules/*/client/**/**/*.js',
    ],
    views: ['modules/*/client/views/**/*.html'],
    templates: ['build/templates.js']
  },
  server: {
    gruntConfig: 'gruntfile.js',
    gulpConfig: 'gulpfile.js',
    allJS: ['server.js', 'config/**/*.js', 'modules/*/server/**/*.js'],
    models: 'modules/*/server/models/**/*.js',
    routes: ['modules/!(core)/server/routes/**/*.js', 'modules/core/server/routes/**/*.js'],
    sockets: 'modules/*/server/sockets/**/*.js',
    config: 'modules/*/server/config/*.js',
    policies: 'modules/*/server/policies/*.js',
    views: 'modules/*/server/views/*.html'
  }
};
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  client: {
    lib: {
      css: [
        'public/lib/bootstrap/dist/css/bootstrap.css',
        'public/lib/bootstrap/dist/css/bootstrap-theme.css'
      ],
      js: [
        'public/lib/angular/angular.js',
        'public/lib/angular-resource/angular-resource.js',
        'public/lib/angular-animate/angular-animate.js',
        'public/lib/angular-messages/angular-messages.js',
        'public/lib/angular-ui-router/release/angular-ui-router.js',
        'public/lib/angular-ui-utils/ui-utils.js',
        'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
        'public/lib/angular-file-upload/angular-file-upload.js',
        'public/lib/owasp-password-strength-test/owasp-password-strength-test.js',
          '//connect.facebook.net/en_US/sdk.js'
      ],
      tests: ['public/lib/angular-mocks/angular-mocks.js']
    },
    css: [
      'modules/*/client/css/*.css'
    ],
    less: [
      'modules/*/client/less/*.less'
    ],
    sass: [
      'modules/*/client/scss/*.scss'
    ],
    js: [
      'modules/core/client/app/config.js',
      'modules/core/client/app/init.js',
      'modules/*/client/*.js',
      'modules/*/client/**/*.js'
    ],
    views: ['modules/*/client/views/**/*.html'],
    templates: ['build/templates.js']
  },
  server: {
    gruntConfig: 'gruntfile.js',
    gulpConfig: 'gulpfile.js',
    allJS: ['server.js', 'config/**/*.js', 'modules/*/server/**/*.js'],
    models: 'modules/*/server/models/**/*.js',
    routes: ['modules/!(core)/server/routes/**/*.js', 'modules/core/server/routes/**/*.js'],
    sockets: 'modules/*/server/sockets/**/*.js',
    config: 'modules/*/server/config/*.js',
    policies: 'modules/*/server/policies/*.js',
    views: 'modules/*/server/views/*.html'
  }
};
<commit_msg>facebook config ---facebooksdk added default.js<commit_after>'use strict';

module.exports = {
  client: {
    lib: {
      css: [
        'public/lib/bootstrap/dist/css/bootstrap.css',
        'public/lib/bootstrap/dist/css/bootstrap-theme.css'
      ],
      js: [
        'public/lib/angular/angular.js',
        'public/lib/angular-resource/angular-resource.js',
        'public/lib/angular-animate/angular-animate.js',
        'public/lib/angular-messages/angular-messages.js',
        'public/lib/angular-ui-router/release/angular-ui-router.js',
        'public/lib/angular-ui-utils/ui-utils.js',
        'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
        'public/lib/angular-file-upload/angular-file-upload.js',
        'public/lib/owasp-password-strength-test/owasp-password-strength-test.js',
          '//connect.facebook.net/en_US/all.js'
      ],
      tests: ['public/lib/angular-mocks/angular-mocks.js']
    },
    css: [
      'modules/*/client/css/*.css'
    ],
    less: [
      'modules/*/client/less/*.less'
    ],
    sass: [
      'modules/*/client/scss/*.scss'
    ],
    js: [
      'modules/core/client/app/config.js',
      'modules/core/client/app/init.js',
      'modules/*/client/*.js',
      'modules/*/client/**/*.js'
    ],
    views: ['modules/*/client/views/**/*.html'],
    templates: ['build/templates.js']
  },
  server: {
    gruntConfig: 'gruntfile.js',
    gulpConfig: 'gulpfile.js',
    allJS: ['server.js', 'config/**/*.js', 'modules/*/server/**/*.js'],
    models: 'modules/*/server/models/**/*.js',
    routes: ['modules/!(core)/server/routes/**/*.js', 'modules/core/server/routes/**/*.js'],
    sockets: 'modules/*/server/sockets/**/*.js',
    config: 'modules/*/server/config/*.js',
    policies: 'modules/*/server/policies/*.js',
    views: 'modules/*/server/views/*.html'
  }
};
<|endoftext|>


<commit_before>var createSpec = require('spec-js'),
    EventEmitter = require('events').EventEmitter,
    jsonConverter = require('./jsonConverter');

var stack = [];
function eventually(fn){
    stack.push(fn);
    if(stack.length === 1){
        setTimeout(function(){
            while(stack.length){
                stack.pop()();
            }
        },100);
    }
}

function getItemPath(item){
    var gedi = item.gaffa.gedi,
        paths = [],
        referencePath,
        referenceItem = item;

    while(referenceItem){

        // item.path should be a child ref after item.sourcePath
        if(referenceItem.path != null){
            paths.push(referenceItem.path);
        }

        // item.sourcePath is most root level path
        if(referenceItem.sourcePath != null){
            paths.push(gedi.paths.create(referenceItem.sourcePath));
        }

        referenceItem = referenceItem.parent;
    }

    return gedi.paths.resolve.apply(this, paths.reverse());
}

var iuid = 0;

function Bindable(){
    this.setMaxListeners(1000);
    // instance unique ID
    this.__iuid = iuid++;
}
Bindable = createSpec(Bindable, EventEmitter);
Bindable.bindables = {};
Bindable.getByIuid = function(id){
    return this.bindables[id];
};
Bindable.prototype.getPath = function(){
    return getItemPath(this);
};
Bindable.prototype.getDataAtPath = function(){
    if(!this.gaffa){
        return;
    }
    return this.gaffa.model.get(getItemPath(this));
};
Bindable.prototype.toJSON = function(){
    var tempObject = jsonConverter(this, this.__serialiseExclude__, this.__serialiseInclude__);

    return tempObject;
};

function setupCleanup(bindable, parent){
    var onDebind = bindable.debind.bind(bindable);
    parent.once('debind', onDebind);
    bindable.once('debind', function(){
        bindable.parent.removeListener('debind', onDebind);
    });

    var onDestroy = bindable.destroy.bind(bindable);
    parent.once('destroy', onDestroy);
    bindable.once('destroy', function(){
        bindable.parent.removeListener('destroy', onDestroy);
    });
}

Bindable.prototype.bind = function(parent){
    if(parent && !parent._bound){
        console.warn('Attempted to bind to a parent who was not bound.');
        return;
    }
    if(this._bound){
        this.debind();
        console.warn('Attempted to bind an already bound item.');
    }

    if(parent){
        this.gaffa = parent.gaffa;
        this.parent = parent;
        this._parentId = parent.__iuid;

        setupCleanup(this, parent);
    }

    this.updatePath();

    this._bound = true;
    Bindable.bindables[this.__iuid] = this;
    this.emit('bind');
    this.removeAllListeners('bind');
};
Bindable.prototype.getSourcePath = function(){
    return this.gaffa.gedi.paths.resolve(this.parent && this.parent.getPath(), this.sourcePath);
}
Bindable.prototype.updatePath = function(){
    if(!this.pathBinding){
        return;
    }

    var bindable = this,
        absoluteSourcePath = this.getSourcePath(),
        lastPath = this.path,
        gaffa = this.gaffa;

    function setPath(valueTokens){
        if(valueTokens){
            var valueToken = valueTokens[valueTokens.length - 1];
            bindable.path = valueToken.sourcePathInfo && valueToken.sourcePathInfo.path;
        }

        if(lastPath !== bindable.path && bindable._bound){
            bindable.debind();
            bindable.bind(bindable.parent);
        }
    }

    setPath(gaffa.gedi.get(this.pathBinding, absoluteSourcePath, bindable.scope, true));

    function handlePathChange(event){
        setPath(gaffa.model.get(bindable.pathBinding, bindable, bindable.scope, true));
    }

    gaffa.gedi.bind(this.pathBinding, handlePathChange, absoluteSourcePath);
    this.on('debind', function(){
        gaffa.gedi.debind(bindable.pathBinding, handlePathChange, absoluteSourcePath);
    });
};
Bindable.prototype.debind = function(){
    var bindable = this;

    if(!this._bound){
        // ToDo: This happens with actions, resolve.
        return;
    }
    this._bound = false;

    this.emit('debind');
    this.removeAllListeners('debind');
    delete Bindable.bindables[this.__iuid];
};
Bindable.prototype.destroy = function(){
    var bindable = this;

    this._destroyed = true;

    if(this._bound){
        this.debind();
    }

    for(var key in this){
        if(key !== 'parent' && this[key] instanceof Bindable && this[key]._bound){
            console.log(key);
        }
    }

    // Destroy bindables asynchonously.
    eventually(function(){

        bindable.emit('destroy');
        bindable.removeAllListeners('destroy');

        // Let any children bound to 'destroy' do their thing before actually destroying this.
        eventually(function(){
            bindable.gaffa = null;
            bindable.parent = null;
        });
    });
};

module.exports = Bindable;<commit_msg>Improved path resolution performance<commit_after>var createSpec = require('spec-js'),
    EventEmitter = require('events').EventEmitter,
    jsonConverter = require('./jsonConverter');

var stack = [];
function eventually(fn){
    stack.push(fn);
    if(stack.length === 1){
        setTimeout(function(){
            while(stack.length){
                stack.pop()();
            }
        },100);
    }
}

function getItemPath(item){
    var gedi = item.gaffa.gedi,
        paths = [],
        referencePath,
        referenceItem = item;

    while(referenceItem){

        // item.path should be a child ref after item.sourcePath
        if(referenceItem.path != null){
            paths.push(referenceItem.path);
            if(gedi.paths.isAbsolute(referenceItem.path)){
                break;
            }
        }

        // item.sourcePath is most root level path
        if(referenceItem.sourcePath != null){
            paths.push(gedi.paths.create(referenceItem.sourcePath));
        }

        referenceItem = referenceItem.parent;
    }

    return gedi.paths.resolve.apply(this, paths.reverse());
}

var iuid = 0;

function Bindable(){
    this.setMaxListeners(1000);
    // instance unique ID
    this.__iuid = iuid++;
}
Bindable = createSpec(Bindable, EventEmitter);
Bindable.bindables = {};
Bindable.getByIuid = function(id){
    return this.bindables[id];
};
Bindable.prototype.getPath = function(){
    return getItemPath(this);
};
Bindable.prototype.getDataAtPath = function(){
    if(!this.gaffa){
        return;
    }
    return this.gaffa.model.get(getItemPath(this));
};
Bindable.prototype.toJSON = function(){
    var tempObject = jsonConverter(this, this.__serialiseExclude__, this.__serialiseInclude__);

    return tempObject;
};

function setupCleanup(bindable, parent){
    var onDebind = bindable.debind.bind(bindable);
    parent.once('debind', onDebind);
    bindable.once('debind', function(){
        bindable.parent.removeListener('debind', onDebind);
    });

    var onDestroy = bindable.destroy.bind(bindable);
    parent.once('destroy', onDestroy);
    bindable.once('destroy', function(){
        bindable.parent.removeListener('destroy', onDestroy);
    });
}

Bindable.prototype.bind = function(parent){
    if(parent && !parent._bound){
        console.warn('Attempted to bind to a parent who was not bound.');
        return;
    }
    if(this._bound){
        this.debind();
        console.warn('Attempted to bind an already bound item.');
    }

    if(parent){
        this.gaffa = parent.gaffa;
        this.parent = parent;
        this._parentId = parent.__iuid;

        setupCleanup(this, parent);
    }

    this.updatePath();

    this._bound = true;
    Bindable.bindables[this.__iuid] = this;
    this.emit('bind');
    this.removeAllListeners('bind');
};
Bindable.prototype.getSourcePath = function(){
    return this.gaffa.gedi.paths.resolve(this.parent && this.parent.getPath(), this.sourcePath);
}
Bindable.prototype.updatePath = function(){
    if(!this.pathBinding){
        return;
    }

    var bindable = this,
        absoluteSourcePath = this.getSourcePath(),
        lastPath = this.path,
        gaffa = this.gaffa;

    function setPath(valueTokens){
        if(valueTokens){
            var valueToken = valueTokens[valueTokens.length - 1];
            bindable.path = valueToken.sourcePathInfo && valueToken.sourcePathInfo.path;
        }

        if(lastPath !== bindable.path && bindable._bound){
            bindable.debind();
            bindable.bind(bindable.parent);
        }
    }

    setPath(gaffa.gedi.get(this.pathBinding, absoluteSourcePath, bindable.scope, true));

    function handlePathChange(event){
        setPath(gaffa.model.get(bindable.pathBinding, bindable, bindable.scope, true));
    }

    gaffa.gedi.bind(this.pathBinding, handlePathChange, absoluteSourcePath);
    this.on('debind', function(){
        gaffa.gedi.debind(bindable.pathBinding, handlePathChange, absoluteSourcePath);
    });
};
Bindable.prototype.debind = function(){
    var bindable = this;

    if(!this._bound){
        // ToDo: This happens with actions, resolve.
        return;
    }
    this._bound = false;

    this.emit('debind');
    this.removeAllListeners('debind');
    delete Bindable.bindables[this.__iuid];
};
Bindable.prototype.destroy = function(){
    var bindable = this;

    this._destroyed = true;

    if(this._bound){
        this.debind();
    }

    for(var key in this){
        if(key !== 'parent' && this[key] instanceof Bindable && this[key]._bound){
            console.log(key);
        }
    }

    // Destroy bindables asynchonously.
    eventually(function(){

        bindable.emit('destroy');
        bindable.removeAllListeners('destroy');

        // Let any children bound to 'destroy' do their thing before actually destroying this.
        eventually(function(){
            bindable.gaffa = null;
            bindable.parent = null;
        });
    });
};

module.exports = Bindable;<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var util  = require('util');
var https = require('https');
var http  = require('http');
var url   = require('url');
var fs    = require('fs');
var ejs   = require('ejs');
var qs    = require('querystring');
var BaseHttpPoller = require('../http/baseHttpPoller');

// The http module lacks proxy support. Let's monkey-patch it.
require('../../proxy');

/**
 * HTTPS Poller, to check web pages served via SSL
 *
 * @param {Mixed} Poller Target (e.g. URL)
 * @param {Number} Poller timeout in milliseconds. Without response before this duration, the poller stops and executes the error callback.
 * @param {Function} Error/success callback
 * @api   public
 */
function HttpsPoller(target, timeout, callback) {
  HttpsPoller.super_.call(this, target, timeout, callback);
}

util.inherits(HttpsPoller, BaseHttpPoller);

HttpsPoller.type = 'https+oauth';

HttpsPoller.validateTarget = function(target) {
  return url.parse(target).protocol == 'https:';
};

getAccessToken = function(self, oauthEndpoint, params, credentials, onSuccess, onError) {
  try {
    var req = https.request(oauthEndpoint, function(res) {
      res.setEncoding('utf8');

      if(res.statusCode == 200) {
        body="";
        res.on('data', function (chunk) {
          body+=chunk;
        });

        res.on('end', function () {
          try {
            var parsed_body = JSON.parse(body);
            onSuccess(self, parsed_body.accessToken || parsed_body.access_token);
          } catch(err) {
            onError(self, {name: "InvalidResponseData", message: "oauth authentication failed, invalid data in response"});
          }
        });
      } else {
        onError(self, {name: "InvalidResponseStatus", message: "oauth authentication failed, invalid status ("+res.statusCode+") in response"});
      }
    });

    req.on('error', function (err) {
      onError(self, err);
    });
    if (typeof params != 'undefined') {
      req.write(qs.stringify(params), "utf-8");
    } else if (typeof credentials != 'undefined') {
      req.write(JSON.stringify(credentials), "utf-8");
    }
    req.end();
  } catch(err) {
    onError(self, {name: "UnknownError", message: "oauth authentication failed, an unknown error occured ("+err.message+")"});
  }
}

/**
 * Launch the actual polling
 *
 * @api   public
 */
HttpsPoller.prototype.poll = function(secure) {
  getAccessToken(this, this.target.endpoint, this.target.params, this.target.credentials, function(self, token) {
    HttpsPoller.super_.prototype.poll.call(self);
    secure = typeof secure !== 'undefined' ? secure : true;
    try {
      console.log(token);
      var options = {
        hostname: self.target.hostname,
        port: self.target.port,
        path: self.target.path,
        method: 'GET',
        headers: {
          "Authorization" : "Bearer " + token
        }
      };

      if (secure) {
        self.request = https.request(options, self.onResponseCallback.bind(self));
      } else {
        self.request = http.request(options, self.onResponseCallback.bind(self));
      }
    } catch(err) {
      return self.onErrorCallback(err);
    }
    self.request.on('error', self.onErrorCallback.bind(self));
    self.request.end();
  }, function(self, err) {
    HttpsPoller.super_.prototype.poll.call(self);
    return self.onErrorCallback(err);
  });
};

// see inherited function BaseHttpPoller.prototype.onResponseCallback
// see inherited function BaseHttpPoller.prototype.onErrorCallback

HttpsPoller.prototype.handleRedirectResponse = function(res) {
  this.debug(this.getTime() + "ms - Got redirect response to " + this.target.href);
  var target = url.parse(res.headers.location);
  if (!target.protocol) {
    // relative location header. This is incorrect but tolerated
    this.target = url.parse('http://' + this.target.hostname + res.headers.location);
    this.poll(false);
    return;
  }
  switch (target.protocol) {
    case 'https:':
      this.target = target;
      this.poll(true);
      break;
    case 'http:':
      this.target = target;
      this.poll(false);
      break;
    default:
      this.request.abort();
      this.onErrorCallback({ name: "WrongRedirectUrl", message: "Received redirection from https: to unsupported protocol " + target.protocol});
  }
  return;
};

module.exports = HttpsPoller;
<commit_msg>TOAD-1048, added support for OAuth2 implicit flow and client credentials flow<commit_after>/**
 * Module dependencies.
 */

var util = require('util');
var https = require('https');
var http = require('http');
var url = require('url');
var fs = require('fs');
var ejs = require('ejs');
var qs = require('querystring');
var BaseHttpPoller = require('../http/baseHttpPoller');

// The http module lacks proxy support. Let's monkey-patch it.
require('../../proxy');

/**
 * HTTPS Poller, to check web pages served via SSL
 *
 * @param {Mixed} Poller Target (e.g. URL)
 * @param {Number} Poller timeout in milliseconds. Without response before this duration, the poller stops and executes the error callback.
 * @param {Function} Error/success callback
 * @api   public
 */
function HttpsPoller(target, timeout, callback) {
    HttpsPoller.super_.call(this, target, timeout, callback);
}

util.inherits(HttpsPoller, BaseHttpPoller);

HttpsPoller.type = 'https+oauth';

HttpsPoller.validateTarget = function (target) {
    return url.parse(target).protocol == 'https:';
};

getAccessToken = function (self, oauthEndpoint, params, credentials, onSuccess, onError) {
    try {
        var req = https.request(oauthEndpoint, function (res) {
            res.setEncoding('utf8');

            if (res.statusCode < 400) {
                body = "";
                res.on('data', function (chunk) {
                    body += chunk;
                });

                res.on('end', function () {
                    try {
                        var token;
                        if (credentials != 'undefined' && credentials.response_type === 'token'){
                            token = res.headers.location.match("(?:access_token=)([A-Za-z0-9]+)")[1];
                        }
                        else {
                            var jsonBody = JSON.parse(body);
                            token = jsonBody.access_token || jsonBody.accessToken;
                        }
                        onSuccess(self, token);
                    } catch (err) {
                        onError(self, {
                            name: "InvalidResponseData",
                            message: "oauth authentication failed, invalid data in response"
                        });
                    }
                });
            } else {
                onError(self, {
                    name: "InvalidResponseStatus",
                    message: "oauth authentication failed, invalid status (" + res.statusCode + ") in response"
                });
            }
        });

        req.on('error', function (err) {
            onError(self, err);
        });
        if (typeof params != 'undefined') {
            req.write(qs.stringify(params), "utf-8");
        } else if (typeof credentials != 'undefined') {
            if (credentials.response_type || credentials.grant_type ) {
                req.write(qs.stringify(credentials), "utf-8");
            }
            else {
                req.write(JSON.stringify(credentials), "utf-8");
            }
        }
        req.end();
    } catch (err) {
        onError(self, {
            name: "UnknownError",
            message: "oauth authentication failed, an unknown error occured (" + err.message + ")"
        });
    }
}

/**
 * Launch the actual polling
 *
 * @api   public
 */
HttpsPoller.prototype.poll = function (secure) {
    getAccessToken(this, this.target.endpoint, this.target.params, this.target.credentials, function (self, token) {
        HttpsPoller.super_.prototype.poll.call(self);
        secure = typeof secure !== 'undefined' ? secure : true;
        try {
            var options = {
                hostname: self.target.hostname,
                port: self.target.port,
                path: self.target.path,
                method: 'GET',
                headers: {
                    "Authorization": "Bearer " + token
                }
            };

            if (secure) {
                self.request = https.request(options, self.onResponseCallback.bind(self));
            } else {
                self.request = http.request(options, self.onResponseCallback.bind(self));
            }
        } catch (err) {
            return self.onErrorCallback(err);
        }
        self.request.on('error', self.onErrorCallback.bind(self));
        self.request.end();
    }, function (self, err) {
        HttpsPoller.super_.prototype.poll.call(self);
        return self.onErrorCallback(err);
    });
};

// see inherited function BaseHttpPoller.prototype.onResponseCallback
// see inherited function BaseHttpPoller.prototype.onErrorCallback

HttpsPoller.prototype.handleRedirectResponse = function (res) {
    this.debug(this.getTime() + "ms - Got redirect response to " + this.target.href);
    var target = url.parse(res.headers.location);
    if (!target.protocol) {
        // relative location header. This is incorrect but tolerated
        this.target = url.parse('http://' + this.target.hostname + res.headers.location);
        this.poll(false);
        return;
    }
    switch (target.protocol) {
        case 'https:':
            this.target = target;
            this.poll(true);
            break;
        case 'http:':
            this.target = target;
            this.poll(false);
            break;
        default:
            this.request.abort();
            this.onErrorCallback({
                name: "WrongRedirectUrl",
                message: "Received redirection from https: to unsupported protocol " + target.protocol
            });
    }
    return;
};

module.exports = HttpsPoller;
<|endoftext|>


<commit_before>/* Janus Event Tracer (C) 2022 QXIP BV */

/* eslint-disable camelcase */
/* eslint-disable semi */
/* eslint quotes: 0 */
/* eslint-disable quote-props */
/* eslint-disable dot-notation */

var base_filter = require('@pastash/pastash').base_filter
var util = require('util')
var logger = require('@pastash/pastash').logger

const QuickLRU = require("quick-lru");

const recordCache = require("record-cache");
const fetch = require('cross-fetch');

const { PrometheusExporter } = require('@opentelemetry/exporter-prometheus');
const { MeterProvider } = require('@opentelemetry/sdk-metrics-base');

function nano_now (date) { return parseInt(date.toString().padEnd(16, '0')) }
function just_now (date) { return nano_now(date || new Date().getTime()) }
function spanid () { return Math.floor(10000000 + Math.random() * 90000000).toString() }

function FilterAppJanusTracer () {
  base_filter.BaseFilter.call(this);
  this.mergeConfig({
    name: 'AppJanusTracer',
    optional_params: ['debug', 'cacheSize', 'cacheAge', 'endpoint', 'bypass', 'port', 'metrics', 'service_name', 'interval'],
    default_values: {
      'cacheSize': 50000,
      'cacheAge': 60000,
      'endpoint': 'http://localhost:3100/tempo/api/push',
      'metrics': false,
      'service_name': 'pastash-janus',
      'interval': 10000,
      'port': 9090,
      'bypass': true,
      'debug': false
    },
    start_hook: this.start.bind(this)
  });
}

util.inherits(FilterAppJanusTracer, base_filter.BaseFilter);

FilterAppJanusTracer.prototype.start = async function (callback) {
  // Session cache
  var sessions = recordCache({
    maxSize: this.cacheSize,
    maxAge: this.cacheAge,
    onStale: false
  });
  this.sessions = sessions;
  this.lru = new QuickLRU({ maxSize: 10000, maxAge: 3600000, onEviction: false });

  if (this.metrics) {
    // Initialize Service
    const options = { port: this.port, startServer: true };
    const exporter = new PrometheusExporter(options);

    // Register the exporter
    this.meter = new MeterProvider({
      exporter,
      interval: this.interval
    }).getMeter(this.service_name)
    this.counters = {};

    // Register counters
    this.counters['s'] = this.meter.createUpDownCounter('sessions', {
      description: 'Session Counters'
    });
    this.counters['e'] = this.meter.createUpDownCounter('events', {
      description: 'Event Counters'
    });

    logger.info('Initialized Janus Prometheus Exporter :' + this.port + '/metrics');
  }
  logger.info('Initialized App Janus Span Tracer with: ' + this.endpoint);
  callback();
};

FilterAppJanusTracer.prototype.process = function (data) {
  // bypass
  if (this.bypass) this.emit('output', data)
  if (!data.message) return;
  var event = {};
  var line = JSON.parse(data.message);
  // logger.info('Incoming line', line.type, line.event)
  /* Ignore all other events */
  if (line.type === 128 || line.type === 8 || line.type === 16 || line.type === 32) return;
  logger.info('Filtered to 1, 2, 64', line.type, line.session_id, line.handle_id)
  /*
  TYPE 1

  Create Session and Destroy Session events are tracked
  */
  if (line.type == 1) {
    event = {
      name: line.event.name,
      event: line.event.name,
      session_id: line.session_id,
      traceId: line.session_id,
      id: line.session_id,
      spanId: spanid(),
      timestamp: line.timestamp || nano_now(new Date().getTime()),
      duration: 1000
    }
    /* CREATE event */
    if (event.name === "created") {
      // create root span
      this.lru.set(event.session_id, event);
      // start root trace, do not update
      this.sessions.add(event.session_id, just_now(event.timestamp));
      this.sessions.add('uuid_' + event.session_id, event.traceId)
      this.sessions.add('span_' + event.session_id, event.spanId)
      this.sessions.add('parent_' + event.session_id, event.spanId)
      if (this.metrics) this.counters['s'].add(1, line.event);
    /* DESTROY event */
    } else if (event.name === "destroyed") {
      const createEvent = this.lru.get(event.session_id)
      createEvent.duration = just_now(event.timestamp) - just_now(createEvent.timestamp);
      /* name the event Session */
      createEvent.name = "Session " + event.session_id
      // delete root span
      this.lru.delete(event.session_id);
      // end root trace
      this.sessions.remove(event.session_id);
      this.sessions.remove('uuid_' + event.session_id);
      this.sessions.remove('span_' + event.session_id, event.spanId)
      this.sessions.remove('parent_' + event.session_id, event.spanId)
      if (this.metrics) this.counters['s'].add(-1, line.event);
      logger.info('type 1 destroyed sending', createEvent)
      tracegen(createEvent, this.endpoint)
      event.duration = 100
      event.name = "Destroyed " + event.id
      tracegen(event, this.endpoint)
    }
  /*
  TYPE 2

  Client Attachment and Detachment is tracked
  */
  } else if (line.type == 2) {
    event = {
      name: line.event.name,
      event: line.event.name,
      session_id: line.session_id,
      id: line.session_id,
      spanId: spanid(),
      timestamp: line.timestamp || nano_now(new Date().getTime())
    }
    if (!line.event.data) return;
    if (event.name === "attached") {
      event.parentId = this.sessions.get("parent_" + event.session_id, 1)[0]
      event.traceId = event.session_id
      this.lru.set("att_" + event.session_id, event);
    } else if (event.name === "detached") {
      const attEvent = this.lru.get("att_" + event.session_id)
      attEvent.duration = just_now(event.timestamp) - just_now(attEvent.timestamp)
      this.lru.delete("att_" + event.session_id)
      logger.info('type 2 detached sending', event)
      tracegen(attEvent, this.endpoint)
      event.parentId = this.sessions.get("parent_" + event.session_id, 1)[0]
      event.traceId = event.session_id
      event.duration = 0
      tracegen(event, this.endpoint)
    }

  /*
  TYPE 64

  Users Joining or Leaving Sessions
  */
  } else if (line.type == 64) {
    event = {
      name: line.event.plugin,
      event: line.event.data.event,
      id: line.event.data.id,
      spanId: spanid(),
      room: line.event.data.room,
      timestamp: line.timestamp || nano_now(new Date().getTime())
    }
    if (!line.event.data) return;

    logger.info("trace 64: ", line)
    if (event.event === "joined") {
      event.display = line.data.display
      event.session_id = line.session_id
      event.traceId = event.session_id
      event.parentId = this.sessions.get('parent_' + event.session_id, 1)[0] || spanid();
      console.log("JOIN ", event)
      // session_id, handle_id, opaque_id, event.data.id
      // correlate: session_id --> event.data.id
      this.lru.set("join_" + event.id, event);
      // increase tag counter
      if (this.metrics) this.counters['e'].add(1, line.event.data);
    } else if (event.event === "configured") {
      /* Set start time of configured as start of join,
         emit span when published is received */
      event.session_id = line.session_id
      event.traceId = event.session_id
      event.parentId = this.sessions.get('parent_' + event.session_id, 1)[0] || spanid();
      /* emit configured event */
      const joinEvent = this.lru.get("join_" + event.id)
      event.duration = just_now(event.timestamp) - just_now(joinEvent.timestamp)
      event.timestamp = joinEvent.timestamp
      event.name = "Configured " + event.id + ", Room " + event.room
      logger.info('type 64 configured sending', event)
      tracegen(event, this.endpoint)
    } else if (event.event === "published") {
      event.session_id = line.session_id
      event.traceId = event.session_id
      event.parentId = this.sessions.get('parent_' + event.session_id, 1)[0] || spanid();
      this.lru.set("pub_" + event.id, event);
    } else if (event.event === "unpublished") {
      // correlate: event.data.id --> session_id
      const pubEvent = this.lru.get("pub_" + event.id)
      if (!pubEvent) return
      pubEvent.duration = just_now(event.timestamp) - just_now(pubEvent.timestamp);
      pubEvent.name = "Published " + event.id + ", Room " + event.room
      this.lru.delete("pub_" + event.id)
      logger.info('type 64 unpublished sending', pubEvent)
      tracegen(pubEvent, this.endpoint)
      event.duration = 1
      event.parentId = this.sessions.get("parent_" + event.session_id, 1)[0]
      event.traceId = event.session_id
      tracegen(event, this.endpoint)
    } else if (event.event === "leaving") {
      // correlate: event.data.id --> session_id
      const joinEvent = this.lru.get('join_' + event.id)
      joinEvent.duration = just_now(event.timestamp) - just_now(joinEvent.timestamp)
      joinEvent.name = "User " + event.id + " / " + joinEvent.display + ", Room " + event.room
      this.lru.delete("join_" + event.id)
      // decrease tag counter
      if (this.metrics) this.counters['e'].add(-1, line.event.data);
      logger.info('type 64 leaving sending', event)
      tracegen(joinEvent, this.endpoint)
      event.duration = 1
      event.parentId = this.sessions.get("parent_" + event.session_id, 1)[0]
      event.traceId = joinEvent.session_id
      tracegen(event, this.endpoint)
    }
  }
};

exports.create = function () {
  return new FilterAppJanusTracer();
};

// TODO: replace trace mocker with opentelemetry-js
// Link: https://github.com/open-telemetry/opentelemetry-js/blob/main/packages/opentelemetry-exporter-zipkin/README.md

async function tracegen (event, endpoint) {
  // mock a zipkin span
  var trace = [{
    "id": event.spanId || spanid(),
    "traceId": event.traceId.toString(),
    "timestamp": nano_now(event.timestamp),
    "duration": event.duration,
    "name": event.event,
    "localEndpoint": {
      "serviceName": event.name
    }
  }]
  if (event.parentId) { trace[0].parentId = event.parentId }
  if (event.tags) {
    trace[0].tags = event.tags
  } else {
    trace[0].tags = { event: 'hello' }
  }

  logger.info("trace: ", trace);
  // send event to endpoint
  if (endpoint) {
    const response = fetch(endpoint, {
      method: 'POST',
      body: JSON.stringify(trace),
      headers: { 'Content-Type': 'application/json' }
    })
      .then(res => {
        return res
      })
      .catch(err => {
        logger.error(err)
      });
    if (this.debug) logger.info(response);
  }
}
<commit_msg>possible fix<commit_after>/* Janus Event Tracer (C) 2022 QXIP BV */

/* eslint-disable camelcase */
/* eslint-disable semi */
/* eslint quotes: 0 */
/* eslint-disable quote-props */
/* eslint-disable dot-notation */

var base_filter = require('@pastash/pastash').base_filter
var util = require('util')
var logger = require('@pastash/pastash').logger

const QuickLRU = require("quick-lru");

const recordCache = require("record-cache");
const fetch = require('cross-fetch');

const { PrometheusExporter } = require('@opentelemetry/exporter-prometheus');
const { MeterProvider } = require('@opentelemetry/sdk-metrics-base');

function nano_now (date) { return parseInt(date.toString().padEnd(16, '0')) }
function just_now (date) { return nano_now(date || new Date().getTime()) }
function spanid () { return Math.floor(10000000 + Math.random() * 90000000).toString() }

function FilterAppJanusTracer () {
  base_filter.BaseFilter.call(this);
  this.mergeConfig({
    name: 'AppJanusTracer',
    optional_params: ['debug', 'cacheSize', 'cacheAge', 'endpoint', 'bypass', 'port', 'metrics', 'service_name', 'interval'],
    default_values: {
      'cacheSize': 50000,
      'cacheAge': 60000,
      'endpoint': 'http://localhost:3100/tempo/api/push',
      'metrics': false,
      'service_name': 'pastash-janus',
      'interval': 10000,
      'port': 9090,
      'bypass': true,
      'debug': false
    },
    start_hook: this.start.bind(this)
  });
}

util.inherits(FilterAppJanusTracer, base_filter.BaseFilter);

FilterAppJanusTracer.prototype.start = async function (callback) {
  // Session cache
  var sessions = recordCache({
    maxSize: this.cacheSize,
    maxAge: this.cacheAge,
    onStale: false
  });
  this.sessions = sessions;
  this.lru = new QuickLRU({ maxSize: 10000, maxAge: 3600000, onEviction: false });

  if (this.metrics) {
    // Initialize Service
    const options = { port: this.port, startServer: true };
    const exporter = new PrometheusExporter(options);

    // Register the exporter
    this.meter = new MeterProvider({
      exporter,
      interval: this.interval
    }).getMeter(this.service_name)
    this.counters = {};

    // Register counters
    this.counters['s'] = this.meter.createUpDownCounter('sessions', {
      description: 'Session Counters'
    });
    this.counters['e'] = this.meter.createUpDownCounter('events', {
      description: 'Event Counters'
    });

    logger.info('Initialized Janus Prometheus Exporter :' + this.port + '/metrics');
  }
  logger.info('Initialized App Janus Span Tracer with: ' + this.endpoint);
  callback();
};

FilterAppJanusTracer.prototype.process = function (data) {
  // bypass
  if (this.bypass) this.emit('output', data)
  if (!data.message) return;
  var event = {};
  var line = JSON.parse(data.message);
  // logger.info('Incoming line', line.type, line.event)
  /* Ignore all other events */
  if (line.type === 128 || line.type === 8 || line.type === 16 || line.type === 32) return;
  logger.info('Filtered to 1, 2, 64', line.type, line.session_id, line.handle_id)
  /*
  TYPE 1

  Create Session and Destroy Session events are tracked
  */
  if (line.type == 1) {
    event = {
      name: line.event.name,
      event: line.event.name,
      session_id: line.session_id,
      traceId: line.session_id,
      id: line.session_id,
      spanId: spanid(),
      timestamp: line.timestamp || nano_now(new Date().getTime()),
      duration: 1000
    }
    /* CREATE event */
    if (event.name === "created") {
      // create root span
      this.lru.set(event.session_id, event);
      // start root trace, do not update
      this.sessions.add(event.session_id, just_now(event.timestamp));
      this.sessions.add('uuid_' + event.session_id, event.traceId)
      this.sessions.add('span_' + event.session_id, event.spanId)
      this.sessions.add('parent_' + event.session_id, event.spanId)
      if (this.metrics) this.counters['s'].add(1, line.event);
    /* DESTROY event */
    } else if (event.name === "destroyed") {
      const createEvent = this.lru.get(event.session_id)
      createEvent.duration = just_now(event.timestamp) - just_now(createEvent.timestamp);
      /* name the event Session */
      createEvent.name = "Session " + event.session_id
      // delete root span
      this.lru.delete(event.session_id);
      // end root trace
      this.sessions.remove(event.session_id);
      this.sessions.remove('uuid_' + event.session_id);
      this.sessions.remove('span_' + event.session_id, event.spanId)
      this.sessions.remove('parent_' + event.session_id, event.spanId)
      if (this.metrics) this.counters['s'].add(-1, line.event);
      logger.info('type 1 destroyed sending', createEvent)
      tracegen(createEvent, this.endpoint)
      event.duration = 100
      event.name = "Destroyed " + event.id
      tracegen(event, this.endpoint)
    }
  /*
  TYPE 2

  Client Attachment and Detachment is tracked
  */
  } else if (line.type == 2) {
    event = {
      name: line.event.name,
      event: line.event.name,
      session_id: line.session_id,
      id: line.session_id,
      spanId: spanid(),
      timestamp: line.timestamp || nano_now(new Date().getTime())
    }
    if (!line.event.data) return;
    if (event.name === "attached") {
      event.parentId = this.sessions.get("parent_" + event.session_id, 1)[0]
      event.traceId = event.session_id
      this.lru.set("att_" + event.session_id, event);
    } else if (event.name === "detached") {
      const attEvent = this.lru.get("att_" + event.session_id)
      attEvent.duration = just_now(event.timestamp) - just_now(attEvent.timestamp)
      this.lru.delete("att_" + event.session_id)
      logger.info('type 2 detached sending', event)
      tracegen(attEvent, this.endpoint)
      event.parentId = this.sessions.get("parent_" + event.session_id, 1)[0]
      event.traceId = event.session_id
      event.duration = 0
      tracegen(event, this.endpoint)
    }

  /*
  TYPE 64

  Users Joining or Leaving Sessions
  */
  } else if (line.type == 64) {
    event = {
      name: line.event.plugin,
      event: line.event.data.event,
      id: line.event.data.id,
      spanId: spanid(),
      room: line.event.data.room,
      timestamp: line.timestamp || nano_now(new Date().getTime())
    }
    if (!line.event.data) return;

    logger.info("trace 64: ", line)
    if (event.event === "joined") {
      event.display = line.event.data.display
      event.session_id = line.session_id
      event.traceId = event.session_id
      event.parentId = this.sessions.get('parent_' + event.session_id, 1)[0] || spanid();
      console.log("JOIN ", event)
      // session_id, handle_id, opaque_id, event.data.id
      // correlate: session_id --> event.data.id
      this.lru.set("join_" + event.id, event);
      // increase tag counter
      if (this.metrics) this.counters['e'].add(1, line.event.data);
    } else if (event.event === "configured") {
      /* Set start time of configured as start of join,
         emit span when published is received */
      event.session_id = line.session_id
      event.traceId = event.session_id
      event.parentId = this.sessions.get('parent_' + event.session_id, 1)[0] || spanid();
      /* emit configured event */
      const joinEvent = this.lru.get("join_" + event.id)
      event.duration = just_now(event.timestamp) - just_now(joinEvent.timestamp)
      event.timestamp = joinEvent.timestamp
      event.name = "Configured " + event.id + ", Room " + event.room
      logger.info('type 64 configured sending', event)
      tracegen(event, this.endpoint)
    } else if (event.event === "published") {
      event.session_id = line.session_id
      event.traceId = event.session_id
      event.parentId = this.sessions.get('parent_' + event.session_id, 1)[0] || spanid();
      this.lru.set("pub_" + event.id, event);
    } else if (event.event === "unpublished") {
      // correlate: event.data.id --> session_id
      const pubEvent = this.lru.get("pub_" + event.id)
      if (!pubEvent) return
      pubEvent.duration = just_now(event.timestamp) - just_now(pubEvent.timestamp);
      pubEvent.name = "Published " + event.id + ", Room " + event.room
      this.lru.delete("pub_" + event.id)
      logger.info('type 64 unpublished sending', pubEvent)
      tracegen(pubEvent, this.endpoint)
      event.duration = 1
      event.parentId = this.sessions.get("parent_" + event.session_id, 1)[0]
      event.traceId = event.session_id
      tracegen(event, this.endpoint)
    } else if (event.event === "leaving") {
      // correlate: event.data.id --> session_id
      try {
        const joinEvent = this.lru.get('join_' + event.id)
        joinEvent.duration = just_now(event.timestamp) - just_now(joinEvent.timestamp)
        joinEvent.name = "User " + event.id + " / " + joinEvent.display + ", Room " + event.room
        this.lru.delete("join_" + event.id)
        logger.info('type 64 leaving sending', event)
        tracegen(joinEvent, this.endpoint)
        event.duration = 1
        event.parentId = this.sessions.get("parent_" + event.session_id, 1)[0]
        event.traceId = joinEvent.session_id
        tracegen(event, this.endpoint)
      } catch (e) {
        console.log(e)
        event.duration = 1
        event.parentId = this.sessions.get("parent_" + event.session_id, 1)[0]
        event.traceId = "1234"
        tracegen(event, this.endpoint)
      }
      // decrease tag counter
      if (this.metrics) this.counters['e'].add(-1, line.event.data);
    }
  }
};

exports.create = function () {
  return new FilterAppJanusTracer();
};

// TODO: replace trace mocker with opentelemetry-js
// Link: https://github.com/open-telemetry/opentelemetry-js/blob/main/packages/opentelemetry-exporter-zipkin/README.md

async function tracegen (event, endpoint) {
  // mock a zipkin span
  var trace = [{
    "id": event.spanId || spanid(),
    "traceId": event.traceId.toString(),
    "timestamp": nano_now(event.timestamp),
    "duration": event.duration,
    "name": event.event,
    "localEndpoint": {
      "serviceName": event.name
    }
  }]
  if (event.parentId) { trace[0].parentId = event.parentId }
  if (event.tags) {
    trace[0].tags = event.tags
  } else {
    trace[0].tags = { event: 'hello' }
  }

  logger.info("trace: ", trace);
  // send event to endpoint
  if (endpoint) {
    const response = fetch(endpoint, {
      method: 'POST',
      body: JSON.stringify(trace),
      headers: { 'Content-Type': 'application/json' }
    })
      .then(res => {
        return res
      })
      .catch(err => {
        logger.error(err)
      });
    if (this.debug) logger.info(response);
  }
}
<|endoftext|>


<commit_before>'use strict';

module.exports = {
	db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/wave-website',
	assets: {
		lib: {
			css: [
                'public/lib/bootswatch/flatly/bootstrap.min.css',
                'public/lib/components-font-awesome/css/font-awesome.min.css',
			],
			js: [
                'public/lib/ng-file-upload/angular-file-upload-shim.js',
                'public/lib/angular/angular.js',
                'public/lib/angular-resource/angular-resource.js',
                'public/lib/angular-cookies/angular-cookies.js',
                'public/lib/angular-animate/angular-animate.js',
                'public/lib/angular-touch/angular-touhomech.js',
                'public/lib/angular-sanitize/angular-sanitize.js',
                'public/lib/angular-ui-router/release/angular-ui-router.js',
                'public/lib/angular-ui-utils/ui-utils.js',
                'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
                'public/lib/ng-file-upload/angular-file-upload.js',
                'public/lib/textAngular/src/textAngular-sanitize.js',
                'public/lib/textAngular/src/textAngularSetup.js',
                'public/lib/textAngular/src/textAngular.js',
                'public/lib/rangy/rangy-core.js',
                'public/lib/jquery/dist/jquery.js',
                'public/lib/ng-grid/build/ng-grid.js'
			]
		},
		css: 'public/dist/application.min.css',
		js: 'public/dist/application.min.js'
	},
	facebook: {
		clientID: process.env.FACEBOOK_ID || 'APP_ID',
		clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
		callbackURL: '/auth/facebook/callback'
	},
	twitter: {
		clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
		clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
		callbackURL: '/auth/twitter/callback'
	},
	google: {
		clientID: process.env.GOOGLE_ID || 'APP_ID',
		clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
		callbackURL: '/auth/google/callback'
	},
	linkedin: {
		clientID: process.env.LINKEDIN_ID || 'APP_ID',
		clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
		callbackURL: '/auth/linkedin/callback'
	},
	mailer: {
		from: process.env.MAILER_FROM || 'MAILER_FROM',
		options: {
			service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
			auth: {
				user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
				pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
			}
		}
	}
};<commit_msg>Changed production css to minified version.<commit_after>'use strict';

module.exports = {
	db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/wave-website',
	assets: {
		lib: {
			css: [
                'public/lib/bootswatch/flatly/bootstrap.min.css',
                'public/lib/components-font-awesome/css/font-awesome.min.css',
			],
			js: [
                'public/lib/ng-file-upload/angular-file-upload-shim.min.js',
                'public/lib/angular/angular.min.js',
                'public/lib/angular-resource/angular-resource.min.js',
                'public/lib/angular-cookies/angular-cookies.min.js',
                'public/lib/angular-animate/angular-animate.min.js',
                'public/lib/angular-touch/angular-touhomech.min.js',
                'public/lib/angular-sanitize/angular-sanitize.min.js',
                'public/lib/angular-ui-router/release/angular-ui-router.min.js',
                'public/lib/angular-ui-utils/ui-utils.min.js',
                'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js',
                'public/lib/ng-file-upload/angular-file-upload.min.js',
                'public/lib/textAngular/src/textAngular-sanitize.min.js',
                'public/lib/textAngular/src/textAngularSetup.min.js',
                'public/lib/textAngular/src/textAngular.min.js',
                'public/lib/rangy/rangy-core.min.js',
                'public/lib/jquery/dist/jquery.min.js',
                'public/lib/ng-grid/build/ng-grid.min.js'
			]
		},
		css: 'public/dist/application.min.css',
		js: 'public/dist/application.min.js'
	},
	facebook: {
		clientID: process.env.FACEBOOK_ID || 'APP_ID',
		clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
		callbackURL: '/auth/facebook/callback'
	},
	twitter: {
		clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
		clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
		callbackURL: '/auth/twitter/callback'
	},
	google: {
		clientID: process.env.GOOGLE_ID || 'APP_ID',
		clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
		callbackURL: '/auth/google/callback'
	},
	linkedin: {
		clientID: process.env.LINKEDIN_ID || 'APP_ID',
		clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
		callbackURL: '/auth/linkedin/callback'
	},
	mailer: {
		from: process.env.MAILER_FROM || 'MAILER_FROM',
		options: {
			service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
			auth: {
				user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
				pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
			}
		}
	}
};<|endoftext|>


<commit_before>const crypto = require("crypto");

const ivLength = 16;
const saltLength = 64;
const tagLength = 16;
const tagPosition = saltLength + ivLength;
const inputPosition = tagPosition + tagLength;

module.exports.encrypt = (input, encryptionKey) => {
  try {
    const iv = crypto.randomBytes(ivLength);
    const salt = crypto.randomBytes(saltLength);
    const key = crypto.pbkdf2Sync(encryptionKey, salt, 100000, 32, "sha512");
    const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
    const encrypted = Buffer.concat([
      cipher.update(input, "utf8"),
      cipher.final(),
    ]);
    const tag = cipher.getAuthTag();
    return Buffer.concat([salt, iv, tag, encrypted]).toString("hex");
  } catch (error) {
    return "";
  }
};

module.exports.decrypt = (output, encryptionKey) => {
  try {
    const stringValue = Buffer.from(output, "hex");
    const salt = stringValue.slice(0, saltLength);
    const iv = stringValue.slice(saltLength, tagPosition);
    const tag = stringValue.slice(tagPosition, inputPosition);
    const encrypted = stringValue.slice(inputPosition);
    const key = crypto.pbkdf2Sync(encryptionKey, salt, 100000, 32, "sha512");
    const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
    decipher.setAuthTag(tag);
    return decipher.update(encrypted) + decipher.final("utf8");
  } catch (error) {
    return "";
  }
};
<commit_msg>log encryption lib errors<commit_after>const crypto = require("crypto");
const logging = require("./logging");

const ivLength = 16;
const saltLength = 64;
const tagLength = 16;
const tagPosition = saltLength + ivLength;
const inputPosition = tagPosition + tagLength;

module.exports.encrypt = (input, encryptionKey) => {
  try {
    const iv = crypto.randomBytes(ivLength);
    const salt = crypto.randomBytes(saltLength);
    const key = crypto.pbkdf2Sync(encryptionKey, salt, 100000, 32, "sha512");
    const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
    const encrypted = Buffer.concat([
      cipher.update(input, "utf8"),
      cipher.final(),
    ]);
    const tag = cipher.getAuthTag();
    return Buffer.concat([salt, iv, tag, encrypted]).toString("hex");
  } catch (error) {
    logging.error("encryption failed", error);
    return "";
  }
};

module.exports.decrypt = (output, encryptionKey) => {
  try {
    const stringValue = Buffer.from(output, "hex");
    const salt = stringValue.slice(0, saltLength);
    const iv = stringValue.slice(saltLength, tagPosition);
    const tag = stringValue.slice(tagPosition, inputPosition);
    const encrypted = stringValue.slice(inputPosition);
    const key = crypto.pbkdf2Sync(encryptionKey, salt, 100000, 32, "sha512");
    const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
    decipher.setAuthTag(tag);
    return decipher.update(encrypted) + decipher.final("utf8");
  } catch (error) {
    logging.error("decryption failed", error);
    return "";
  }
};
<|endoftext|>