<commit_before>(function() {

	var dayNamesInWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  	var shortDayNamessInWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  	var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  	var shortMonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

	Date.prototype.format = function(format) {
		var pattern = '',
			returnValue = '',
			count = 0;

		for(var i = 0; i < format.length; i++) {
			var currentPattern = format.charAt(i);
            var nextPattern = format.charAt(i + 1);

            pattern += currentPattern;
            switch (pattern) {
            	//year
            	case 'y':
            		count++;
	            	if(nextPattern === 'y') {
	            		pattern = '';
	            		break;
	            	}
	            	if (count == 2) {
	            		returnValue += ('' + this.getFullYear()).substr(2);
	            	} else {
	            		returnValue += this.getFullYear();
	            	}
	            	pattern = '';
	            	count = 0;
	            	break;

            	//month
	            case 'M':
            		count++;
	            	if(nextPattern === 'M') {
	            		pattern = '';
	            		break;
	            	}
	            	if (count < 3) {
	            		if (this.getMonth() < 9 && count > 1) {
	            			returnValue += '0';
	            		}
	            		returnValue += (this.getMonth() + 1);
	            	} else if (count == 3) {
	            		returnValue += shortMonths[this.getMonth()];
	            	} else {
	            		returnValue += months[this.getMonth()];
	            	}
	            	pattern = '';
	            	count = 0;
	            	break;
            	//day
            	case 'd':
            		count++;
	            	if(nextPattern === 'd') {
	            		if (this.getDate() < 10) {
	            			if (count >= 1) {
	            				returnValue += '0';
	            			}
	            		} else {
	            			if (count > 1) {
	            				returnValue += '0';
	            			}
	            		}
	            		pattern = '';
	            		break;
	            	}
	            	returnValue += this.getDate();
	            	pattern = '';
	            	count = 0;
	            	break;
	            case 'D':
		            var start = new Date(this.getFullYear(), 0, 0);
		            var diff = this - start;
		            var oneDay = 1000 * 60 * 60 * 24;
	            	returnValue += Math.ceil(diff / oneDay);
	            	pattern = '';
	            	break;
	            case 'F':
	            	count++;
	            	if(nextPattern === 'F') {
	            		if (count >= 1) {
	            			returnValue += '0';
	            		}
	            		pattern = '';
	            		break;
	            	}
	            	var d = new Date(this.valueOf()),
	            		dayOfWeekInMonth = 0,
	            		month = this.getMonth();

	            	while (d.getMonth() === month) {
	            		dayOfWeekInMonth++;
	            		d.setDate(d.getDate() - 7);
	            	}

	            	returnValue += dayOfWeekInMonth;
	            	pattern = '';
	            	count = 0;
	            	break;
	            case 'E':
            		count++;
	            	if(nextPattern === 'E') {
	            		pattern = '';
	            		break;
	            	}
	            	if (count > 3) {
	            		returnValue += dayNamesInWeek[this.getDay()];
	            	} else {
	            		returnValue += shortDayNamessInWeek[this.getDay()];
	            	}
	            	pattern = '';
	            	count = 0;
	            	break;
	            case 'u':
            		count++;
	            	if(nextPattern === 'u') {
	            		if (count >= 1) {
	            			returnValue += '0';
	            		}
	            		pattern = '';
	            		break;
	            	}
	            	if (this.getDay() == 0) {
	            		returnValue += 7;
	            	} else {
	            		returnValue += this.getDay();
	            	}
	            	pattern = '';
	            	count = 0;
	            	break;
            	default:
	            	returnValue += currentPattern;
	            	pattern = '';
	            	break;
            }
        }
        return returnValue;
    };

}).call(this);<commit_msg>add am/pm marker<commit_after>(function() {

	var dayNamesInWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  	var shortDayNamessInWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  	var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  	var shortMonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

	Date.prototype.format = function(format) {
		var pattern = '',
			returnValue = '',
			count = 0;

		for(var i = 0; i < format.length; i++) {
			var currentPattern = format.charAt(i);
            var nextPattern = format.charAt(i + 1);

            pattern += currentPattern;
            switch (pattern) {
            	//year
            	case 'y':
            		count++;
	            	if(nextPattern === 'y') {
	            		pattern = '';
	            		break;
	            	}
	            	if (count == 2) {
	            		returnValue += ('' + this.getFullYear()).substr(2);
	            	} else {
	            		returnValue += this.getFullYear();
	            	}
	            	pattern = '';
	            	count = 0;
	            	break;

            	//month
	            case 'M':
            		count++;
	            	if(nextPattern === 'M') {
	            		pattern = '';
	            		break;
	            	}
	            	if (count < 3) {
	            		if (this.getMonth() < 9 && count > 1) {
	            			returnValue += '0';
	            		}
	            		returnValue += (this.getMonth() + 1);
	            	} else if (count == 3) {
	            		returnValue += shortMonths[this.getMonth()];
	            	} else {
	            		returnValue += months[this.getMonth()];
	            	}
	            	pattern = '';
	            	count = 0;
	            	break;
            	//day
            	case 'd':
            		count++;
	            	if(nextPattern === 'd') {
	            		if (this.getDate() < 10) {
	            			if (count >= 1) {
	            				returnValue += '0';
	            			}
	            		} else {
	            			if (count > 1) {
	            				returnValue += '0';
	            			}
	            		}
	            		pattern = '';
	            		break;
	            	}
	            	returnValue += this.getDate();
	            	pattern = '';
	            	count = 0;
	            	break;
	            case 'D':
		            var start = new Date(this.getFullYear(), 0, 0);
		            var diff = this - start;
		            var oneDay = 1000 * 60 * 60 * 24;
	            	returnValue += Math.ceil(diff / oneDay);
	            	pattern = '';
	            	break;
	            case 'F':
	            	count++;
	            	if(nextPattern === 'F') {
	            		if (count >= 1) {
	            			returnValue += '0';
	            		}
	            		pattern = '';
	            		break;
	            	}
	            	var d = new Date(this.valueOf()),
	            		dayOfWeekInMonth = 0,
	            		month = this.getMonth();

	            	while (d.getMonth() === month) {
	            		dayOfWeekInMonth++;
	            		d.setDate(d.getDate() - 7);
	            	}

	            	returnValue += dayOfWeekInMonth;
	            	pattern = '';
	            	count = 0;
	            	break;
	            case 'E':
            		count++;
	            	if(nextPattern === 'E') {
	            		pattern = '';
	            		break;
	            	}
	            	if (count > 3) {
	            		returnValue += dayNamesInWeek[this.getDay()];
	            	} else {
	            		returnValue += shortDayNamessInWeek[this.getDay()];
	            	}
	            	pattern = '';
	            	count = 0;
	            	break;
	            case 'u':
            		count++;
	            	if(nextPattern === 'u') {
	            		if (count >= 1) {
	            			returnValue += '0';
	            		}
	            		pattern = '';
	            		break;
	            	}
	            	if (this.getDay() == 0) {
	            		returnValue += 7;
	            	} else {
	            		returnValue += this.getDay();
	            	}
	            	pattern = '';
	            	count = 0;
	            	break;
	            //time
	            case 'a':
	            	if(nextPattern === 'a') {
	            		pattern = '';
	            		break;
	            	}
	            	if (this.getHours() < 12) {
	            		returnValue += 'AM';
	            	} else {
	            		returnValue += 'PM';
	            	}
	            	pattern = '';
	            	count = 0;
	            	break;
            	default:
	            	returnValue += currentPattern;
	            	pattern = '';
	            	break;
            }
        }
        return returnValue;
    };

}).call(this);<|endoftext|>


<commit_before>const output = require('../output');
const inquirer = require('inquirer');
const fs = require('fs');
const path = require('path');
const colors = require('chalk');
const { fileExists, ucfirst, lcfirst } = require('../utils');
const mkdirp = require('mkdirp');
const {
  getConfig, getTestRoot, updateConfig, safeFileWrite,
} = require('./utils');

const testTemplate = `
Feature('{{feature}}');

Scenario('test something', ({{actor}}) => {

});
`;

// generates empty test
module.exports.test = function (genPath) {
  const testsPath = getTestRoot(genPath);
  const config = getConfig(testsPath);
  if (!config) return;

  output.print('Creating a new test...');
  output.print('----------------------');

  const defaultExt = config.tests.match(/\*(.*?)$/[1])[0] || '_test.js';

  inquirer.prompt([
    {
      type: 'input',
      message: 'Filename of a test',
      name: 'filename',
    },
    {
      type: 'input',
      name: 'feature',
      message: 'Feature which is being tested',
      default(answers) {
        return ucfirst(answers.filename).replace('_', ' ').replace('-', ' ');
      },
    },
  ], (result) => {
    const testFilePath = path.dirname(path.join(testsPath, config.tests)).replace(/\*\*$/, '');
    let testFile = path.join(testFilePath, result.filename);
    const ext = path.extname(testFile);
    if (!ext) testFile += defaultExt;
    const dir = path.dirname(testFile);
    if (!fileExists(dir)) mkdirp.sync(dir);
    let testContent = testTemplate.replace('{{feature}}', result.feature);

    // can be confusing before translations are documented
    // commenting it out:

    // let container = require('../container');
    // container.create(config);
    // testContent = testContent.replace('{{actor}}', container.translation().I);
    testContent = testContent.replace('{{actor}}', 'I');

    if (!safeFileWrite(testFile, testContent)) return;
    output.success(`Test for ${result.filename} was created in ${testFile}`);
  });
};

const pageObjectTemplate = `
const I = actor();

module.exports = {

  // insert your locators and methods here
}
`;

module.exports.pageObject = function (genPath, opts) {
  const testsPath = getTestRoot(genPath);
  const config = getConfig(testsPath);
  const kind = opts.T || 'page';
  if (!config) return;

  output.print(`Creating a new ${kind} object`);
  output.print('--------------------------');

  inquirer.prompt([{
    type: 'input',
    name: 'name',
    message: `Name of a ${kind} object`,
  }, {
    type: 'input',
    name: 'filename',
    message: 'Where should it be stored',
    default: answers => `./${kind}s/${answers.name}.js`,
  }], (result) => {
    const pageObjectFile = path.join(testsPath, result.filename);
    const dir = path.dirname(pageObjectFile);
    if (!fileExists(dir)) fs.mkdirSync(dir);

    let actor = 'actor';
    if (config.include.I) {
      let actorPath = config.include.I;
      if (actorPath.charAt(0) === '.') { // relative path
        actorPath = path.relative(dir, path.dirname(path.join(testsPath, actorPath))) + actorPath.substring(1); // get an upper level
      }
      actor = `require('${actorPath}')`;
    }
    if (!safeFileWrite(pageObjectFile, pageObjectTemplate.replace('{{actor}}', actor))) return;
    const name = lcfirst(result.name) + ucfirst(kind);
    config.include[name] = result.filename;
    updateConfig(testsPath, config);
    output.success(`${ucfirst(kind)} object for ${result.name} was created in ${pageObjectFile}`);
    output.print(`Use ${output.colors.bold(name)} as parameter in test scenarios to access it`);
  });
};

const helperTemplate = `
class {{name}} extends Helper {

  // before/after hooks
  _before() {
    // remove if not used
  }

  _after() {
    // remove if not used
  }

  // add custom methods here
  // If you need to access other helpers
  // use: this.helpers['helperName']

}

module.exports = {{name}};
`;

module.exports.helper = function (genPath) {
  const testsPath = getTestRoot(genPath);
  const config = getConfig(testsPath);

  output.print('Creating a new helper');
  output.print('--------------------------');

  inquirer.prompt([{
    type: 'input',
    name: 'name',
    message: 'Name of a Helper',
  }, {
    type: 'input',
    name: 'filename',
    message: 'Where should it be stored',
    default: answers => `./${answers.name.toLowerCase()}_helper.js`,
  }], (result) => {
    const name = ucfirst(result.name);
    const helperFile = path.join(testsPath, result.filename);
    const dir = path.dirname(helperFile);
    if (!fileExists(dir)) fs.mkdirSync(dir);

    if (!safeFileWrite(helperFile, helperTemplate.replace(/{{name}}/g, name))) return;
    config.helpers[name] = {
      require: result.filename,
    };
    updateConfig(testsPath, config);
    output.success(`Helper for ${name} was created in ${helperFile}`);
  });
};
<commit_msg>Correctly extract default extension (#1214)<commit_after>const output = require('../output');
const inquirer = require('inquirer');
const fs = require('fs');
const path = require('path');
const colors = require('chalk');
const { fileExists, ucfirst, lcfirst } = require('../utils');
const mkdirp = require('mkdirp');
const {
  getConfig, getTestRoot, updateConfig, safeFileWrite,
} = require('./utils');

const testTemplate = `
Feature('{{feature}}');

Scenario('test something', ({{actor}}) => {

});
`;

// generates empty test
module.exports.test = function (genPath) {
  const testsPath = getTestRoot(genPath);
  const config = getConfig(testsPath);
  if (!config) return;

  output.print('Creating a new test...');
  output.print('----------------------');

  const defaultExt = config.tests.match(/([^\*/]*?)$/[1])[0] || '_test.js';

  inquirer.prompt([
    {
      type: 'input',
      message: 'Filename of a test',
      name: 'filename',
    },
    {
      type: 'input',
      name: 'feature',
      message: 'Feature which is being tested',
      default(answers) {
        return ucfirst(answers.filename).replace('_', ' ').replace('-', ' ');
      },
    },
  ], (result) => {
    const testFilePath = path.dirname(path.join(testsPath, config.tests)).replace(/\*\*$/, '');
    let testFile = path.join(testFilePath, result.filename);
    const ext = path.extname(testFile);
    if (!ext) testFile += defaultExt;
    const dir = path.dirname(testFile);
    if (!fileExists(dir)) mkdirp.sync(dir);
    let testContent = testTemplate.replace('{{feature}}', result.feature);

    // can be confusing before translations are documented
    // commenting it out:

    // let container = require('../container');
    // container.create(config);
    // testContent = testContent.replace('{{actor}}', container.translation().I);
    testContent = testContent.replace('{{actor}}', 'I');

    if (!safeFileWrite(testFile, testContent)) return;
    output.success(`Test for ${result.filename} was created in ${testFile}`);
  });
};

const pageObjectTemplate = `
const I = actor();

module.exports = {

  // insert your locators and methods here
}
`;

module.exports.pageObject = function (genPath, opts) {
  const testsPath = getTestRoot(genPath);
  const config = getConfig(testsPath);
  const kind = opts.T || 'page';
  if (!config) return;

  output.print(`Creating a new ${kind} object`);
  output.print('--------------------------');

  inquirer.prompt([{
    type: 'input',
    name: 'name',
    message: `Name of a ${kind} object`,
  }, {
    type: 'input',
    name: 'filename',
    message: 'Where should it be stored',
    default: answers => `./${kind}s/${answers.name}.js`,
  }], (result) => {
    const pageObjectFile = path.join(testsPath, result.filename);
    const dir = path.dirname(pageObjectFile);
    if (!fileExists(dir)) fs.mkdirSync(dir);

    let actor = 'actor';
    if (config.include.I) {
      let actorPath = config.include.I;
      if (actorPath.charAt(0) === '.') { // relative path
        actorPath = path.relative(dir, path.dirname(path.join(testsPath, actorPath))) + actorPath.substring(1); // get an upper level
      }
      actor = `require('${actorPath}')`;
    }
    if (!safeFileWrite(pageObjectFile, pageObjectTemplate.replace('{{actor}}', actor))) return;
    const name = lcfirst(result.name) + ucfirst(kind);
    config.include[name] = result.filename;
    updateConfig(testsPath, config);
    output.success(`${ucfirst(kind)} object for ${result.name} was created in ${pageObjectFile}`);
    output.print(`Use ${output.colors.bold(name)} as parameter in test scenarios to access it`);
  });
};

const helperTemplate = `
class {{name}} extends Helper {

  // before/after hooks
  _before() {
    // remove if not used
  }

  _after() {
    // remove if not used
  }

  // add custom methods here
  // If you need to access other helpers
  // use: this.helpers['helperName']

}

module.exports = {{name}};
`;

module.exports.helper = function (genPath) {
  const testsPath = getTestRoot(genPath);
  const config = getConfig(testsPath);

  output.print('Creating a new helper');
  output.print('--------------------------');

  inquirer.prompt([{
    type: 'input',
    name: 'name',
    message: 'Name of a Helper',
  }, {
    type: 'input',
    name: 'filename',
    message: 'Where should it be stored',
    default: answers => `./${answers.name.toLowerCase()}_helper.js`,
  }], (result) => {
    const name = ucfirst(result.name);
    const helperFile = path.join(testsPath, result.filename);
    const dir = path.dirname(helperFile);
    if (!fileExists(dir)) fs.mkdirSync(dir);

    if (!safeFileWrite(helperFile, helperTemplate.replace(/{{name}}/g, name))) return;
    config.helpers[name] = {
      require: result.filename,
    };
    updateConfig(testsPath, config);
    output.success(`Helper for ${name} was created in ${helperFile}`);
  });
};
<|endoftext|>


<commit_before>// Copyright 2015, EMC, Inc.

'use strict';

module.exports = constantsFactory;

constantsFactory.$provide = 'Constants';
constantsFactory.$inject = [
    'path'
];

function constantsFactory (path) {
    var constants = Object.freeze({
        WorkingDirectory: process.cwd(),
        Name: process.cwd().split(path.sep).reverse()[0],
        Host: require('os').hostname().split(/\./)[0],
        Events: {
            Log: 'log',
            Unhandled: 'errors.unhandled',
            Ignored: 'errors.ignored',
            Blocked: 'errors.blocked'
        },
        Logging: {
            Colors: {
              critical: 'red',
              error: 'red',
              warning: 'yellow',
              info: 'green',
              debug: 'cyan',
            },
            Levels: {
                critical: 5,
                error: 4,
                warning: 3,
                info: 2,
                debug: 1
            },
            Context: {
                Length: 6
            },
            Sanitizations: ['id', 'mac', 'ip'],
            Redactions: [ 'password' ]
        },
        Configuration: {
            Files: {
                Global: process.env.MONORAIL_CONFIG || '/opt/monorail/config.json',
                OnRack: '/opt/onrack/etc/monorail.json'
            }
        },
        WorkItems: {
            Pollers: {
                IPMI: 'Pollers.IPMI',
                SNMP: 'Pollers.SNMP',
                REDFISH: 'Pollers.Redfish',
                Metrics: {
                    SnmpInterfaceBandwidthUtilization: 'snmp-interface-bandwidth-utilization',
                    SnmpInterfaceState: 'snmp-interface-state',
                    SnmpProcessorLoad: 'snmp-processor-load',
                    SnmpMemoryUsage: 'snmp-memory-usage',
                    SnmpPduPowerStatus: 'snmp-pdu-power-status'
                }
            },
        },
        Protocol: {
            Exchanges: {
                Configuration: {
                    Name: 'on.configuration',
                    Options: {
                        type: 'topic',
                        durable: true,
                        autoDelete: false
                    }
                },
                Dhcp: {
                    Name: 'on.dhcp',
                    Options: {
                        type: 'topic',
                        durable: true,
                        autoDelete: false
                    }
                },
                Events: {
                    Name: 'on.events',
                    Options: {
                        type: 'topic',
                        durable: true,
                        autoDelete: false
                    }
                },
                Http: {
                    Name: 'on.http',
                    Options: {
                        type: 'topic',
                        durable: true,
                        autoDelete: false
                    }
                },
                Logging: {
                    Name: 'on.logging',
                    Options: {
                        type: 'topic',
                        durable: true,
                        autoDelete: false
                    }
                },
                TaskGraphRunner: {
                    Name: 'on.task-graph-runner',
                    Options: {
                        type: 'topic',
                        durable: true,
                        autoDelete: false
                    }
                },
                Scheduler: {
                    Name: 'on.scheduler',
                    Options: {
                        type: 'topic',
                        durable: true,
                        autoDelete: false
                    }
                },
                Task: {
                    Name: 'on.task',
                    Options: {
                        type: 'topic',
                        durable: true,
                        autoDelete: false
                    }
                },
                Tftp: {
                    Name: 'on.tftp',
                    Options: {
                        type: 'topic',
                        durable: true,
                        autoDelete: false
                    }
                },
                Waterline: {
                    Name: 'on.waterline',
                    Options: {
                        type: 'topic',
                        durable: true,
                        autoDelete: false
                    }
                },
                Test: {
                    Name: 'on.test',
                    Options: {
                        type: 'topic',
                        durable: true,
                        autoDelete: false
                    }
                }
            }
        },
        Profiles: {
            Directory: process.cwd() + '/data/profiles'
        },
        Templates: {
            Directory: process.cwd() + '/data/templates'
        },
        Task: {
            FinishedStates: [
                'succeeded',
                'timeout',
                'cancelled',
                'failed'
            ],
            FailedStates: [
                'failed',
                'timeout',
                'cancelled'
            ],
            ActiveStates: [
                'pending'
            ],
            States: {
                Running: 'running',
                Succeeded: 'succeeded',
                Failed: 'failed',
                Cancelled: 'cancelled',
                Timeout: 'timeout',
                Pending: 'pending',
                Finished: 'finished'
            },
            DefaultDomain: 'default',
            DefaultLeaseAdjust: 2000,
        },
        Regex: {
            Base64: /^(?:[A-Z0-9+\/]{4})*(?:[A-Z0-9+\/]{2}==|[A-Z0-9+\/]{3}=|[A-Z0-9+\/]{4})$/i,
            Encrypted: /^(?:[A-Z0-9+\/]{4})*(?:[A-Z0-9+\/]{2}==|[A-Z0-9+\/]{3}=|[A-Z0-9+\/]{4})\.(?:[A-Z0-9+\/]{4})*(?:[A-Z0-9+\/]{2}==|[A-Z0-9+\/]{3}=|[A-Z0-9+\/]{4})$/i, // jshint ignore:line
            MacAddress: /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/,
            IpAddress: /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/,
        },
        ChildProcess: {
            maxBuffer: 200 * 1024
        },
        ObmSettings: {
            'noop-obm-service': [
                {
                    type: 'compute'
                },
            ],
            'ipmi-obm-service': [
                {
                    type: 'compute'
                }
            ],
            'panduit-obm-service': [
                {
                    type: 'enclosure'
                },
                {
                    type: 'compute',
                    sku: 'noop' // Example for multi-item rule
                }
            ],
            'vbox-obm-service': [
                {
                    type: 'compute'
                }
            ],
            'redfish-obm-service': [
                {
                    type: 'redfish'
                }
            ]
        },
        NodeRelations: {
            /* There are two classes about the pair of relations:
             * component: one node is a component of the other
             *     e.g.  compute node vs. enclosure node
             *     expect behavior:
             *         the "By" in the relationType is used to tell component from its parent
             *         delete a node as well as its components;
             *         delete a component and update its parenet node
             * link: two nodes is linked to each other
             *     e.g.  compute node vs pdu node (TODO)
             *     expect behavior:
             *         delete one node and update the other
            */
            encloses: {
                mapping: 'enclosedBy',
                relationClass: 'component'
            },
            enclosedBy: {
                mapping: 'encloses',
                relationClass: 'component'
            },
            /* Below are an example used to verify function
             * currently used in unit test
             compute node:
             "relations": [
                 {
                     "relationType": "poweredBy",
                     "targets": [
                         "567b8f478b7444e407bb0729"
                     ]
                 }
             ],
             pdu node:
             "relations": [
                 {
                     "relationType": "powers",
                     "targets": [
                         "567b8f478b7444e407bb072a"
                         "567b8f478b7444e407bb072b"
                     ]
                 }
             ],
             If either of them is removed, the other node will only be updated without deletion
            */
            powers: {
                mapping: 'poweredBy',
                relationClass: 'link'
            },
            poweredBy: {
                mapping: 'powers',
                relationClass: 'link'
            }
            /* end example */
        },
        Scope: {
            Global: 'global'
        },
        NodeTypes: {
            Compute: 'compute',
            Switch: 'switch',
            Dae: 'dae',
            Pdu: 'pdu',
            Mgmt: 'mgmt',
            Enclosure: 'enclosure'
        }
    });

    return constants;
}
<commit_msg>Add Views.Directory to Constants<commit_after>// Copyright 2015, EMC, Inc.

'use strict';

module.exports = constantsFactory;

constantsFactory.$provide = 'Constants';
constantsFactory.$inject = [
    'path'
];

function constantsFactory (path) {
    var constants = Object.freeze({
        WorkingDirectory: process.cwd(),
        Name: process.cwd().split(path.sep).reverse()[0],
        Host: require('os').hostname().split(/\./)[0],
        Events: {
            Log: 'log',
            Unhandled: 'errors.unhandled',
            Ignored: 'errors.ignored',
            Blocked: 'errors.blocked'
        },
        Logging: {
            Colors: {
              critical: 'red',
              error: 'red',
              warning: 'yellow',
              info: 'green',
              debug: 'cyan',
            },
            Levels: {
                critical: 5,
                error: 4,
                warning: 3,
                info: 2,
                debug: 1
            },
            Context: {
                Length: 6
            },
            Sanitizations: ['id', 'mac', 'ip'],
            Redactions: [ 'password' ]
        },
        Configuration: {
            Files: {
                Global: process.env.MONORAIL_CONFIG || '/opt/monorail/config.json',
                OnRack: '/opt/onrack/etc/monorail.json'
            }
        },
        WorkItems: {
            Pollers: {
                IPMI: 'Pollers.IPMI',
                SNMP: 'Pollers.SNMP',
                REDFISH: 'Pollers.Redfish',
                Metrics: {
                    SnmpInterfaceBandwidthUtilization: 'snmp-interface-bandwidth-utilization',
                    SnmpInterfaceState: 'snmp-interface-state',
                    SnmpProcessorLoad: 'snmp-processor-load',
                    SnmpMemoryUsage: 'snmp-memory-usage',
                    SnmpPduPowerStatus: 'snmp-pdu-power-status'
                }
            },
        },
        Protocol: {
            Exchanges: {
                Configuration: {
                    Name: 'on.configuration',
                    Options: {
                        type: 'topic',
                        durable: true,
                        autoDelete: false
                    }
                },
                Dhcp: {
                    Name: 'on.dhcp',
                    Options: {
                        type: 'topic',
                        durable: true,
                        autoDelete: false
                    }
                },
                Events: {
                    Name: 'on.events',
                    Options: {
                        type: 'topic',
                        durable: true,
                        autoDelete: false
                    }
                },
                Http: {
                    Name: 'on.http',
                    Options: {
                        type: 'topic',
                        durable: true,
                        autoDelete: false
                    }
                },
                Logging: {
                    Name: 'on.logging',
                    Options: {
                        type: 'topic',
                        durable: true,
                        autoDelete: false
                    }
                },
                TaskGraphRunner: {
                    Name: 'on.task-graph-runner',
                    Options: {
                        type: 'topic',
                        durable: true,
                        autoDelete: false
                    }
                },
                Scheduler: {
                    Name: 'on.scheduler',
                    Options: {
                        type: 'topic',
                        durable: true,
                        autoDelete: false
                    }
                },
                Task: {
                    Name: 'on.task',
                    Options: {
                        type: 'topic',
                        durable: true,
                        autoDelete: false
                    }
                },
                Tftp: {
                    Name: 'on.tftp',
                    Options: {
                        type: 'topic',
                        durable: true,
                        autoDelete: false
                    }
                },
                Waterline: {
                    Name: 'on.waterline',
                    Options: {
                        type: 'topic',
                        durable: true,
                        autoDelete: false
                    }
                },
                Test: {
                    Name: 'on.test',
                    Options: {
                        type: 'topic',
                        durable: true,
                        autoDelete: false
                    }
                }
            }
        },
        Profiles: {
            Directory: process.cwd() + '/data/profiles'
        },
        Templates: {
            Directory: process.cwd() + '/data/templates'
        },
        Views: {
            Directory: process.cwd() + '/data/views'
        },
        Task: {
            FinishedStates: [
                'succeeded',
                'timeout',
                'cancelled',
                'failed'
            ],
            FailedStates: [
                'failed',
                'timeout',
                'cancelled'
            ],
            ActiveStates: [
                'pending'
            ],
            States: {
                Running: 'running',
                Succeeded: 'succeeded',
                Failed: 'failed',
                Cancelled: 'cancelled',
                Timeout: 'timeout',
                Pending: 'pending',
                Finished: 'finished'
            },
            DefaultDomain: 'default',
            DefaultLeaseAdjust: 2000,
        },
        Regex: {
            Base64: /^(?:[A-Z0-9+\/]{4})*(?:[A-Z0-9+\/]{2}==|[A-Z0-9+\/]{3}=|[A-Z0-9+\/]{4})$/i,
            Encrypted: /^(?:[A-Z0-9+\/]{4})*(?:[A-Z0-9+\/]{2}==|[A-Z0-9+\/]{3}=|[A-Z0-9+\/]{4})\.(?:[A-Z0-9+\/]{4})*(?:[A-Z0-9+\/]{2}==|[A-Z0-9+\/]{3}=|[A-Z0-9+\/]{4})$/i, // jshint ignore:line
            MacAddress: /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/,
            IpAddress: /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/,
        },
        ChildProcess: {
            maxBuffer: 200 * 1024
        },
        ObmSettings: {
            'noop-obm-service': [
                {
                    type: 'compute'
                },
            ],
            'ipmi-obm-service': [
                {
                    type: 'compute'
                }
            ],
            'panduit-obm-service': [
                {
                    type: 'enclosure'
                },
                {
                    type: 'compute',
                    sku: 'noop' // Example for multi-item rule
                }
            ],
            'vbox-obm-service': [
                {
                    type: 'compute'
                }
            ],
            'redfish-obm-service': [
                {
                    type: 'redfish'
                }
            ]
        },
        NodeRelations: {
            /* There are two classes about the pair of relations:
             * component: one node is a component of the other
             *     e.g.  compute node vs. enclosure node
             *     expect behavior:
             *         the "By" in the relationType is used to tell component from its parent
             *         delete a node as well as its components;
             *         delete a component and update its parenet node
             * link: two nodes is linked to each other
             *     e.g.  compute node vs pdu node (TODO)
             *     expect behavior:
             *         delete one node and update the other
            */
            encloses: {
                mapping: 'enclosedBy',
                relationClass: 'component'
            },
            enclosedBy: {
                mapping: 'encloses',
                relationClass: 'component'
            },
            /* Below are an example used to verify function
             * currently used in unit test
             compute node:
             "relations": [
                 {
                     "relationType": "poweredBy",
                     "targets": [
                         "567b8f478b7444e407bb0729"
                     ]
                 }
             ],
             pdu node:
             "relations": [
                 {
                     "relationType": "powers",
                     "targets": [
                         "567b8f478b7444e407bb072a"
                         "567b8f478b7444e407bb072b"
                     ]
                 }
             ],
             If either of them is removed, the other node will only be updated without deletion
            */
            powers: {
                mapping: 'poweredBy',
                relationClass: 'link'
            },
            poweredBy: {
                mapping: 'powers',
                relationClass: 'link'
            }
            /* end example */
        },
        Scope: {
            Global: 'global'
        },
        NodeTypes: {
            Compute: 'compute',
            Switch: 'switch',
            Dae: 'dae',
            Pdu: 'pdu',
            Mgmt: 'mgmt',
            Enclosure: 'enclosure'
        }
    });

    return constants;
}
<|endoftext|>


<commit_before>"use strict";

/// !doc
///
/// # streamline/lib/compiler/command
///
/// Streamline commmand line analyzer / dispatcher
///
var compile = require('./compile').compile;
var path = require('path');
var flows = require('streamline/lib/util/flows');

function _run(){
	var argv = process.argv;
	var inputs;
	argv.shift();

	if (argv.length <= 1)
		return require("repl").start("node-streamline> ");

	// for now!
	//return require(path.join(process.cwd(), argv[1]));
	var options = {
		action: "run",
		lines: "mark"
	};
	while (argv[1] && argv[1][0] == '-') {
		var arg = argv.splice(1, 1)[0];
		switch (arg) {
			case '-c':
			case '--compile':
				options.action = "compile";
				inputs = argv.splice(1, argv.length - 1);
				break;
			case '-f':
			case '--force':
				options.force = true;
				break;
			case '-v':
			case '--verbose':
				options.verbose = true;
				break;
			case '-lm':
			case '--lines-mark':
				options.lines = "mark";
				break;
			case '-li':
			case '--lines-ignore':
				options.lines = "ignore";
				break;
			case '-lm':
			case '--lines-mark':
				options.lines = "mark";
				break;
			case '-lp':
			case '--lines-preserve':
				options.lines = "preserve";
				break;
			case '-h':
			case '--help':
				options.action = "help";
				break;
			default:
				throw new Error("unkown option " + arg + ". Try -h for help");
		}
	}
	switch (options.action) {
		case "run":
			if (argv.length < 1) {
				throw new Error("invalid command line. Try -h for help");
			}
			require('./register').register({compileAnyways:1});
			require(path.resolve(process.cwd(), argv[1]));
			break;
		case "compile":
			compile(function(err) {
				err && console.error(err.message + "\n" + err.stack);
			}, inputs, options);
			break;
		case "help":
			console.log("Usage:");
			console.log("  node-streamline module\n");
			console.log("Available options:");
			console.log("  -c, --compile          compile *_.js files and save as *.js files");
			console.log("  -f, --force            force recompilation");
			console.log("  -v, --verbose          verbose");
			console.log("  -li, --lines-ignore    ignore line numbers");
			console.log("  -lm, --lines-mark      mark with line numbers");
			console.log("  -lp, --lines-preserve  preserve line numbers");
			console.log("  -h, --help             displays this help message");
			console.log("");
			break;
	}
}

/// * `command.run()`
///   runs `node-streamline` command line analyzer / dispatcher
exports.run = function(){
	try {
		_run();
	}
	catch (ex) {
		console.error(ex.message + "\n" + ex.stack);
	}
}
<commit_msg>adding callback specification to options for compiling with a diff callback, and fix require()<commit_after>"use strict";

/// !doc
///
/// # streamline/lib/compiler/command
///
/// Streamline commmand line analyzer / dispatcher
///
var compile = require('./compile').compile;
var path = require('path');
var flows = require('../util/flows');

function _run(){
	var argv = process.argv;
	var inputs;
	argv.shift();

	if (argv.length <= 1)
		return require("repl").start("node-streamline> ");

	// for now!
	//return require(path.join(process.cwd(), argv[1]));
	var options = {
		action: "run",
		lines: "mark"
	};
	while (argv[1] && argv[1][0] == '-') {
		var arg = argv.splice(1, 1)[0];
		switch (arg) {
			case '-c':
			case '--compile':
				options.action = "compile";
				inputs = argv.splice(1, argv.length - 1);
				break;
			case '--cb':
					options.callback = argv.splice(1, 1)[0];
					break;
			case '-f':
			case '--force':
				options.force = true;
				break;
			case '-v':
			case '--verbose':
				options.verbose = true;
				break;
			case '-lm':
			case '--lines-mark':
				options.lines = "mark";
				break;
			case '-li':
			case '--lines-ignore':
				options.lines = "ignore";
				break;
			case '-lm':
			case '--lines-mark':
				options.lines = "mark";
				break;
			case '-lp':
			case '--lines-preserve':
				options.lines = "preserve";
				break;
			case '-h':
			case '--help':
				options.action = "help";
				break;
			default:
				throw new Error("unkown option " + arg + ". Try -h for help");
		}
	}
	switch (options.action) {
		case "run":
			if (argv.length < 1) {
				throw new Error("invalid command line. Try -h for help");
			}
			require('./register').register({compileAnyways:1});
			require(path.resolve(process.cwd(), argv[1]));
			break;
		case "compile":
			compile(function(err) {
				err && console.error(err.message + "\n" + err.stack);
			}, inputs, options);
			break;
		case "help":
			console.log("Usage:");
			console.log("  node-streamline module\n");
			console.log("Available options:");
			console.log("  -c, --compile          compile *_.js files and save as *.js files");
			console.log("  --cb                   set callback identifier when compiling. only valid with -c");
			console.log("  -f, --force            force recompilation");
			console.log("  -v, --verbose          verbose");
			console.log("  -li, --lines-ignore    ignore line numbers");
			console.log("  -lm, --lines-mark      mark with line numbers");
			console.log("  -lp, --lines-preserve  preserve line numbers");
			console.log("  -h, --help             displays this help message");
			console.log("");
			break;
	}
}

/// * `command.run()`
///   runs `node-streamline` command line analyzer / dispatcher
exports.run = function(){
	try {
		_run();
	}
	catch (ex) {
		console.error(ex.message + "\n" + ex.stack);
	}
}
<|endoftext|>


<commit_before>var React = require('react');
var ExecutionEnvironment = require('react/lib/ExecutionEnvironment');
var ModalPortal = React.createFactory(require('./ModalPortal'));
var ariaAppHider = require('../helpers/ariaAppHider');
var injectCSS = require('../helpers/injectCSS');
var elementClass = require('element-class');

var SafeHTMLElement = ExecutionEnvironment.canUseDOM ? window.HTMLElement : {};

var Modal = module.exports = React.createClass({

  displayName: 'Modal',

  statics: {
    setAppElement: ariaAppHider.setElement,
    injectCSS: injectCSS
  },

  propTypes: {
    isOpen: React.PropTypes.bool.isRequired,
    onRequestClose: React.PropTypes.func,
    appElement: React.PropTypes.instanceOf(SafeHTMLElement),
    closeTimeoutMS: React.PropTypes.number,
    ariaHideApp: React.PropTypes.bool
  },

  getDefaultProps: function () {
    return {
      isOpen: false,
      ariaHideApp: true,
      closeTimeoutMS: 0
    };
  },

  componentDidMount: function() {
    this.node = document.createElement('div');
    this.node.className = 'ReactModalPortal';
    document.body.appendChild(this.node);
    this.renderPortal(this.props);
  },

  componentWillReceiveProps: function(newProps) {
    this.renderPortal(newProps);
  },

  componentWillUnmount: function() {
    React.unmountComponentAtNode(this.node);
    document.body.removeChild(this.node);
  },

  renderPortal: function(props) {
    if (props.isOpen) {
      elementClass(document.body).add('ReactModal__Body--open');
    } else {
      elementClass(document.body).remove('ReactModal__Body--open');
    }

    if (props.ariaHideApp) {
      ariaAppHider.toggle(props.isOpen, props.appElement);
    }
    sanitizeProps(props);
    if (this.portal)
      this.portal.setProps(props);
    else
      this.portal = React.render(ModalPortal(props), this.node);
  },

  render: function () {
    return null;
  }
});

function sanitizeProps(props) {
  delete props.ref;
}
<commit_msg>Returning noscript tag instead of null<commit_after>var React = require('react');
var ExecutionEnvironment = require('react/lib/ExecutionEnvironment');
var ModalPortal = React.createFactory(require('./ModalPortal'));
var ariaAppHider = require('../helpers/ariaAppHider');
var injectCSS = require('../helpers/injectCSS');
var elementClass = require('element-class');

var SafeHTMLElement = ExecutionEnvironment.canUseDOM ? window.HTMLElement : {};

var Modal = module.exports = React.createClass({

  displayName: 'Modal',

  statics: {
    setAppElement: ariaAppHider.setElement,
    injectCSS: injectCSS
  },

  propTypes: {
    isOpen: React.PropTypes.bool.isRequired,
    onRequestClose: React.PropTypes.func,
    appElement: React.PropTypes.instanceOf(SafeHTMLElement),
    closeTimeoutMS: React.PropTypes.number,
    ariaHideApp: React.PropTypes.bool
  },

  getDefaultProps: function () {
    return {
      isOpen: false,
      ariaHideApp: true,
      closeTimeoutMS: 0
    };
  },

  componentDidMount: function() {
    this.node = document.createElement('div');
    this.node.className = 'ReactModalPortal';
    document.body.appendChild(this.node);
    this.renderPortal(this.props);
  },

  componentWillReceiveProps: function(newProps) {
    this.renderPortal(newProps);
  },

  componentWillUnmount: function() {
    React.unmountComponentAtNode(this.node);
    document.body.removeChild(this.node);
  },

  renderPortal: function(props) {
    if (props.isOpen) {
      elementClass(document.body).add('ReactModal__Body--open');
    } else {
      elementClass(document.body).remove('ReactModal__Body--open');
    }

    if (props.ariaHideApp) {
      ariaAppHider.toggle(props.isOpen, props.appElement);
    }
    sanitizeProps(props);
    if (this.portal)
      this.portal.setProps(props);
    else
      this.portal = React.render(ModalPortal(props), this.node);
  },

  render: function () {
    return React.DOM.noscript();
  }
});

function sanitizeProps(props) {
  delete props.ref;
}
<|endoftext|>


<commit_before>const httpRequest = require('request');
const cheerio = require('cheerio');
const Photo = require('../model/Photo');

const GOPRO_URL = 'https://gopro.com/photos/photo-of-the-day/';

var cache = require('../cache');

module.exports = function (request, reply) {
    var date = request.params.date ?
        new Date(Date.parse(encodeURIComponent(request.params.date)))
        : new Date();
    var url = GOPRO_URL + date.toCustomString('/');

    var cacheKey = date.toCustomString();
    var cacheEntry = cache.get(cacheKey);

    if (cacheEntry) {
        reply(cacheEntry);
    } else {
        getPhoto(url, cacheKey, reply);
    }
};

function getPhoto(url, cacheKey, reply) {
    httpRequest(url, function (error, response, html) {
        if (!error && response.statusCode == 200) {
            var body = cheerio.load(html);
            var uri = body('div.span12.text-center.black-background img').attr('src').toString();
            var title = body('title').text().replace('GoPro Photo Of The Day | ', '');

            var byline = body('div.row-fluid.black-background.medium-top-padding.xxlarge-bottom-padding ' +
            'p.gray-font.medium-bottom-margin').text();
            byline = byline.trimSequence('\n');
            byline = byline.replace('\n', ' ');

            var photo = new Photo(uri, title, byline);
            cache.put(cacheKey, photo);

            reply(photo);
        }
    });
}
<commit_msg>more refactoring<commit_after>const httpRequest = require('request');
const cheerio = require('cheerio');
const Photo = require('../model/Photo');

const GOPRO_URL = 'https://gopro.com/photos/photo-of-the-day/';

var cache = require('../cache');

module.exports = function (request, reply) {
    var date = request.params.date ?
        new Date(Date.parse(encodeURIComponent(request.params.date)))
        : new Date();
    var url = GOPRO_URL + date.toCustomString('/');

    var cacheKey = date.toCustomString();
    var cacheEntry = cache.get(cacheKey);

    if (cacheEntry) {
        reply(cacheEntry);
    } else {
        getPhoto(url, cacheKey, reply);
    }
};

function getPhoto(url, cacheKey, reply) {
    httpRequest(url, function (error, response, html) {
        if (!error && response.statusCode == 200) {
            var photo = parseGoproWebpage(html);
            cache.put(cacheKey, photo);

            reply(photo);
        }
    });
}

function parseGoproWebpage(html) {
    var body = cheerio.load(html);
    var uri = body('div.span12.text-center.black-background img').attr('src').toString();
    var title = body('title').text().replace('GoPro Photo Of The Day | ', '');

    var byline = body('div.row-fluid.black-background.medium-top-padding.xxlarge-bottom-padding ' +
    'p.gray-font.medium-bottom-margin').text();
    byline = byline.trimSequence('\n');
    byline = byline.replace('\n', ' ');

    return new Photo(uri, title, byline);
}
<|endoftext|>


<commit_before>/*

    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      This file is part of the Smart Developer Hub Project:
        http://www.smartdeveloperhub.org/
      Center for Open Middleware
            http://www.centeropenmiddleware.com/
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      Copyright (C) 2015 Center for Open Middleware.
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
     limitations under the License.
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
*/

'use strict';

var uuid = require('node-uuid');

/**
 * Get full API Swagger JSON description.
 * This method use express (http://expressjs.com/)
 * @param req Request http://expressjs.com/api.html#req
 * @param res Response http://expressjs.com/api.html#res
 * @param next Pass control to the next handler
 */
module.exports.login = function login (req, res, next) {
    console.log("Trying to login in SDH-API");
    passport.authenticate('ldapauth', {session: false})(req, res, function() {
        console.log("... LDAP ...");
        if(req.user != null) {
            console.log("LDAP credentials validation");
            //Create a new session
            var token = uuid.v4();
            GLOBAL.SESSIONS[token] = {
                info: {
                    lastAccess: Date.now()
                },
                data: req.user
            };
            var getRandomGravatar = function getRandomGravatar(size) {
                return "https://secure.gravatar.com/avatar/"+CryptoJS.MD5(""+Math.random())+"?d=identicon&s="+size;"https://secure.gravatar.com/avatar/"+CryptoJS.MD5(""+Math.random())+"?d=identicon&s="+size;
            };
            var thePos;
            var theAvatar;
            // TODO add in req.user 'positions': {orgId: [positionId]} and 'roles': {projectId: [roleId]}
            if (usersById[req.user.uidNumber] == undefined) {
                thePos = {1:[69]};
            }
            else {
                thePos = usersById[req.user.uidNumber].positionsByOrgId;
            }
            req.user["positions"] = thePos;
            if (usersById[req.user.uidNumber].avatar == undefined) {
                theAvatar = "http://hospitalfranciscovilar.com.br/wp-content/uploads/2013/11/gravatar-60-grey.jpg";
                console.log(theAvatar);
                req.user["avatar"] = theAvatar;
            } else {
                theAvatar = usersById[req.user.uidNumber].avatar;
                console.log(theAvatar);
                req.user["avatar"] = theAvatar;
            }

            console.log("positions: " + thePos);
            console.log(JSON.stringify({token: token, user: req.user}));
            res.statusCode = 200;
            res.setHeader('Content-Type', 'application/json');
            res.end(JSON.stringify({token: token, user: req.user}));
        } else {
            console.log("Login Error. User '" + req.body.username + '"');
            res.statusCode = 401;
            res.end();
        }

    });
};

function randomIntFromInterval(min,max) {
    return Math.floor(Math.random()*(max-min+1)+min);
}

module.exports.check = function check (req, res, next) {

    passport.authenticate('bearer', {session: false})(req, res, function() {

        res.statusCode = 200;
        res.end();
    });

};

module.exports.logout = function logout(req, res, next) {

    passport.authenticate('bearer', {session: false})(req, res, function() {

        // TODO make sessions global if necessary
        var Sessions = require('../sessions');

        //Remove the session
        var token = Sessions.getToken(req);
        var session = Sessions.getSession(token);
        if(session != null) {
            Sessions.deleteSession(token);
        }

        res.statusCode = 200;
        res.end();
    });

};<commit_msg>Fix problem with user avatar<commit_after>/*

    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      This file is part of the Smart Developer Hub Project:
        http://www.smartdeveloperhub.org/
      Center for Open Middleware
            http://www.centeropenmiddleware.com/
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      Copyright (C) 2015 Center for Open Middleware.
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
     limitations under the License.
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
*/

'use strict';

var uuid = require('node-uuid');

/**
 * Get full API Swagger JSON description.
 * This method use express (http://expressjs.com/)
 * @param req Request http://expressjs.com/api.html#req
 * @param res Response http://expressjs.com/api.html#res
 * @param next Pass control to the next handler
 */
module.exports.login = function login (req, res, next) {
    console.log("Trying to login in SDH-API");
    passport.authenticate('ldapauth', {session: false})(req, res, function() {
        console.log("... LDAP ...");
        if(req.user != null) {
            console.log("LDAP credentials validation");
            //Create a new session
            var token = uuid.v4();
            GLOBAL.SESSIONS[token] = {
                info: {
                    lastAccess: Date.now()
                },
                data: req.user
            };

            var thePos;
            var theAvatar;
            // TODO add in req.user 'positions': {orgId: [positionId]} and 'roles': {projectId: [roleId]}
            if (usersById[req.user.uidNumber] == undefined) {
                thePos = {1:[69]};
            }
            else {
                thePos = usersById[req.user.uidNumber].positionsByOrgId;
            }
            req.user["positions"] = thePos;
            if (typeof usersById[req.user.uidNumber].avatar == 'undefined') {
                theAvatar = "http://hospitalfranciscovilar.com.br/wp-content/uploads/2013/11/gravatar-60-grey.jpg";
                req.user["avatar"] = theAvatar;
            } else {
                theAvatar = usersById[req.user.uidNumber].avatar;
                req.user["avatar"] = theAvatar;
            }

            console.log("positions: " + thePos);
            console.log(JSON.stringify({token: token, user: req.user}));
            res.statusCode = 200;
            res.setHeader('Content-Type', 'application/json');
            res.end(JSON.stringify({token: token, user: req.user}));
        } else {
            console.log("Login Error. User '" + req.body.username + '"');
            res.statusCode = 401;
            res.end();
        }

    });
};

function randomIntFromInterval(min,max) {
    return Math.floor(Math.random()*(max-min+1)+min);
}

module.exports.check = function check (req, res, next) {

    passport.authenticate('bearer', {session: false})(req, res, function() {

        res.statusCode = 200;
        res.end();
    });

};

module.exports.logout = function logout(req, res, next) {

    passport.authenticate('bearer', {session: false})(req, res, function() {

        // TODO make sessions global if necessary
        var Sessions = require('../sessions');

        //Remove the session
        var token = Sessions.getToken(req);
        var session = Sessions.getSession(token);
        if(session != null) {
            Sessions.deleteSession(token);
        }

        res.statusCode = 200;
        res.end();
    });

};<|endoftext|>


<commit_before>"use strict";

var Blog = require("../models/blog").Blog;
var Blogger = require("../models/blogger").Blogger;
var BloggerController = require("./blogger")
var paginate = require('express-paginate');
var sanitizeHtml = require('sanitize-html');

//Done of form (blogs, pageNumber, showBack, showNext, error)
exports.getPaginatedBlogs = function (options, req, done) {
    Blog.paginate(options, req.query.page, req.query.limit, function (error, pageCount, blogs, itemCount) {
        if (error) {
            done(null, -1, false, false, error);
        }
        else {
            // Attach bloggers to blogs
            BloggerController.getAllProfiles(true, function(allBloggers, error) {
                if (error) {
                    done(null, -1, false, false, error);
                }
                else {
                    for (var i = 0; i < blogs.length; ++i) {
                        // Associate each blog with its blogger
                        blogs[i].author = allBloggers.filter(function(element) {
                            return ((element.userId == blogs[i].userId) && (element.userProvider == blogs[i].userProvider));
                        })[0];
                    }

                    done(blogs, req.query.page, (req.query.page > 1), paginate.hasNextPages(req)(pageCount), null);
                }
            });
        }
    }, {sortBy: {pubDate : 'desc'}, columns: {__v: 0}});
};

//Done of form (recentBlogs, error)
exports.getMostRecentBlogs = function(options, howMany, done) {
    Blog.find(options, null, {skip: 0, limit: howMany, sort: {pubDate: 'desc'}}, function(error, recentBlogs) {
        if (error) {
            done(null, error);
        }
        else {
            // Attach bloggers to blogs
            BloggerController.getAllProfiles(true, function(allBloggers, error) {
                if (error) {
                    done(null, error);
                }
                else {
                    for (var i = 0; i < recentBlogs.length; ++i) {
                        // Associate each blog with its blogger
                        recentBlogs[i].author = allBloggers.filter(function(element) {
                            return ((element.userId == recentBlogs[i].userId) && (element.userProvider == recentBlogs[i].userProvider));
                        })[0];
                    }

                    done(recentBlogs, null);
                }
            });
        }
    });
};

exports.truncateAndRemoveHTML = function(str, len) {
    str = sanitizeHtml(str, {
        allowedTags: [],
        allowedAttributes: {}
    });
    if (str.length > len && str.length > 0) {
        var new_str = str + " ";
        new_str = str.substr(0, len);
        new_str = str.substr(0, new_str.lastIndexOf(" "));
        new_str = (new_str.length > 0) ? new_str : str.substr(0, len);

        return new_str + '…';
    }

    // Some blogs leave annoying bits at then end, such as their own
    // continue reading link or ellipses. Remove these.
    var continueReadingPosition = str.indexOf('… Continue reading →');
    if (continueReadingPosition !== -1) {
        str = str.substring(0, continueReadingPosition);
    }

    var readMorePosition = str.indexOf('... Read more');
    if (readMorePosition !== -1) {
        str = str.substring(0, readMorePosition);
    }

    if (str.indexOf('[…]', str.length - 3) !== -1) {
        str = str.substring(0, str.length - 3);
    }

    // Trim start and end of string
    str = str.replace(/^\s+|\s+$/g, '');

    return str;
};

exports.removeAllHTML = function(blogs, len) {
    for (var i = 0; i < blogs.length; ++i) {
        blogs[i].summary = exports.truncateAndRemoveHTML(blogs[i].summary, len);
    }
}
<commit_msg>Fixed summary trim() bug in truncateAndRemoveHTML function<commit_after>"use strict";

var Blog = require("../models/blog").Blog;
var Blogger = require("../models/blogger").Blogger;
var BloggerController = require("./blogger")
var paginate = require('express-paginate');
var sanitizeHtml = require('sanitize-html');

//Done of form (blogs, pageNumber, showBack, showNext, error)
exports.getPaginatedBlogs = function (options, req, done) {
    Blog.paginate(options, req.query.page, req.query.limit, function (error, pageCount, blogs, itemCount) {
        if (error) {
            done(null, -1, false, false, error);
        }
        else {
            // Attach bloggers to blogs
            BloggerController.getAllProfiles(true, function(allBloggers, error) {
                if (error) {
                    done(null, -1, false, false, error);
                }
                else {
                    for (var i = 0; i < blogs.length; ++i) {
                        // Associate each blog with its blogger
                        blogs[i].author = allBloggers.filter(function(element) {
                            return ((element.userId == blogs[i].userId) && (element.userProvider == blogs[i].userProvider));
                        })[0];
                    }

                    done(blogs, req.query.page, (req.query.page > 1), paginate.hasNextPages(req)(pageCount), null);
                }
            });
        }
    }, {sortBy: {pubDate : 'desc'}, columns: {__v: 0}});
};

//Done of form (recentBlogs, error)
exports.getMostRecentBlogs = function(options, howMany, done) {
    Blog.find(options, null, {skip: 0, limit: howMany, sort: {pubDate: 'desc'}}, function(error, recentBlogs) {
        if (error) {
            done(null, error);
        }
        else {
            // Attach bloggers to blogs
            BloggerController.getAllProfiles(true, function(allBloggers, error) {
                if (error) {
                    done(null, error);
                }
                else {
                    for (var i = 0; i < recentBlogs.length; ++i) {
                        // Associate each blog with its blogger
                        recentBlogs[i].author = allBloggers.filter(function(element) {
                            return ((element.userId == recentBlogs[i].userId) && (element.userProvider == recentBlogs[i].userProvider));
                        })[0];
                    }

                    done(recentBlogs, null);
                }
            });
        }
    });
};

exports.truncateAndRemoveHTML = function(str, len) {
    str = sanitizeHtml(str, {
        allowedTags: [],
        allowedAttributes: {}
    });
    if (str.length > len && str.length > 0) {
        var new_str = str + " ";
        new_str = str.substr(0, len);
        new_str = str.substr(0, new_str.lastIndexOf(" "));
        new_str = (new_str.length > 0) ? new_str : str.substr(0, len);

        return new_str.trim() + '…';
    }

    // Some blogs leave annoying bits at then end, such as their own
    // continue reading link or ellipses. Remove these.
    var continueReadingPosition = str.indexOf('… Continue reading →');
    if (continueReadingPosition !== -1) {
        str = str.substring(0, continueReadingPosition);
    }

    var readMorePosition = str.indexOf('... Read more');
    if (readMorePosition !== -1) {
        str = str.substring(0, readMorePosition);
    }

    if (str.indexOf('[…]', str.length - 3) !== -1) {
        str = str.substring(0, str.length - 3);
    }

    return str.trim();
};

exports.removeAllHTML = function(blogs, len) {
    for (var i = 0; i < blogs.length; ++i) {
        blogs[i].summary = exports.truncateAndRemoveHTML(blogs[i].summary, len);
    }
}
<|endoftext|>


<commit_before>var request = require('request-promise-native')
var SSDP = require('node-ssdp').Server
const camelCase = require('uppercamelcase')
const uuidv4 = require('uuid/v4')

function loadSmartThingsAppEndpoints (token) {
  return new Promise((resolve, reject) => {
    var options = {
      headers: {
        'Authorization': `Bearer ${token}`
      },
      uri: 'https://graph.api.smartthings.com/api/smartapps/endpoints',
      json: true
    }
    request(options)
    .then(result => {
      console.log(result)
      resolve(result)
    })
    .catch(reason => {
      reject(reason)
    })
  })
}

module.exports = {

  tableName: 'device',

  findTypedDevice: function (isyDevice) {
    return new Promise((resolve, reject) => {
      var deviceType
      switch (isyDevice.deviceType) {
        case 'Light':
          deviceType = Switch
          break
        case 'DimmableLight':
          deviceType = Dimmer
          break
        case 'Fan':
          deviceType = Fan
          break
        case 'Outlet':
          deviceType = Switch
          break
        case 'Scene':
          deviceType = Scene
          break
      }
      deviceType.findOne({ isyAddress: isyDevice.address }).exec((err, device) => {
        if (err) {
          console.log(`Error fetching device record for ${device.address}`)
          reject(err)
        }
        resolve(device)
      })
    })
  },

  attributes: {

    id: {
      type: 'string',
      primaryKey: true,
      defaultsTo: function () { return uuidv4() },
      unique: true,
      index: true,
      uuidv4: true
    },

    isyType: {
      type: 'string',
      enum: ['Light', 'DimmableLight', 'Fan', 'Outlet', 'Scene'],
      required: true
    },

    isyAddress: {
      type: 'string',
      required: true,
      unique: true,
      index: true
    },

    name: {
      type: 'string',
      required: true
    },

    isAdvertised: {
      type: 'boolean',
      defaultsTo: true
    },

    refreshSeconds: {
      type: 'integer',
      defaultsTo: 300
    },

    smartThingsToken: {
      type: 'string'
    },

    isyAddressCompact: function () {
      return this.isyAddress.replace(/[ ]/g, '')
    },

    smartThingsNeworkId: function () {
      return `${process.env.INSTANCE_ID || '01'}${this.isyAddressCompact()}`
    },

    smartThingsName: function () {
      return `${this.smartThingsDeviceHandler()} [${this.isyAddress}]`
    },

    smartThingsDeviceHandler: function () {
      switch (this.isyType) {
        case 'DimmableLight':
          return 'ISY Insteon Dimmer'
        case 'Light':
          return 'ISY Insteon Switch'
        case 'Fan':
          return 'ISY Insteon Fan'
        case 'Outlet':
          return 'ISY Insteon Switch'
        case 'Scene':
          return 'ISY Insteon Scene'
      }
    },

    toJSON: function () {
      return {
        id: this.id,
        isy_type: this.isyType,
        isy_address: this.isyAddress,
        name: `${process.env.DEVICE_NAME_PREFIX || ''} ${this.name} ${process.env.DEVICE_NAME_SUFFIX || ''}`.trim(),
        description: this.description,
        smart_things_network_id: this.smartThingsNeworkId(),
        smart_things_name: this.smartThingsName(),
        smart_things_device_handler: this.smartThingsDeviceHandler(),
        refresh_seconds: this.refreshSeconds,
        is_advertised: this.isAdvertised,
        udn: this.ssdpUDN(),
        ip: this.ssdpAdvertiseIP(),
        port: this.ssdpAdvertisePort(),
        mac: this.ssdpAdvertiseMAC()
      }
    },

    isyDevice: function () {
      return sails.hooks.isy.connection().getDevice(this.isyAddress)
    },

    resetSmartThingsEndpoints: function () {
      this._smartThingsWebhookURIs = null
    },

    sendSmartThingsUpdate: function () {
      var body = { device: this.toJSON(), data: this.getStatus() }

      if (!this.smartThingsToken) {
        return null
      }

      if (!this._smartThingsWebhookURIs) {
        loadSmartThingsAppEndpoints(this.smartThingsToken).then(result => {
          this._smartThingsWebhookURIs = result.map(r => { return r.uri })
        })
      }

      this._smartThingsWebhookURIs.forEach(endpoint => {
        var options = {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${this.smartThingsToken}`
          },
          uri: `${endpoint.uri}/update`,
          body: body,
          json: true
        }
        request(options)
        .then(result => {
          console.log(`Successfully sent update ${JSON.stringify(data)} to ${endpoint.uri}/update`)
        })
        .catch(reason => {
          console.log(`Error sending update ${JSON.stringify(data)} to ${endpoint.uri}/update`)
        })
      })
    },

    ssdpUSN: function () {
      return `urn:schemas-upnp-org:device:isy:Insteon${this.isyType}:1`
    },

    ssdpUDN: function () {
      return `uuid:${this.id}`
    },

    ssdpLocation: function () {
      return `http://${this.ssdpAdvertiseIP()}:${this.ssdpAdvertisePort()}/api/device/${this.id}`
    },

    ssdpAdvertiseIP: function () {
      return sails.hooks.ssdp.advertiseIP()
    },

    ssdpAdvertisePort: function () {
      return sails.hooks.ssdp.advertisePort()
    },

    ssdpAdvertiseMAC: function () {
      return sails.hooks.ssdp.advertiseMAC()
    },

    ssdpAdvertise: function () {
      console.log(`Starting SSDP server advertising for USN: ${this.ssdpUSN()}, UDN: ${this.ssdpUDN()}, Location: ${this.ssdpLocation()}...`)

      var ssdp = new SSDP(
        {
          location: this.ssdpLocation(),
          udn: this.ssdpUDN(),
          sourcePort: 1900
        }
      )

      ssdp.addUSN(this.ssdpUSN())

      ssdp.on('advertise-alive', (headers) => {
        // Expire old devices from your cache.
        // Register advertising device somewhere (as designated in http headers heads)
        // console.log(`Advertise alive for USN: ${usn}, UDN: ${device.ssdpUDN()}, Location: ${location}`)
      })

      ssdp.on('advertise-bye', (headers) => {
        // Remove specified device from cache.
        // console.log(`Advertise bye for USN: ${usn}, UDN: ${device.ssdpUDN()}, Location: ${location}`)
      })

      ssdp.start()

      process.on('exit', () => {
        // Advertise shutting down and stop listening
        ssdp.stop()
      })

      console.log(`Started SSDP server advertising for USN: ${this.ssdpUSN()}, UDN: ${this.ssdpUDN()}, Location: ${this.ssdpLocation()}`)

      return ssdp
    }
  }
}
<commit_msg>Cleanup<commit_after>var request = require('request-promise-native')
var SSDP = require('node-ssdp').Server
const camelCase = require('uppercamelcase')
const uuidv4 = require('uuid/v4')

function loadSmartThingsAppEndpoints (token) {
  return new Promise((resolve, reject) => {
    var options = {
      headers: {
        'Authorization': `Bearer ${token}`
      },
      uri: 'https://graph.api.smartthings.com/api/smartapps/endpoints',
      json: true
    }
    request(options)
    .then(result => {
      console.log(result)
      resolve(result)
    })
    .catch(reason => {
      reject(reason)
    })
  })
}

module.exports = {

  tableName: 'device',

  findTypedDevice: function (isyDevice) {
    return new Promise((resolve, reject) => {
      var deviceType
      switch (isyDevice.deviceType) {
        case 'Light':
          deviceType = Switch
          break
        case 'DimmableLight':
          deviceType = Dimmer
          break
        case 'Fan':
          deviceType = Fan
          break
        case 'Outlet':
          deviceType = Switch
          break
        case 'Scene':
          deviceType = Scene
          break
      }
      deviceType.findOne({ isyAddress: isyDevice.address }).exec((err, device) => {
        if (err) {
          console.log(`Error fetching device record for ${device.address}`)
          reject(err)
        }
        resolve(device)
      })
    })
  },

  attributes: {

    id: {
      type: 'string',
      primaryKey: true,
      defaultsTo: function () { return uuidv4() },
      unique: true,
      index: true,
      uuidv4: true
    },

    isyType: {
      type: 'string',
      enum: ['Light', 'DimmableLight', 'Fan', 'Outlet', 'Scene'],
      required: true
    },

    isyAddress: {
      type: 'string',
      required: true,
      unique: true,
      index: true
    },

    name: {
      type: 'string',
      required: true
    },

    isAdvertised: {
      type: 'boolean',
      defaultsTo: true
    },

    refreshSeconds: {
      type: 'integer',
      defaultsTo: 300
    },

    smartThingsToken: {
      type: 'string'
    },

    isyAddressCompact: function () {
      return this.isyAddress.replace(/[ ]/g, '')
    },

    smartThingsName: function () {
      return `${this.smartThingsDeviceHandler()} [${this.isyAddress}]`
    },

    smartThingsDeviceHandler: function () {
      switch (this.isyType) {
        case 'DimmableLight':
          return 'ISY Insteon Dimmer'
        case 'Light':
          return 'ISY Insteon Switch'
        case 'Fan':
          return 'ISY Insteon Fan'
        case 'Outlet':
          return 'ISY Insteon Switch'
        case 'Scene':
          return 'ISY Insteon Scene'
      }
    },

    toJSON: function () {
      return {
        id: this.id,
        isy_type: this.isyType,
        isy_address: this.isyAddress,
        name: `${process.env.DEVICE_NAME_PREFIX || ''} ${this.name} ${process.env.DEVICE_NAME_SUFFIX || ''}`.trim(),
        description: this.description,
        smart_things_network_id: this.smartThingsNeworkId(),
        smart_things_name: this.smartThingsName(),
        smart_things_device_handler: this.smartThingsDeviceHandler(),
        refresh_seconds: this.refreshSeconds,
        is_advertised: this.isAdvertised,
        udn: this.ssdpUDN(),
        ip: this.ssdpAdvertiseIP(),
        port: this.ssdpAdvertisePort(),
        mac: this.ssdpAdvertiseMAC()
      }
    },

    isyDevice: function () {
      return sails.hooks.isy.connection().getDevice(this.isyAddress)
    },

    resetSmartThingsEndpoints: function () {
      this._smartThingsWebhookURIs = null
    },

    sendSmartThingsUpdate: function () {
      var body = { device: this.toJSON(), data: this.getStatus() }

      if (!this.smartThingsToken) {
        return null
      }

      if (!this._smartThingsWebhookURIs) {
        loadSmartThingsAppEndpoints(this.smartThingsToken).then(result => {
          this._smartThingsWebhookURIs = result.map(r => { return r.uri })
        })
      }

      this._smartThingsWebhookURIs.forEach(endpoint => {
        var options = {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${this.smartThingsToken}`
          },
          uri: `${endpoint.uri}/update`,
          body: body,
          json: true
        }
        request(options)
        .then(result => {
          console.log(`Successfully sent update ${JSON.stringify(data)} to ${endpoint.uri}/update`)
        })
        .catch(reason => {
          console.log(`Error sending update ${JSON.stringify(data)} to ${endpoint.uri}/update`)
        })
      })
    },

    ssdpUSN: function () {
      return `urn:schemas-upnp-org:device:isy:Insteon${this.isyType}:1`
    },

    ssdpUDN: function () {
      return `uuid:${this.id}`
    },

    ssdpLocation: function () {
      return `http://${this.ssdpAdvertiseIP()}:${this.ssdpAdvertisePort()}/api/device/${this.id}`
    },

    ssdpAdvertiseIP: function () {
      return sails.hooks.ssdp.advertiseIP()
    },

    ssdpAdvertisePort: function () {
      return sails.hooks.ssdp.advertisePort()
    },

    ssdpAdvertiseMAC: function () {
      return sails.hooks.ssdp.advertiseMAC()
    },

    ssdpAdvertise: function () {
      console.log(`Starting SSDP server advertising for USN: ${this.ssdpUSN()}, UDN: ${this.ssdpUDN()}, Location: ${this.ssdpLocation()}...`)

      var ssdp = new SSDP(
        {
          location: this.ssdpLocation(),
          udn: this.ssdpUDN(),
          sourcePort: 1900
        }
      )

      ssdp.addUSN(this.ssdpUSN())

      ssdp.on('advertise-alive', (headers) => {
        // Expire old devices from your cache.
        // Register advertising device somewhere (as designated in http headers heads)
        // console.log(`Advertise alive for USN: ${usn}, UDN: ${device.ssdpUDN()}, Location: ${location}`)
      })

      ssdp.on('advertise-bye', (headers) => {
        // Remove specified device from cache.
        // console.log(`Advertise bye for USN: ${usn}, UDN: ${device.ssdpUDN()}, Location: ${location}`)
      })

      ssdp.start()

      process.on('exit', () => {
        // Advertise shutting down and stop listening
        ssdp.stop()
      })

      console.log(`Started SSDP server advertising for USN: ${this.ssdpUSN()}, UDN: ${this.ssdpUDN()}, Location: ${this.ssdpLocation()}`)

      return ssdp
    }
  }
}
<|endoftext|>


<commit_before>var pmongoose = require("mongoose");
var Photo = require("./schema").Photo;

function newGallery(data, callback) {

	var newPhoto = new Photo(data);

	Photo.create(newPhoto, function(err, data) {
		if (err) {
			return callback(err, null);
		}
		else {
			return callback(null, data);
		}

	});
}

function findGallery(data, callback) {

	var query = {"user": data};

	Photo.findOne(query, function(err, data) {

		if (err) {
			return callback(err);
		}
		else {
			return callback(null, data);
		}
	});
}

function newPhoto(id, update, callback) {

	var query = {"user": id};

	Photo.findOneAndUpdate(query, update, function(err, data) {

		if (err) {
			return callback(err);
		}
		else {
			return callback(null, data);
		}
	});
}

function deleteURL() {

}

module.exports = {
	newGallery: newGallery,
	findGallery: findGallery,
	newPhoto: newPhoto,
	deleteURL: deleteURL
};<commit_msg>delete function<commit_after>var pmongoose = require("mongoose");
var Photo = require("./schema").Photo;

function newGallery(data, callback) {

	var newPhoto = new Photo(data);

	Photo.create(newPhoto, function(err, data) {

		if (err) {
			return callback(err, null);
		}
		else {
			return callback(null, data);
		}

	});
}

function findGallery(data, callback) {

	var query = {"user": data};

	Photo.findOne(query, function(err, data) {

		if (err) {
			return callback(err, null);
		}
		else {
			return callback(null, data);
		}
	});
}

function newPhoto(id, update, callback) {

	var query = {"user": id};

	Photo.findOneAndUpdate(query, update, function(err, data) {

		if (err) {
			return callback(err, null);
		}
		else {
			return callback(null, data);
		}
	});
}

function deleteURL(id, photo, callback) {

	var url = Object.keys(photo)[0];
	console.log(photo);
	var query = {"user": id};
	var remove = { $pull: {"photos": {"url": url}}};

	Photo.findOneAndUpdate(query, remove, function(err, data) {
		console.log(query, remove, data);
		if (err) {
			return callback(err, null);
		}
		else {
			return callback(null, data);
		}
	});
}

module.exports = {
	newGallery: newGallery,
	findGallery: findGallery,
	newPhoto: newPhoto,
	deleteURL: deleteURL
};<|endoftext|>