<commit_before>var request = require('request');
// bloo bloo
function APIClient(_appKey, _appSecret) {

    this.appKey = _appKey;
    this.appSecret = _appSecret;

    this.auth = new Buffer(this.appKey + ":" + this.appSecret).toString('base64');

    this.getKey = function getKey(){
        return this.appKey;
    }

    this.getSecret = function getSecret(){
        return this.appSecret;
    }

    this.getTags = function getTags(callback){
        var options = {
              method: 'GET'
            , auth: { user: client.appKey, pass: client.appSecret, sendImmediately: true }
            , uri: 'https://go.urbanairship.com/api/tags'
            , header: 'Content-type: application/vnd.urbanairship+json; version=3; charset=utf8;'
        }
        request(options, callback);
    }

    this.createTag = function createTag(tag, callback){
        var options = {
              method: 'PUT'
            , auth: { user: client.appKey, pass: client.appSecret, sendImmediately: true }
            , url: 'https://go.urbanairship.com/api/tags/' + tag
            , header: 'Content-type: application/vnd.urbanairship+json; version=3; charset=utf8;'
        }
        request(options, callback);
    }

    this.deleteTag = function deleteTag(tag, callback){
        var options = {
              method: 'DELETE'
            , auth: { user: client.appKey, pass: client.appSecret, sendImmediately: true }
            , url: 'https://go.urbanairship.com/api/tags/' + tag
            , header: 'Content-type: application/vnd.urbanairship+json; version=3; charset=utf8;'
        }
        request(options, callback);
    }

    this.getDeviceTokens = function getDeviceTokens(callback){
        var options = {
              method: 'GET'
            , auth: { user: client.appKey, pass: client.appSecret, sendImmediately: true }
            , url: 'https://go.urbanairship.com/api/device_tokens/'
            , header: 'Content-type: application/vnd.urbanairship+json; version=3; charset=utf8;'
        }
        request(options, callback);
    }

    this.getDeviceToken = function getDeviceTokens(deviceToken, callback){
        var options = {
              method: 'GET'
            , auth: { user: client.appKey, pass: client.appSecret, sendImmediately: true }
            , url: 'https://go.urbanairship.com/api/device_tokens/' + deviceToken
            , header: 'Content-type: application/vnd.urbanairship+json; version=3; charset=utf8;'
        }
        request(options, callback);
    }

    this.getApids = function getApids(callback){
        var options = {
              method: 'GET'
            , auth: { user: client.appKey, pass: client.appSecret, sendImmediately: true }
            , url: 'https://go.urbanairship.com/api/apids/'
            , header: 'Content-type: application/vnd.urbanairship+json; version=3; charset=utf8;'
        }
        request(options, callback);
    }

    this.getApid = function getApid(apid, callback){
        var options = {
              method: 'GET'
            , auth: { user: client.appKey, pass: client.appSecret, sendImmediately: true }
            , url: 'https://go.urbanairship.com/api/apids/' + apid
            , header: 'Content-type: application/vnd.urbanairship+json; version=3; charset=utf8;'
        }
        request(options, callback);
    }

    this.sendPush = function sendPush(push, callback){

        // build payload
        payload = push.toJSON();

        var b = JSON.stringify(payload);

        var options = {
              method: 'POST'
            , auth: { user: client.appKey, pass: client.appSecret, sendImmediately: true }
            , url: 'https://go.urbanairship.com/api/push/'
            , body: b
            , headers: { 'Accept' : 'application/vnd.urbanairship+json; version=3; charset=utf8;'
                       , 'Content-Type' : 'application/json'
                    }
        }
        request(options, callback);
    }

}

function DeviceType() {
    this.IOS = "ios";
    this.ANDROID = "android";
    this.ALL = "all";
}

function Push() {

    this.notifications = [];
    this.audience = {};

    this.addNotification = function addNotification(notification){
        this.notifications.push(notification);
    }

    this.setAudience = function(selector){
        this.audience = selector;
    }

    this.toJSON = function(){
        var payload = {};

        // parse the device types in the list of notifications, do any of them have all?
        var anyNotificationSetToAll = false;
        this.notifications.forEach(function(notification){
            if (notification.deviceType === 'all') {
                anyNotificationSetToAll = true;
            }
        })

        if (!anyNotificationSetToAll) {
            // build an array of notificatons from the device types
            payload.device_types = [];
            this.notifications.forEach(function(notification){
                payload.device_types.push(notification.deviceType)
            })
        }
        else {
            payload.device_types = 'all';
        }

        payload.notification = {}

        this.notifications.forEach(function(notification){
            if (notification.deviceType === 'all') {

                payload.notification.alert = notification.alert;

            } else if (notification.deviceType === 'ios'){

                payload.notification.ios = {}

                if (notification.alert !== undefined) {
                    payload.notification.ios.alert = notification.alert
                }

                if (notification.badge !== undefined) {
                    payload.notification.ios.badge = notification.badge
                }

                if (notification.extras.length > 0) {
                    payload.notification.ios.extra = {}
                    notification.extras.forEach(function(extra){
                        payload.notification.ios.extra[extra.key] = extra.value
                    })
                }

            } else if (notification.deviceType === 'android') {

                payload.notification.android = {}

                if (notification.alert !== undefined) {
                    payload.notification.android.alert = notification.alert
                }

                if (notification.extras.length > 0) {
                    payload.notification.android.extra = {}
                    notification.extras.forEach(function(extra){
                        payload.notification.android.extra[extra.key] = extra.value
                    })
                }
            }

        });

        if(this.audience.operator !== undefined){
            payload.audience = this.audience.toJSON();
        }
        else {
            payload.audience = "all";
        }

        return payload;

    }
}

function Notification() {

    this.deviceType;
    this.badge;
    this.alert;
    this.extras = [];

    this.setDeviceType = function setDeviceType(deviceType){
        this.deviceType = deviceType;
    }

    this.setBadge = function setBadge(badge){
        this.badge = badge;
    }

    this.setAlert = function setAlert(alert){
        this.alert = alert;
    }

    this.addExtra = function addExtra(k,v){
        this.extras.push({ key: k, value: v});
    }

}

function Selector(booleanOperator) {

    this.operator = booleanOperator
    this.tags = []
    this.aliases = []
    this.deviceTokens = []
    this.apids = []
    this.selectors = []

    this.addTag = function(tag){
        this.tags.push(tag)
    }

    this.addAlias = function(alias){
        this.aliases.push(alias)
    }

    this.addDeviceToken = function(deviceToken){
        this.deviceTokens.push(deviceToken)
    }

    this.addApid = function(apid){
        this.apids.push(apid)
    }

    this.addSelector = function(selector){
        this.selectors.push(selector)
    }

    this.toJSON = function(){

        var payload = {}
        payload[this.operator] = []
        var nested = payload[this.operator]

        this.tags.forEach(function(tag){
            nested.push({ "tag":tag })
        })

        this.aliases.forEach(function(alias){
            nested.push({ "alias": alias })
        })

        this.deviceTokens.forEach(function(deviceToken){
            nested.push({ "device_token" : deviceToken })
        })

        this.apids.forEach(function(apid){
            nested.push({ "apid" : apid })
        })

        this.selectors.forEach(function(selector){
           nested.push(selector.toJSON())
        })

        // sometimes the selector is nothing
        if (nested.length === 0) {
            payload = "all";
        }

        return payload;
    }

}

var client = new APIClient('YPDu34kcS6q42ioANsv8KA', 'IXGz8cn_TdmnSJ44N6ssAg');

// build audience
var s = new Selector("AND");
    s.addTag("foo");

    var s2 = new Selector("OR");
    s2.addTag("bar");
    s2.addTag("baz");
    s.addSelector(s2);

// build notification
var n = new Notification();
    n.setDeviceType(new DeviceType().ALL);
    n.setAlert("YAY. BASIC ALERT.");

var n2 = new Notification();
    n2.setDeviceType(new DeviceType().IOS);
    n2.setAlert("YAY IOS.");
    n2.setBadge(0);
    n2.addExtra('url', 'http://apple.com');

var n3 = new Notification();
    n3.setDeviceType(new DeviceType().ANDROID);
    n3.setAlert("YAY Android.");
    n3.addExtra('url', 'http://google.com');

// build push
var p = new Push();
    p.addNotification(n)
    p.addNotification(n2)
    p.addNotification(n3);
    // p.setAudience(s)

    console.log(JSON.stringify(p.toJSON(),null,4));

client.sendPush(p, displayResults);

// client.getApids(displayResults)
// client.getApid("b7962a6b-4c54-456d-91d1-de1466788db2", displayResults)
// client.getDeviceTokens(displayResults)
// client.getDeviceToken('068A81174355005612A4BA390B99E6F7BC7567F754C54D1B079EABAC8340A1E1', displayResults)
// client.getTags(displayResults)
// client.createTag("library", displayResults)
// client.deleteTag("library", displayResults)

function displayResults(error, response, body) {

    console.log("");

    if (error !== null) {
        console.log("Error");
        console.log(error);
    }

    console.log("Response Status Code : " + response.statusCode);

    console.log("Body");
    console.log(JSON.stringify(JSON.parse(body),null,2));

    // process.exit(0);

}

//435334

/*

    Todo:

*/

<commit_msg>lewlewl<commit_after>var request = require('request');
// bloo bloo
function APIClient(_appKey, _appSecret) {

    this.appKey = _appKey;
    this.appSecret = _appSecret;

    this.auth = new Buffer(this.appKey + ":" + this.appSecret).toString('base64');

    this.getKey = function getKey(){
        return this.appKey;
    }

    this.getSecret = function getSecret(){
        return this.appSecret;
    }

    this.getTags = function getTags(ready){
        var options = {
              method: 'GET'
            , auth: { user: client.appKey, pass: client.appSecret, sendImmediately: true }
            , uri: 'https://go.urbanairship.com/api/tags'
            , header: 'Content-type: application/vnd.urbanairship+json; version=3; charset=utf8;'
        }
        request(options, ready);
    }

    this.createTag = function createTag(tag, ready){
        var options = {
              method: 'PUT'
            , auth: { user: client.appKey, pass: client.appSecret, sendImmediately: true }
            , url: 'https://go.urbanairship.com/api/tags/' + tag
            , header: 'Content-type: application/vnd.urbanairship+json; version=3; charset=utf8;'
        }
        request(options, ready);
    }

    this.deleteTag = function deleteTag(tag, ready){
        var options = {
              method: 'DELETE'
            , auth: { user: client.appKey, pass: client.appSecret, sendImmediately: true }
            , url: 'https://go.urbanairship.com/api/tags/' + tag
            , header: 'Content-type: application/vnd.urbanairship+json; version=3; charset=utf8;'
        }
        request(options, ready);
    }

    this.getDeviceTokens = function getDeviceTokens(ready){
        var options = {
              method: 'GET'
            , auth: { user: client.appKey, pass: client.appSecret, sendImmediately: true }
            , url: 'https://go.urbanairship.com/api/device_tokens/'
            , header: 'Content-type: application/vnd.urbanairship+json; version=3; charset=utf8;'
        }
        request(options, ready);
    }

    this.getDeviceToken = function getDeviceTokens(deviceToken, ready){
        var options = {
              method: 'GET'
            , auth: { user: client.appKey, pass: client.appSecret, sendImmediately: true }
            , url: 'https://go.urbanairship.com/api/device_tokens/' + deviceToken
            , header: 'Content-type: application/vnd.urbanairship+json; version=3; charset=utf8;'
        }
        request(options, ready);
    }

    this.getApids = function getApids(ready){
        var options = {
              method: 'GET'
            , auth: { user: client.appKey, pass: client.appSecret, sendImmediately: true }
            , url: 'https://go.urbanairship.com/api/apids/'
            , header: 'Content-type: application/vnd.urbanairship+json; version=3; charset=utf8;'
        }
        request(options, ready);
    }

    this.getApid = function getApid(apid, ready){
        var options = {
              method: 'GET'
            , auth: { user: client.appKey, pass: client.appSecret, sendImmediately: true }
            , url: 'https://go.urbanairship.com/api/apids/' + apid
            , header: 'Content-type: application/vnd.urbanairship+json; version=3; charset=utf8;'
        }
        request(options, ready);
    }

    this.sendPush = function sendPush(push, ready){

        // build payload
        payload = push.toJSON();

        var b = JSON.stringify(payload);

        var options = {
              method: 'POST'
            , auth: { user: client.appKey, pass: client.appSecret, sendImmediately: true }
            , url: 'https://go.urbanairship.com/api/push/'
            , body: b
            , headers: { 'Accept' : 'application/vnd.urbanairship+json; version=3; charset=utf8;'
                       , 'Content-Type' : 'application/json'
                    }
        }
        request(options, ready);
    }

}

function DeviceType() {
    this.IOS = "ios";
    this.ANDROID = "android";
    this.ALL = "all";
}

function Push() {

    this.notifications = [];
    this.audience = {};

    this.addNotification = function addNotification(notification){
        this.notifications.push(notification);
    }

    this.setAudience = function(selector){
        this.audience = selector;
    }

    this.toJSON = function(){
        var payload = {};

        // parse the device types in the list of notifications, do any of them have all?
        var anyNotificationSetToAll = false;
        this.notifications.forEach(function(notification){
            if (notification.deviceType === 'all') {
                anyNotificationSetToAll = true;
            }
        })

        if (!anyNotificationSetToAll) {
            // build an array of notificatons from the device types
            payload.device_types = [];
            this.notifications.forEach(function(notification){
                payload.device_types.push(notification.deviceType)
            })
        }
        else {
            payload.device_types = 'all';
        }

        payload.notification = {}

        this.notifications.forEach(function(notification){
            if (notification.deviceType === 'all') {

                payload.notification.alert = notification.alert;

            } else if (notification.deviceType === 'ios'){

                payload.notification.ios = {}

                if (notification.alert !== undefined) {
                    payload.notification.ios.alert = notification.alert
                }

                if (notification.badge !== undefined) {
                    payload.notification.ios.badge = notification.badge
                }

                if (notification.extras.length > 0) {
                    payload.notification.ios.extra = {}
                    notification.extras.forEach(function(extra){
                        payload.notification.ios.extra[extra.key] = extra.value
                    })
                }

            } else if (notification.deviceType === 'android') {

                payload.notification.android = {}

                if (notification.alert !== undefined) {
                    payload.notification.android.alert = notification.alert
                }

                if (notification.extras.length > 0) {
                    payload.notification.android.extra = {}
                    notification.extras.forEach(function(extra){
                        payload.notification.android.extra[extra.key] = extra.value
                    })
                }
            }

        });

        if(this.audience.operator !== undefined){
            payload.audience = this.audience.toJSON();
        }
        else {
            payload.audience = "all";
        }

        return payload;

    }
}

function Notification() {

    this.deviceType;
    this.badge;
    this.alert;
    this.extras = [];

    this.setDeviceType = function setDeviceType(deviceType){
        this.deviceType = deviceType;
    }

    this.setBadge = function setBadge(badge){
        this.badge = badge;
    }

    this.setAlert = function setAlert(alert){
        this.alert = alert;
    }

    this.addExtra = function addExtra(k,v){
        this.extras.push({ key: k, value: v});
    }

}

function Selector(booleanOperator) {

    this.operator = booleanOperator
    this.tags = []
    this.aliases = []
    this.deviceTokens = []
    this.apids = []
    this.selectors = []

    this.addTag = function(tag){
        this.tags.push(tag)
    }

    this.addAlias = function(alias){
        this.aliases.push(alias)
    }

    this.addDeviceToken = function(deviceToken){
        this.deviceTokens.push(deviceToken)
    }

    this.addApid = function(apid){
        this.apids.push(apid)
    }

    this.addSelector = function(selector){
        this.selectors.push(selector)
    }

    this.toJSON = function(){

        var payload = {}
        payload[this.operator] = []
        var nested = payload[this.operator]

        this.tags.forEach(function(tag){
            nested.push({ "tag":tag })
        })

        this.aliases.forEach(function(alias){
            nested.push({ "alias": alias })
        })

        this.deviceTokens.forEach(function(deviceToken){
            nested.push({ "device_token" : deviceToken })
        })

        this.apids.forEach(function(apid){
            nested.push({ "apid" : apid })
        })

        this.selectors.forEach(function(selector){
           nested.push(selector.toJSON())
        })

        // sometimes the selector is nothing
        if (nested.length === 0) {
            payload = "all";
        }

        return payload;
    }

}

var client = new APIClient('YPDu34kcS6q42ioANsv8KA', 'IXGz8cn_TdmnSJ44N6ssAg');

// build audience
var s = new Selector("AND");
    s.addTag("foo");

    var s2 = new Selector("OR");
    s2.addTag("bar");
    s2.addTag("baz");
    s.addSelector(s2);

// build notification
var n = new Notification();
    n.setDeviceType(new DeviceType().ALL);
    n.setAlert("YAY. BASIC ALERT.");

var n2 = new Notification();
    n2.setDeviceType(new DeviceType().IOS);
    n2.setAlert("YAY IOS.");
    n2.setBadge(0);
    n2.addExtra('url', 'http://apple.com');

var n3 = new Notification();
    n3.setDeviceType(new DeviceType().ANDROID);
    n3.setAlert("YAY Android.");
    n3.addExtra('url', 'http://google.com');

// build push
var p = new Push();
    p.addNotification(n)
    p.addNotification(n2)
    p.addNotification(n3);
    // p.setAudience(s)

    console.log(JSON.stringify(p.toJSON(),null,4));

client.sendPush(p, displayResults);

// client.getApids(displayResults)
// client.getApid("b7962a6b-4c54-456d-91d1-de1466788db2", displayResults)
// client.getDeviceTokens(displayResults)
// client.getDeviceToken('068A81174355005612A4BA390B99E6F7BC7567F754C54D1B079EABAC8340A1E1', displayResults)
// client.getTags(displayResults)
// client.createTag("library", displayResults)
// client.deleteTag("library", displayResults)

function displayResults(error, response, body) {

    console.log("");

    if (error !== null) {
        console.log("Error");
        console.log(error);
    }

    console.log("Response Status Code : " + response.statusCode);

    console.log("Body");
    console.log(JSON.stringify(JSON.parse(body),null,2));

    // process.exit(0);

}

//435334

/*

    Todo:

*/

<|endoftext|>


<commit_before>import Service from '@ember/service';
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import moment from 'moment';
import { setupMirage } from 'ember-cli-mirage/test-support';

module('Integration | Service | school events', function (hooks) {
  setupTest(hooks);
  setupMirage(hooks);

  test('getEvents', async function (assert) {
    assert.expect(21);
    const event1 = {
      offering: 1,
      startDate: '2011-04-21',
      school: 7,
      prerequisites: [],
      postrequisites: [],
    };
    const event2 = {
      ilmSession: 3,
      startDate: '2008-09-02',
      school: 7,
      prerequisites: [],
      postrequisites: [],
    };
    const from = moment('20150305', 'YYYYMMDD').hour(0);
    const to = from.clone().hour(24);

    this.server.get(`/api/schoolevents/:id`, (scheme, { params, queryParams }) => {
      assert.ok('id' in params);
      assert.strictEqual(parseInt(params.id, 10), 7);
      assert.ok('from' in queryParams);
      assert.ok('to' in queryParams);
      assert.strictEqual(parseInt(queryParams.from, 10), from.unix());
      assert.strictEqual(parseInt(queryParams.to, 10), to.unix());

      return { events: [event1, event2] };
    });
    const schoolId = 7;
    const subject = this.owner.lookup('service:school-events');
    const events = await subject.getEvents(schoolId, from.unix(), to.unix());
    assert.strictEqual(events.length, 2);
    assert.strictEqual(events[0].ilmSession, event2.ilmSession);
    assert.strictEqual(events[0].startDate, event2.startDate);
    assert.strictEqual(events[0].school, event2.school);
    assert.deepEqual(events[0].prerequisites, event2.prerequisites);
    assert.deepEqual(events[0].postrequisites, event2.postrequisites);
    assert.strictEqual(events[0].slug, 'S0720080902I3');
    assert.notOk(events[0].isBlanked);

    assert.strictEqual(events[1].offering, event1.offering);
    assert.strictEqual(events[1].startDate, event1.startDate);
    assert.strictEqual(events[1].school, event1.school);
    assert.deepEqual(events[1].prerequisites, event1.prerequisites);
    assert.deepEqual(events[1].postrequisites, event1.postrequisites);
    assert.strictEqual(events[1].slug, 'S0720110421O1');
    assert.notOk(events[1].isBlanked);
  });

  test('getEvents - with configured namespace', async function (assert) {
    assert.expect(4);
    const iliosConfigMock = Service.extend({
      apiNameSpace: 'geflarknik',
    });
    this.owner.register('service:iliosConfig', iliosConfigMock);

    const from = moment('20150305', 'YYYYMMDD').hour(0);
    const to = from.clone().hour(24);
    this.server.get(`/geflarknik/schoolevents/:id`, (scheme, { params, queryParams }) => {
      assert.strictEqual(parseInt(params.id, 10), 3);
      assert.strictEqual(parseInt(queryParams.from, 10), from.unix());
      assert.strictEqual(parseInt(queryParams.to, 10), to.unix());
      return { events: [] };
    });
    const subject = this.owner.lookup('service:school-events');
    const schoolId = 3;
    const events = await subject.getEvents(schoolId, from.unix(), to.unix());
    assert.strictEqual(events.length, 0);
  });

  test('getEventForSlug - offering', async function (assert) {
    assert.expect(10);
    const event1 = {
      offering: 1,
      startDate: '2011-04-21',
      school: 7,
      prerequisites: [],
      postrequisites: [],
    };
    const event2 = {
      ilmSession: 3,
      startDate: '2008-09-02',
      school: 7,
      prerequisites: [],
      postrequisites: [],
    };
    this.server.get(`/api/schoolevents/:id`, (scheme, { params, queryParams }) => {
      const from = moment('20110421', 'YYYYMMDD').hour(0);
      const to = from.clone().hour(24);
      assert.strictEqual(parseInt(params.id, 10), 7);
      assert.strictEqual(parseInt(queryParams.from, 10), from.unix());
      assert.strictEqual(parseInt(queryParams.to, 10), to.unix());

      return { events: [event1, event2] };
    });

    const subject = this.owner.lookup('service:school-events');
    const event = await subject.getEventForSlug('S0720110421O1');
    assert.strictEqual(event.offering, event1.offering);
    assert.strictEqual(event.startDate, event1.startDate);
    assert.strictEqual(event.school, event1.school);
    assert.deepEqual(event.prerequisites, event1.prerequisites);
    assert.deepEqual(event.postrequisites, event1.postrequisites);
    assert.strictEqual(event.slug, 'S0720110421O1');
    assert.notOk(event.isBlanked);
  });

  test('getEventForSlug - ILM', async function (assert) {
    assert.expect(10);
    const event1 = {
      offering: 1,
      startDate: '2011-04-21',
      school: 7,
      prerequisites: [],
      postrequisites: [],
    };
    const event2 = {
      ilmSession: 3,
      startDate: '2008-09-02',
      school: 7,
      prerequisites: [],
      postrequisites: [],
    };
    this.server.get(`/api/schoolevents/:id`, (scheme, { params, queryParams }) => {
      const from = moment('20080902', 'YYYYMMDD').hour(0);
      const to = from.clone().hour(24);
      assert.strictEqual(parseInt(params.id, 10), 7);
      assert.strictEqual(parseInt(queryParams.from, 10), from.unix());
      assert.strictEqual(parseInt(queryParams.to, 10), to.unix());

      return { events: [event1, event2] };
    });

    const subject = this.owner.lookup('service:school-events');
    const event = await subject.getEventForSlug('S0720080902I3');
    assert.strictEqual(event.ilmSession, event2.ilmSession);
    assert.strictEqual(event.startDate, event2.startDate);
    assert.strictEqual(event.school, event2.school);
    assert.deepEqual(event.prerequisites, event2.prerequisites);
    assert.deepEqual(event.postrequisites, event2.postrequisites);
    assert.strictEqual(event.slug, 'S0720080902I3');
    assert.notOk(event.isBlanked);
  });
});
<commit_msg>Replace moment with luxon in test<commit_after>import Service from '@ember/service';
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import { DateTime } from 'luxon';
import { setupMirage } from 'ember-cli-mirage/test-support';

module('Integration | Service | school events', function (hooks) {
  setupTest(hooks);
  setupMirage(hooks);

  test('getEvents', async function (assert) {
    assert.expect(21);
    const event1 = {
      offering: 1,
      startDate: '2011-04-21',
      school: 7,
      prerequisites: [],
      postrequisites: [],
    };
    const event2 = {
      ilmSession: 3,
      startDate: '2008-09-02',
      school: 7,
      prerequisites: [],
      postrequisites: [],
    };
    const from = DateTime.fromObject({ year: 2015, month: 3, day: 5, hour: 0 });
    const to = from.set({ hour: 24 });

    this.server.get(`/api/schoolevents/:id`, (scheme, { params, queryParams }) => {
      assert.ok('id' in params);
      assert.strictEqual(Number(params.id), 7);
      assert.ok('from' in queryParams);
      assert.ok('to' in queryParams);
      assert.strictEqual(Number(queryParams.from), from.toSeconds());
      assert.strictEqual(Number(queryParams.to), to.toSeconds());

      return { events: [event1, event2] };
    });
    const schoolId = 7;
    const subject = this.owner.lookup('service:school-events');
    const events = await subject.getEvents(schoolId, from.toSeconds(), to.toSeconds());
    assert.strictEqual(events.length, 2);
    assert.strictEqual(events[0].ilmSession, event2.ilmSession);
    assert.strictEqual(events[0].startDate, event2.startDate);
    assert.strictEqual(events[0].school, event2.school);
    assert.deepEqual(events[0].prerequisites, event2.prerequisites);
    assert.deepEqual(events[0].postrequisites, event2.postrequisites);
    assert.strictEqual(events[0].slug, 'S0720080902I3');
    assert.notOk(events[0].isBlanked);

    assert.strictEqual(events[1].offering, event1.offering);
    assert.strictEqual(events[1].startDate, event1.startDate);
    assert.strictEqual(events[1].school, event1.school);
    assert.deepEqual(events[1].prerequisites, event1.prerequisites);
    assert.deepEqual(events[1].postrequisites, event1.postrequisites);
    assert.strictEqual(events[1].slug, 'S0720110421O1');
    assert.notOk(events[1].isBlanked);
  });

  test('getEvents - with configured namespace', async function (assert) {
    assert.expect(4);
    const iliosConfigMock = Service.extend({
      apiNameSpace: 'geflarknik',
    });
    this.owner.register('service:iliosConfig', iliosConfigMock);

    const from = DateTime.fromObject({ year: 2015, month: 3, day: 5, hour: 0 });
    const to = from.set({ hour: 24 });

    this.server.get(`/geflarknik/schoolevents/:id`, (scheme, { params, queryParams }) => {
      assert.strictEqual(Number(params.id), 3);
      assert.strictEqual(Number(queryParams.from), from.toSeconds());
      assert.strictEqual(Number(queryParams.to), to.toSeconds());
      return { events: [] };
    });
    const subject = this.owner.lookup('service:school-events');
    const schoolId = 3;
    const events = await subject.getEvents(schoolId, from.toSeconds(), to.toSeconds());
    assert.strictEqual(events.length, 0);
  });

  test('getEventForSlug - offering', async function (assert) {
    assert.expect(10);
    const event1 = {
      offering: 1,
      startDate: '2011-04-21',
      school: 7,
      prerequisites: [],
      postrequisites: [],
    };
    const event2 = {
      ilmSession: 3,
      startDate: '2008-09-02',
      school: 7,
      prerequisites: [],
      postrequisites: [],
    };
    this.server.get(`/api/schoolevents/:id`, (scheme, { params, queryParams }) => {
      const from = DateTime.fromObject({ year: 2011, month: 4, day: 21, hour: 0 });
      const to = from.set({ hour: 24 });
      assert.strictEqual(Number(params.id), 7);
      assert.strictEqual(Number(queryParams.from), from.toSeconds());
      assert.strictEqual(Number(queryParams.to), to.toSeconds());

      return { events: [event1, event2] };
    });

    const subject = this.owner.lookup('service:school-events');
    const event = await subject.getEventForSlug('S0720110421O1');
    assert.strictEqual(event.offering, event1.offering);
    assert.strictEqual(event.startDate, event1.startDate);
    assert.strictEqual(event.school, event1.school);
    assert.deepEqual(event.prerequisites, event1.prerequisites);
    assert.deepEqual(event.postrequisites, event1.postrequisites);
    assert.strictEqual(event.slug, 'S0720110421O1');
    assert.notOk(event.isBlanked);
  });

  test('getEventForSlug - ILM', async function (assert) {
    assert.expect(10);
    const event1 = {
      offering: 1,
      startDate: '2011-04-21',
      school: 7,
      prerequisites: [],
      postrequisites: [],
    };
    const event2 = {
      ilmSession: 3,
      startDate: '2008-09-02',
      school: 7,
      prerequisites: [],
      postrequisites: [],
    };
    this.server.get(`/api/schoolevents/:id`, (scheme, { params, queryParams }) => {
      const from = DateTime.fromObject({ year: 2008, month: 9, day: 2, hour: 0 });
      const to = from.set({ hour: 24 });

      assert.strictEqual(Number(params.id), 7);
      assert.strictEqual(Number(queryParams.from), from.toSeconds());
      assert.strictEqual(Number(queryParams.to), to.toSeconds());

      return { events: [event1, event2] };
    });

    const subject = this.owner.lookup('service:school-events');
    const event = await subject.getEventForSlug('S0720080902I3');
    assert.strictEqual(event.ilmSession, event2.ilmSession);
    assert.strictEqual(event.startDate, event2.startDate);
    assert.strictEqual(event.school, event2.school);
    assert.deepEqual(event.prerequisites, event2.prerequisites);
    assert.deepEqual(event.postrequisites, event2.postrequisites);
    assert.strictEqual(event.slug, 'S0720080902I3');
    assert.notOk(event.isBlanked);
  });
});
<|endoftext|>


<commit_before>const mongoose = require('mongoose');
const router = require('express').Router();
const bodyParser = require('body-parser').json();
const User = require('../models/user');
const Mood = require('../models/mood');
const ensureAuth = require('../auth/ensure-auth')();
const weatherApi = require('./weather-api');

router
    .get('/', (req, res, next) => {
        const id = req.user.id;
        User.findById(id, '_id, username')
            .then(user => {
                if (!user) {
                    res.status(404).send({ error: 'that user not found' });
                } else {
                    res.send(user);
                }
            })
            .catch(next);
        //returns user obj with username, id, and email
    })
    .get('/moods', (req, res, next) => {
        const nId = (req.user.id);
        const query = { userId: nId };
        const date = req.query.date;
        if (date) query.date = date;
        Mood.find(query)
            .populate('color block')
            .then(moods => res.send(moods))
            .catch(next);
    })
    //.get('/mood/week')
    //get by week (return an array of all moods for one week, moods to be sorted by day)
    //figure out how to group moods per day to send back to front-end
    //weekArray = [[sunday moods (9)],[monday moods (9)],[],[],[],[], []]
    .get('/moods/month', (req, res, next) => {
        const findDate = new Date(req.query.month);

        let startDate = new Date(findDate.getFullYear(), findDate.getMonth(), 1);
        let endDate = new Date(findDate.getFullYear(), findDate.getMonth() + 1, 0);

        const query = { date: { $gte: startDate, $lte: endDate } }
        Mood.find(query)
            .populate('color block')
            .then(moods => res.send(moods))
            .catch(next);
    })
    .post('/moods/add', ensureAuth, bodyParser, weatherApi, (req, res, next) => {
        let newEntry = {
            userId: req.user.id,
            date: req.body.date,
            color: req.body.colorId,
            comment: req.body.comment,
            block: req.body.blockId,
            weather: req.body.weather,
            zipcode: req.body.zipcode
        };

        let mood = new Mood(newEntry);
        mood.save();
        res.send(mood);

        //posts a new mood that is associated with an existing user, date, location,
    });

module.exports = router;
<commit_msg>changed query for month user<commit_after>const mongoose = require('mongoose');
const router = require('express').Router();
const bodyParser = require('body-parser').json();
const User = require('../models/user');
const Mood = require('../models/mood');
const ensureAuth = require('../auth/ensure-auth')();
const weatherApi = require('./weather-api');

router
    .get('/', (req, res, next) => {
        const id = req.user.id;
        User.findById(id, '_id, username')
            .then(user => {
                if (!user) {
                    res.status(404).send({ error: 'that user not found' });
                } else {
                    res.send(user);
                }
            })
            .catch(next);
        //returns user obj with username, id, and email
    })
    .get('/moods', (req, res, next) => {
        const nId = (req.user.id);
        const query = { userId: nId };
        const date = req.query.date;
        if (date) query.date = date;
        Mood.find(query)
            .populate('color block')
            .then(moods => res.send(moods))
            .catch(next);
    })
    //.get('/mood/week')
    //get by week (return an array of all moods for one week, moods to be sorted by day)
    //figure out how to group moods per day to send back to front-end
    //weekArray = [[sunday moods (9)],[monday moods (9)],[],[],[],[], []]
    .get('/moods/month', (req, res, next) => {
        const nId = (req.user.id);
        const findDate = new Date(req.query.month);

        let startDate = new Date(findDate.getFullYear(), findDate.getMonth(), 1);
        let endDate = new Date(findDate.getFullYear(), findDate.getMonth() + 1, 0);
        const query = { userId: nId, date: { $gte: startDate, $lte: endDate } };

        Mood.find(query)
            .populate('color block')
            .then(moods => res.send(moods))
            .catch(next);
    })
    .post('/moods/add', ensureAuth, bodyParser, weatherApi, (req, res, next) => {
        let newEntry = {
            userId: req.user.id,
            date: req.body.date,
            color: req.body.colorId,
            comment: req.body.comment,
            block: req.body.blockId,
            weather: req.body.weather,
            zipcode: req.body.zipcode
        };

        let mood = new Mood(newEntry);
        mood.save();
        res.send(mood);

        //posts a new mood that is associated with an existing user, date, location,
    });

module.exports = router;
<|endoftext|>


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

  angular.module('openSenseMapApp').directive('osemClipboard', OsemClipboard);

  OsemClipboard.$inject = ['$window'];
  function OsemClipboard ($window) {
    // Usage:
    //
    // Creates:
    //
    var directive = {
      link: link,
      restrict: 'A',
      scope: {
        text: '='
      }
    };

    return directive;

    function link (scope, element) {
      element.on('click', function (event) {
        // event.stopPropagation();
        // event.preventDefault();

        var textField = $window.document.createElement('textarea');
        // Place in top-left corner of screen regardless of scroll position.
        textField.style.position = 'fixed';
        textField.style.top = '0';
        textField.style.left = '0';
        textField.style.width = '2em';
        textField.style.height = '2em';
        textField.style.padding = '0';
        textField.style.border = 'none';
        textField.style.outline = 'none';
        textField.style.boxShadow = 'none';
        textField.style.background = 'transparent';
        textField.innerText = scope.text;
        $window.document.body.appendChild(textField);

        var range, selection;
        range = $window.document.createRange();
        range.selectNodeContents(textField);
        selection = $window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
        textField.setSelectionRange(0, 999999);

        $window.document.execCommand('copy');
        $window.document.body.removeChild(textField);
      });
    }
  }
})();
<commit_msg>fix(clipboard): Fix copy to clipboard directive (#303)<commit_after>(function () {
  'use strict';

  angular.module('openSenseMapApp').directive('osemClipboard', OsemClipboard);

  OsemClipboard.$inject = ['$window'];
  function OsemClipboard ($window) {
    // Usage:
    //
    // Creates:
    //
    var directive = {
      link: link,
      restrict: 'A',
      scope: {
        text: '='
      }
    };

    return directive;

    function link (scope, element) {
      element.on('click', function () {

        var isOS = $window.navigator.userAgent.match(/ipad|iphone/i);

        var textField = $window.document.createElement('textarea');
        // Place in top-left corner of screen regardless of scroll position.
        textField.style.position = 'fixed';
        textField.style.top = '0';
        textField.style.left = '0';
        textField.style.width = '2em';
        textField.style.height = '2em';
        textField.style.padding = '0';
        textField.style.border = 'none';
        textField.style.outline = 'none';
        textField.style.boxShadow = 'none';
        textField.style.background = 'transparent';
        textField.innerText = scope.text;
        $window.document.body.appendChild(textField);

        if (isOS) {
          var range, selection;
          range = $window.document.createRange();
          range.selectNodeContents(textField);
          selection = $window.getSelection();
          selection.removeAllRanges();
          selection.addRange(range);
          textField.setSelectionRange(0, 999999);
        } else {
          textField.select();
        }

        try {
          $window.document.execCommand('copy');
        } catch (err) {
          console.log('Oops, unable to cut');
        }
        $window.document.body.removeChild(textField);
      });
    }
  }
})();
<|endoftext|>


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

import React from 'react';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import withMobileDialog from '@material-ui/core/withMobileDialog';
import semver from 'semver';
import GenericDialog from './GenericDialog';
import LogoIcon from '../../assets/images/icon100x100.svg';
import i18n from '../../services/i18n';
import versionMeta from '../../version.json';
import PlatformIO from '../../services/platform-io';
import { Pro } from '../../pro';
import { getLastVersionPromise } from '../../reducers/settings';
import AppConfig from '../../config';

type Props = {
  open: boolean,
  fullScreen: boolean,
  toggleLicenseDialog: () => void,
  toggleThirdPartyLibsDialog: () => void,
  onClose: () => void
};

type State = {
  updateAvailable?: boolean,
  newVersion?: string
};

let buildID = versionMeta.commitId;
if (buildID && buildID.length >= 11) {
  buildID = buildID.slice(0, 11);
}

const productName = versionMeta.name + (Pro ? ' Pro' : '');
document.title = productName + ' ' + versionMeta.version;

class AboutDialog extends React.Component<Props, State> {
  state = {
    updateAvailable: false,
    newVersion: ''
  };

  checkForUpdates = () => {
    if (this.state.updateAvailable) {
      PlatformIO.openUrl(AppConfig.downloadURL);
    } else {
      getLastVersionPromise()
        .then(lastVersion => {
          console.log('Last version on server: ' + lastVersion);
          const cleanedLastVersion = semver.coerce(lastVersion);
          // const cleanedCurrentVersion = '3.0.2'
          const cleanedCurrentVersion = semver.coerce(versionMeta.version);
          if (
            semver.valid(cleanedLastVersion) &&
            semver.gt(cleanedLastVersion, cleanedCurrentVersion)
          ) {
            this.setState({
              updateAvailable: true,
              newVersion: cleanedLastVersion.version
            });
          }
          // this.setState({ newVersion: '3.0.1' });
          return true;
        })
        .catch(error => {
          console.warn('Error while checking for update: ' + error);
        });
    }
  };

  renderTitle = () => <DialogTitle>{productName}</DialogTitle>;

  renderContent = () => (
    <DialogContent>

      <Typography
        variant="subtitle1"
        title={'Build on: ' + versionMeta.buildTime}
      >
        Version: {versionMeta.version} / BuildID: {buildID}
      </Typography>

      <Typography id="aboutContent" variant="body1">
        {productName} is made possible by the
        TagSpaces(github.com/tagspaces) open source project and other{' '}
        <Button onClick={this.props.toggleThirdPartyLibsDialog}>
          open source software
        </Button>
        .

        {!Pro && (

            This program is free software: you can redistribute it and/or modify
            it under the terms of the GNU Affero General Public License (version
            3) as published by the Free Software Foundation.

        )}

        This program is distributed in the hope that it will be useful, but
        WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for
        more details.

        <Button
          onClick={() => {
            PlatformIO.openUrl('https://www.tagspaces.org/about/imprint/');
          }}
        >
          Imprint
        </Button>
        <Button
          onClick={() => {
            PlatformIO.openUrl('https://www.tagspaces.org/about/privacy/');
          }}
        >
          Privacy Policy
        </Button>
        <Button
          onClick={() => {
            PlatformIO.openUrl('https://www.tagspaces.org/whatsnew/');
          }}
        >
          Changelog
        </Button>
        <Button
          data-tid="openLicenseDialog"
          onClick={this.props.toggleLicenseDialog}
        >
          License Agreement
        </Button>
      </Typography>
    </DialogContent>
  );

  renderActions = () => {
    let versionInfo = 'Check for updates';
    if (this.state.newVersion.length > 1) {
      if (this.state.updateAvailable) {
        versionInfo = i18n.t('getNewVersion', {
          newVersion: this.state.newVersion
        });
      } else {
        versionInfo = i18n.t('latestVersion', { productName });
      }
    }

    return (
      <DialogActions>
        {!Pro && (
          <Button
            data-tid="checkForUpdates"
            title={i18n.t('core:checkForNewVersion')}
            onClick={() => {
              PlatformIO.openUrl('https://www.tagspaces.org/products/');
            }}
            color="primary"
          >
            Upgrade to PRO
          </Button>
        )}
        <Button
          data-tid="checkForUpdates"
          title={i18n.t('core:checkForNewVersion')}
          onClick={this.checkForUpdates}
          color="primary"
        >
          {versionInfo}
        </Button>
        {/* <Button
          data-tid="openLicenseDialog"
          onClick={this.props.toggleLicenseDialog}
        >
          {i18n.t('core:license')}
        </Button>
        <Button
          data-tid="openThirdPartyLibsDialog"
          onClick={this.props.toggleThirdPartyLibsDialog}
        >
          {i18n.t('core:thirdPartyLibs')}
        </Button> */}
        <Button
          data-tid="closeAboutDialog"
          onClick={this.props.onClose}
          color="primary"
        >
          {i18n.t('core:ok')}
        </Button>
      </DialogActions>
    );
  };

  render() {
    const { fullScreen, open, onClose } = this.props;
    return (
      <GenericDialog
        fullScreen={fullScreen}
        open={open}
        onClose={onClose}
        renderTitle={this.renderTitle}
        renderContent={this.renderContent}
        renderActions={this.renderActions}
      />
    );
  }
}

export default withMobileDialog()(AboutDialog);
<commit_msg>fix check for a newer version of TagSpaces<commit_after>/**
 * TagSpaces - universal file and folder organizer
 * Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License (version 3) as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * @flow
 */

import React from 'react';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import withMobileDialog from '@material-ui/core/withMobileDialog';
import semver from 'semver';
import GenericDialog from './GenericDialog';
import LogoIcon from '../../assets/images/icon100x100.svg';
import i18n from '../../services/i18n';
import versionMeta from '../../version.json';
import PlatformIO from '../../services/platform-io';
import { Pro } from '../../pro';
import { getLastVersionPromise } from '../../reducers/settings';
import AppConfig from '../../config';

type Props = {
  open: boolean,
  fullScreen: boolean,
  toggleLicenseDialog: () => void,
  toggleThirdPartyLibsDialog: () => void,
  onClose: () => void
};

type State = {
  updateAvailable: boolean,
  newVersion: string
};

let buildID = versionMeta.commitId;
if (buildID && buildID.length >= 11) {
  buildID = buildID.slice(0, 11);
}

const productName = versionMeta.name + (Pro ? ' Pro' : '');
document.title = productName + ' ' + versionMeta.version;

class AboutDialog extends React.Component<Props, State> {
  state = {
    updateAvailable: false,
    newVersion: ''
  };

  checkForUpdates = () => {
    if (this.state.updateAvailable) {
      PlatformIO.openUrl(AppConfig.downloadURL);
    } else {
      getLastVersionPromise()
        .then(lastVersion => {
          console.log('Last version on server: ' + lastVersion);
          const cleanedLastVersion = semver.coerce(lastVersion);
          // const cleanedCurrentVersion = '3.0.2'
          const cleanedCurrentVersion = semver.coerce(versionMeta.version);
          if (
            semver.valid(cleanedLastVersion) &&
            semver.gt(cleanedLastVersion, cleanedCurrentVersion)
          ) {
            this.setState({
              updateAvailable: true,
              newVersion: cleanedLastVersion.version
            });
          } else {
            this.setState({
              newVersion: versionMeta.version
            });
          }
          return true;
        })
        .catch(error => {
          console.warn('Error while checking for update: ' + error);
        });
    }
  };

  renderTitle = () => <DialogTitle>{productName}</DialogTitle>;

  renderContent = () => (
    <DialogContent>

      <Typography
        variant="subtitle1"
        title={'Build on: ' + versionMeta.buildTime}
      >
        Version: {versionMeta.version} / BuildID: {buildID}
      </Typography>

      <Typography id="aboutContent" variant="body1">
        {productName} is made possible by the
        TagSpaces(github.com/tagspaces) open source project and other{' '}
        <Button onClick={this.props.toggleThirdPartyLibsDialog}>
          open source software
        </Button>
        .

        {!Pro && (

            This program is free software: you can redistribute it and/or modify
            it under the terms of the GNU Affero General Public License (version
            3) as published by the Free Software Foundation.

        )}

        This program is distributed in the hope that it will be useful, but
        WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for
        more details.

        <Button
          onClick={() => {
            PlatformIO.openUrl('https://www.tagspaces.org/about/imprint/');
          }}
        >
          Imprint
        </Button>
        <Button
          onClick={() => {
            PlatformIO.openUrl('https://www.tagspaces.org/about/privacy/');
          }}
        >
          Privacy Policy
        </Button>
        <Button
          onClick={() => {
            PlatformIO.openUrl('https://www.tagspaces.org/whatsnew/');
          }}
        >
          Changelog
        </Button>
        <Button
          data-tid="openLicenseDialog"
          onClick={this.props.toggleLicenseDialog}
        >
          License Agreement
        </Button>
      </Typography>
    </DialogContent>
  );

  renderActions = () => {
    let versionInfo = 'Check for updates';
    if (this.state.newVersion && this.state.newVersion.length > 1) {
      if (this.state.updateAvailable) {
        versionInfo = i18n.t('getNewVersion', {
          newVersion: this.state.newVersion
        });
      } else {
        versionInfo = i18n.t('latestVersion', { productName });
      }
    }

    return (
      <DialogActions>
        {!Pro && (
          <Button
            data-tid="checkForUpdates"
            title={i18n.t('core:checkForNewVersion')}
            onClick={() => {
              PlatformIO.openUrl('https://www.tagspaces.org/products/');
            }}
            color="primary"
          >
            Upgrade to PRO
          </Button>
        )}
        <Button
          data-tid="checkForUpdates"
          title={i18n.t('core:checkForNewVersion')}
          onClick={this.checkForUpdates}
          color="primary"
        >
          {versionInfo}
        </Button>
        {/* <Button
          data-tid="openLicenseDialog"
          onClick={this.props.toggleLicenseDialog}
        >
          {i18n.t('core:license')}
        </Button>
        <Button
          data-tid="openThirdPartyLibsDialog"
          onClick={this.props.toggleThirdPartyLibsDialog}
        >
          {i18n.t('core:thirdPartyLibs')}
        </Button> */}
        <Button
          data-tid="closeAboutDialog"
          onClick={this.props.onClose}
          color="primary"
        >
          {i18n.t('core:ok')}
        </Button>
      </DialogActions>
    );
  };

  render() {
    const { fullScreen, open, onClose } = this.props;
    return (
      <GenericDialog
        fullScreen={fullScreen}
        open={open}
        onClose={onClose}
        renderTitle={this.renderTitle}
        renderContent={this.renderContent}
        renderActions={this.renderActions}
      />
    );
  }
}

export default withMobileDialog()(AboutDialog);
<|endoftext|>


<commit_before>var tfidf = require('../tfidf');
var redis = require('redis').createClient();

function runTest() {
    var totalTermCount = 0;
    for (var prop in documents[documents.length - 1]) {
        if (documents[documents.length - 1].hasOwnProperty(prop)) {
            totalTermCount+=documents[documents.length-1][prop];
        }
    }
    tfidf.getScores(documents[documents.length-1], totalTermCount, function(scores) {
        var fail = false;
        if (scores.one != scores.two || scores.one != scores.three || scores.one != scores.four)
            fail = true;
        console.log('Test has pased: ' + (fail === false));
    });
}

var documents = [];
documents.push({
    'one': 1,
    'two': 1,
    'three': 1,
    'four': 1
});

var keysServiced = 0;
for (var key in documents[documents.length - 1]) {
    if (documents[documents.length - 1].hasOwnProperty(key)) {
        (function(key) {
            redis.set(key, 0, function(err, res) {
                keysServiced++;
                if (keysServiced === Object.keys(documents[documents.length - 1]).length) {
                    return runTest();
                }
            });
        })(key);
    }
}

<commit_msg>Exiting on equal scores test. Shit works<commit_after>var tfidf = require('../tfidf');
var redis = require('redis').createClient();

function runTest() {
    var totalTermCount = 0;
    for (var prop in documents[documents.length - 1]) {
        if (documents[documents.length - 1].hasOwnProperty(prop)) {
            totalTermCount+=documents[documents.length-1][prop];
        }
    }
    tfidf.getScores(documents[documents.length-1], totalTermCount, function(scores) {
        var fail = false;
        if (scores.one !== scores.two || scores.one !== scores.three || scores.one !== scores.four) {
            fail = true;
        }
        var success = (fail === false);
        console.log('Test has pased: ' + success);
        process.exit(success);
    });
}

var documents = [];
documents.push({
    'one': 1,
    'two': 1,
    'three': 1,
    'four': 1
});

var keysServiced = 0;
for (var key in documents[documents.length - 1]) {
    if (documents[documents.length - 1].hasOwnProperty(key)) {
        (function(key) {
            redis.set(key, 0, function(err, res) {
                keysServiced++;
                if (keysServiced === Object.keys(documents[documents.length - 1]).length) {
                    return runTest();
                }
            });
        })(key);
    }
}

<|endoftext|>


<commit_before>var util = require('../../util');
var url = require('url');
var net = require('net');
var dns = require('dns');
var extend = require('util')._extend;

var rules, hosts, heads, req, res, dump;
rules = hosts = heads = req = res = dump = [];

function parse(text) {
	rules = [];
	hosts = [];
	heads = [];
	req = [];
	res = [];
	dump = [];
	if (!text || !(text = text.trim())) {
		return;
	}

	text.split(/\n|\r\n|\r/g).forEach(pareLine);
}

function pareLine(line) {
	line = line.replace(/#.*$/, '').trim();
	if (!line) {
		return;
	}

	line = line.split(/\s+/);
	var pattern = line[0];
	if (net.isIP(pattern) || (util.hasProtocol(pattern) && !/^https?:\/\//.test(pattern))) {
		line.slice(1).forEach(function(matcher) {
			parseRule(matcher, pattern);
		});
	} else if (!util.isRegExp(pattern) && util.isRegExp(line[1])) {
		parseRule(line[1], pattern);
	} else {
		parseRule(pattern, line[1]);
	}
}

function parseRule(pattern, matcher) {
	if (!pattern || !matcher) {
		return;
	}

	var isIP = net.isIP(matcher);
	var isRegExp = util.isRegExp(pattern);
	var protocol;
	if (!isRegExp) {
		protocol = util.getProtocol(pattern);

		if (!isIP) {
			if (pattern.indexOf('/', protocol == null ? 0 : pattern.indexOf('://') + 3) == -1) {
				pattern += '/';
			}
		} else if (!(pattern = util.getHost(pattern))) {
			return;
		}
	} else if (!(pattern = util.toRegExp(pattern))) {
		return;
	}

	var rule = {
			isRegExp: isRegExp,
			protocol: protocol,
			pattern: pattern,
			matcher: matcher
		};

	if (isIP) {
		hosts.push(rule);
	} else if (/^head:\/\//.test(matcher)) {
		heads.push(rule);
	} else if (/^req:\/\//.test(matcher)) {
		req.push(rule);
	} else if (/^res:\/\//.test(matcher)) {
		res.push(rule);
	} else if (/^dump:\/\//.test(matcher)) {
		dump.push(rule);
	} else {
		rules.push(rule);
	}
}

exports.parse = parse;

function resolve(_url, callback) {
	var rule = {};
	var matchedUrl = resolveRule(_url, rule);
	var error, done;
	var matcher = matchedUrl || _url;
	var options = url.parse(matcher);
	var hosts = options.hosts = [];
	options.url = matcher;
	options.rule = rule;
	options.hasMatcher = !!matchedUrl;

	if (matchedUrl) {
		resolveHost(matchedUrl, function(err, ip) {
			hosts[1] = ip;
			error = err;
			execCallback();
		});

		hosts[0] = null;
		execCallback();
	} else {
		resolveHost(_url, function(err, ip) {
			hosts[0] = ip;
			if (!matchedUrl) {
				hosts[1] = ip;
				error = err;
			}
			execCallback();
		});
	}

	function execCallback() {
		if (!done && (error || (typeof hosts[0] != 'undefined' && typeof hosts[1] != 'undefined'))) {
			done = true;
			hosts[1] = hosts[1] || hosts[0];
			hosts[0] = hosts[0] || hosts[1];
			callback(error, options);
		}
	}
}

exports.resolve = resolve;

function resolveHost(_url, callback) {
	var options = _url ? url.parse(util.setProtocol(_url)) : {};
	var protocol = options.protocol;
	if (!util.isWebProtocol(protocol)) {
		callback(null, null);
		return;
	}
	var hostname = options.hostname;
	for (var i = 0, host; host = hosts[i]; i++) {
		if (host.isRegExp ? host.pattern.test(_url) : (hostname == host.pattern && (!host.protocol || host.protocol == protocol))) {
			callback(null, host.matcher);
			return;
		}
	}

	try {
		dns.lookup(hostname, function(err, ip, addressType) {
		      callback(err, err ? null : (ip || (!addressType || addressType === 4 ? '127.0.0.1' : '0:0:0:0:0:0:0:1')));
		  });
	} catch(err) {//如果断网，可能直接抛异常，https代理没有用到error-handler
		callback(err);
	}
}

exports.resolveHost = resolveHost;

function resolveRule(url, data, _rules) {
	data = data || {};
	_rules = _rules || rules;
	var _url = url.replace(/(?:\?|#).*$/, '');
	for (var i = 0, rule; rule = _rules[i]; i++) {
		var pattern = rule.pattern;
		if (rule.isRegExp) {
			if (pattern.test(url)) {
				var regExp = {};
				for (var i = 0; i < 10; i++) {
					regExp['$' + i] = RegExp['$' + i] || '';
				}
				extend(data, rule);
				return setProtocol(rule.matcher.replace(/(^|.)?(\$[1-9])/g,
						function(matched, $1, $2) {
					return $1 == '\\' ? $2 : ($1 || '') + regExp[$2];
				}), url);
			}
		} else {
			pattern = setProtocol(pattern, url);
			if (_url.indexOf(pattern) === 0) {
				var len = pattern.length;
				if (pattern == _url || isPathSeparator(_url[len]) || isPathSeparator(pattern[len - 1])) {
					extend(data, rule);
					return join(setProtocol(rule.matcher, url), url.substring(len));
				}
			}
		}
	}
}

function _resolveRule(url, _rules) {
	_rules = _rules || rules;
	var _url = url.replace(/(?:\?|#).*$/, '');
	for (var i = 0, rule; rule = _rules[i]; i++) {
		var pattern = rule.pattern;
		if (rule.isRegExp) {
			if (pattern.test(url)) {
				var regExp = {};
				for (var i = 0; i < 10; i++) {
					regExp['$' + i] = RegExp['$' + i] || '';
				}
				var result = extend({}, rule);
				result.url = setProtocol(rule.matcher.replace(/(^|.)?(\$[1-9])/g,
						function(matched, $1, $2) {
					return $1 == '\\' ? $2 : ($1 || '') + regExp[$2];
				}), url);
				return result;
			}
		} else {
			pattern = setProtocol(pattern, url);
			if (_url.indexOf(pattern) === 0) {
				var len = pattern.length;
				if (pattern == _url || isPathSeparator(_url[len]) || isPathSeparator(pattern[len - 1])) {
					var result = extend({}, rule);
					result.url = join(setProtocol(rule.matcher, url), url.substring(len));
					return result;
				}
			}
		}
	}
}

function setProtocol(target, source) {
	if (util.hasProtocol(target)) {
		return target;
	}

	var protocol = util.getProtocol(source);
	if (protocol == null) {
		return target;
	}

	return protocol + '//' + target;
}

exports.resolveRule = resolveRule;

function resolveHead(url, data) {
	return resolveRule(url, data, heads);
}

exports.resolveHead = resolveHead;

function resolveReq(url, data) {
	return resolveRule(url, data, req);
}

exports.resolveReq = resolveReq;

function resolveRes(url, data) {
	return resolveRule(url, data, res);
}

exports.resolveRes = resolveRes;

function resolveDump(url, data) {
	return resolveRule(url, data, dump);
}

exports.resolveDump = resolveDump;

function isPathSeparator(ch) {
	return ch == '/' || ch == '\\';
}

function join(first, last) {
	if (!first || !last) {
		return first + last;
	}

	var len = first.length - 1;
	if (isPathSeparator(first[len])) {
		return isPathSeparator(last[0]) ? first.substring(0, len) + last : first + last;
	}

	return isPathSeparator(last[0]) ? first + last : first + '/' + last;
}

<commit_msg>rules<commit_after>var util = require('../../util');
var url = require('url');
var net = require('net');
var dns = require('dns');
var extend = require('util')._extend;

var rules, hosts, heads, req, res, dump;
rules = hosts = heads = req = res = dump = [];

function parse(text) {
	rules = [];
	hosts = [];
	heads = [];
	req = [];
	res = [];
	dump = [];
	if (!text || !(text = text.trim())) {
		return;
	}

	text.split(/\n|\r\n|\r/g).forEach(pareLine);
}

function pareLine(line) {
	line = line.replace(/#.*$/, '').trim();
	if (!line) {
		return;
	}

	line = line.split(/\s+/);
	var pattern = line[0];
	if (net.isIP(pattern) || (util.hasProtocol(pattern) && !/^https?:\/\//.test(pattern))) {
		line.slice(1).forEach(function(matcher) {
			parseRule(matcher, pattern);
		});
	} else if (!util.isRegExp(pattern) && util.isRegExp(line[1])) {
		parseRule(line[1], pattern);
	} else {
		parseRule(pattern, line[1]);
	}
}

function parseRule(pattern, matcher) {
	if (!pattern || !matcher) {
		return;
	}

	var isIP = net.isIP(matcher);
	var isRegExp = util.isRegExp(pattern);
	var protocol;
	if (!isRegExp) {
		protocol = util.getProtocol(pattern);

		if (!isIP) {
			if (pattern.indexOf('/', protocol == null ? 0 : pattern.indexOf('://') + 3) == -1) {
				pattern += '/';
			}
		} else if (!(pattern = util.getHost(pattern))) {
			return;
		}
	} else if (!(pattern = util.toRegExp(pattern))) {
		return;
	}

	var rule = {
			isRegExp: isRegExp,
			protocol: protocol,
			pattern: pattern,
			matcher: matcher
		};

	if (isIP) {
		hosts.push(rule);
	} else if (/^head:\/\//.test(matcher)) {
		heads.push(rule);
	} else if (/^req:\/\//.test(matcher)) {
		req.push(rule);
	} else if (/^res:\/\//.test(matcher)) {
		res.push(rule);
	} else if (/^dump:\/\//.test(matcher)) {
		dump.push(rule);
	} else {
		rules.push(rule);
	}
}

exports.parse = parse;

function resolve(_url, callback) {
	var rule = {};
	var matchedUrl = resolveRule(_url, rule);
	var error, done;
	var matcher = matchedUrl || _url;
	var options = url.parse(matcher);
	var hosts = options.hosts = [];
	options.url = matcher;
	options.rule = rule;
	options.hasMatcher = !!matchedUrl;

	if (matchedUrl) {
		resolveHost(matchedUrl, function(err, ip) {
			hosts[1] = ip;
			error = err;
			execCallback();
		});

		hosts[0] = null;
		execCallback();
	} else {
		resolveHost(_url, function(err, ip) {
			hosts[0] = ip;
			if (!matchedUrl) {
				hosts[1] = ip;
				error = err;
			}
			execCallback();
		});
	}

	function execCallback() {
		if (!done && (error || (typeof hosts[0] != 'undefined' && typeof hosts[1] != 'undefined'))) {
			done = true;
			hosts[1] = hosts[1] || hosts[0];
			hosts[0] = hosts[0] || hosts[1];
			callback(error, options);
		}
	}
}

exports.resolve = resolve;

function resolveHost(_url, callback) {
	var options = _url ? url.parse(util.setProtocol(_url)) : {};
	var protocol = options.protocol;
	if (!util.isWebProtocol(protocol)) {
		callback(null, null);
		return;
	}
	var hostname = options.hostname;
	for (var i = 0, host; host = hosts[i]; i++) {
		if (host.isRegExp ? host.pattern.test(_url) : (hostname == host.pattern && (!host.protocol || host.protocol == protocol))) {
			callback(null, host.matcher);
			return;
		}
	}

	try {
		dns.lookup(hostname, function(err, ip, addressType) {
		      callback(err, err ? null : (ip || (!addressType || addressType === 4 ? '127.0.0.1' : '0:0:0:0:0:0:0:1')));
		  });
	} catch(err) {//如果断网，可能直接抛异常，https代理没有用到error-handler
		callback(err);
	}
}

exports.resolveHost = resolveHost;

function resolveRule(url, data, _rules) {
	data = data || {};
	_rules = _rules || rules;
	var _url = url.replace(/(?:\?|#).*$/, '');
	for (var i = 0, rule; rule = _rules[i]; i++) {
		var pattern = rule.pattern;
		if (rule.isRegExp) {
			if (pattern.test(url)) {
				var regExp = {};
				for (var i = 0; i < 10; i++) {
					regExp['$' + i] = RegExp['$' + i] || '';
				}
				extend(data, rule);
				return setProtocol(rule.matcher.replace(/(^|.)?(\$[1-9])/g,
						function(matched, $1, $2) {
					return $1 == '\\' ? $2 : ($1 || '') + regExp[$2];
				}), url);
			}
		} else {
			pattern = setProtocol(pattern, url);
			if (_url.indexOf(pattern) === 0) {
				var len = pattern.length;
				if (pattern == _url || isPathSeparator(_url[len]) || isPathSeparator(pattern[len - 1])) {
					extend(data, rule);
					return join(setProtocol(rule.matcher, url), url.substring(len));
				}
			}
		}
	}
}

function _resolveRule(url, _rules) {
	_rules = _rules || rules;
	var _url = url.replace(/(?:\?|#).*$/, '');
	for (var i = 0, rule; rule = _rules[i]; i++) {
		var pattern = rule.pattern;
		if (rule.isRegExp) {
			if (pattern.test(url)) {
				var regExp = {};
				for (var i = 0; i < 10; i++) {
					regExp['$' + i] = RegExp['$' + i] || '';
				}

				return extend({
					url: setProtocol(rule.matcher.replace(/(^|.)?(\$[1-9])/g,
							function(matched, $1, $2) {
						return $1 == '\\' ? $2 : ($1 || '') + regExp[$2];
					}), url)
				}, rule);;
			}
		} else {
			pattern = setProtocol(pattern, url);
			if (_url.indexOf(pattern) === 0) {
				var len = pattern.length;
				if (pattern == _url || isPathSeparator(_url[len]) || isPathSeparator(pattern[len - 1])) {
					return extend({
						url: join(setProtocol(rule.matcher, url), url.substring(len))
					}, rule);
				}
			}
		}
	}
}

function setProtocol(target, source) {
	if (util.hasProtocol(target)) {
		return target;
	}

	var protocol = util.getProtocol(source);
	if (protocol == null) {
		return target;
	}

	return protocol + '//' + target;
}

exports.resolveRule = resolveRule;

function resolveHead(url, data) {
	return resolveRule(url, data, heads);
}

exports.resolveHead = resolveHead;

function resolveReq(url, data) {
	return resolveRule(url, data, req);
}

exports.resolveReq = resolveReq;

function resolveRes(url, data) {
	return resolveRule(url, data, res);
}

exports.resolveRes = resolveRes;

function resolveDump(url, data) {
	return resolveRule(url, data, dump);
}

exports.resolveDump = resolveDump;

function isPathSeparator(ch) {
	return ch == '/' || ch == '\\';
}

function join(first, last) {
	if (!first || !last) {
		return first + last;
	}

	var len = first.length - 1;
	if (isPathSeparator(first[len])) {
		return isPathSeparator(last[0]) ? first.substring(0, len) + last : first + last;
	}

	return isPathSeparator(last[0]) ? first + last : first + '/' + last;
}

<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import Dropzone from 'react-dropzone'
import { FormControl, ControlLabel } from 'react-bootstrap'
import regularStyles from './areaLinks.css'
import pdfStyles from './areaLinksPdf.css'

const AreaLinks = ({
  links,
  activeId,
  blur,
  change,
  isPrintPreview,
}) => {
  const styles = isPrintPreview ? pdfStyles : regularStyles

  const onDrop = (files) => {
    console.log('Received files: ', files)
    console.log('path: ', files[0].path)
  }

  return (

        Links

        {
          links.map((link, index) =>

                {link.url}

                {link.txt}

          )
        }

        <Dropzone
          onDrop={onDrop}
          className={styles.dropzone}
        >

Datei hierhin ziehen...

...oder klicken, um sie zu wählen.

        </Dropzone>

  )
}

AreaLinks.displayName = 'AreaLinks'

AreaLinks.propTypes = {
  links: PropTypes.array.isRequired,
  activeId: PropTypes.number.isRequired,
  blur: PropTypes.func.isRequired,
  change: PropTypes.func.isRequired,
  isPrintPreview: PropTypes.bool.isRequired,
}

export default AreaLinks
<commit_msg>optimize<commit_after>import React, { PropTypes } from 'react'
import Dropzone from 'react-dropzone'
import regularStyles from './areaLinks.css'
import pdfStyles from './areaLinksPdf.css'

const AreaLinks = ({
  links,
  activeId,
  blur,
  change,
  isPrintPreview,
}) => {
  const styles = isPrintPreview ? pdfStyles : regularStyles

  const onDrop = (files) => {
    console.log('Received files: ', files)
    console.log('path: ', files[0].path)
  }

  return (

        Links

        {
          links.map(link =>
            <div
              key={`${link.idGeschaeft}${link.url}`}
              className={styles.fields}
            >

                {link.url}

                {link.txt}

          )
        }

        <Dropzone
          onDrop={onDrop}
          className={styles.dropzone}
        >

Datei hierhin ziehen...

...oder klicken, um sie zu wählen.

        </Dropzone>

  )
}

AreaLinks.displayName = 'AreaLinks'

AreaLinks.propTypes = {
  links: PropTypes.array.isRequired,
  activeId: PropTypes.number.isRequired,
  blur: PropTypes.func.isRequired,
  change: PropTypes.func.isRequired,
  isPrintPreview: PropTypes.bool.isRequired,
}

export default AreaLinks
<|endoftext|>


<commit_before>"use strict";
const deployer = require("soajs").drivers;

const repos = {

	validate: function(req, context, lib, async, BL, modelName, callback){
		let resourceSection = context.opts.section[context.opts.section.length - 1];
		if (!context.template.content.deployments
			|| !context.template.content.deployments.resources
			|| !context.template.content.deployments.resources[resourceSection]) {
			//this deployment entry is not found in the template content
			context.errors.push({
				code: 172,
				msg: `The template does not support deploying resources for ${resourceSection}`
			});
			return callback();
		}
		if (!context.template.content.deployments.resources[resourceSection].limit) {
			context.template.content.deployments.resources[resourceSection].limit = 1;
		}

		if (!context.opts.inputs || !Array.isArray(context.opts.inputs) || context.opts.inputs.length !== context.template.content.deployments.resources[resourceSection].limit) {
			context.errors.push({
				code: 172,
				msg: `Mismatch between the number of inputs provided and the template entries in resources ${resourceSection}!`
			});
			return callback();
		}

		let myValidator = new req.soajs.validator.Validator();
		let dataImfv;
		context.opts.inputs.forEach((entryImfv) =>{
			if(entryImfv.name === resourceSection){
				dataImfv = entryImfv;
			}
		});

		if(!dataImfv || typeof dataImfv !== 'object'){
			context.errors.push({code: 172, msg: `Invalid or not all inputs provided for resource ${resourceSection}`});
			return callback();
		}

		async.series({
			"validateResource": (mCb) => {
				let schema = context.config.schema.post["/resources/add"];
				req.soajs.log.debug("Validating Resource db inputs ", resourceSection);
				let dbData = {
					"name": dataImfv.name,
					"type": dataImfv.type,
					"category": dataImfv.category,
					"locked": dataImfv.locked,
					"plugged": dataImfv.plugged,
					"shared": dataImfv.shared,
					"config": dataImfv.config || null
				};
				if(dataImfv.sharedEnv){
					dbData["sharedEnv"] = dataImfv.sharedEnv;
				}

				let status = myValidator.validate(dbData, schema);
				if (!status.valid) {
					status.errors.forEach(function (err) {
						context.errors.push({code: 173, msg: `Resource ${resourceSection}: ` + err.stack});
					});
				}
				return mCb();
			},
			"validateCD": (mCb) =>{
				let cdData = dataImfv.deploy;
				if(cdData){
					let schema = context.config.schema.put["/resources/config/update"].config.validation;
					req.soajs.log.debug("Validating CD inputs ", resourceSection);

					let status = myValidator.validate(cdData, schema);
					if (!status.valid) {
						status.errors.forEach(function (err) {
							context.errors.push({code: 173, msg: `Resource ${resourceSection}: ` + err.stack});
						});
					}
				}
				return mCb();
			},
			"validateDeploy": (mCb) => {
				if(dataImfv.deploy){
					let imfv = context.config.schema.post["/cloud/services/soajs/deploy"];
					let schema = {
						"type": "object",
						"required": true,
						"properties":{
							recipe: imfv.recipe.validation,
							deployConfig: imfv.deployConfig.validation,
							autoScale: imfv.autoScale.validation,
							custom: imfv.custom.validation,
						}
					};

					req.soajs.log.debug("Validating deploy inputs ", resourceSection);
					let cdData = dataImfv.deploy.options;
					let status = myValidator.validate(cdData, schema);
					if (!status.valid) {
						status.errors.forEach(function (err) {
							context.errors.push({code: 173, msg: `Resource ${resourceSection}: ` + err.stack});
						});
					}
				}
				return mCb();
			}
		}, callback);
	},

	deploy: function(req, context, lib, async, BL, modelName, callback){
		let resourceName = context.opts.section[context.opts.section.length -1];

		//check if previously completed
		if(context.template.deploy[context.opts.stage][context.opts.group][context.opts.stepPath].status){
			if(context.template.deploy[context.opts.stage][context.opts.group][context.opts.stepPath].status.done){
				req.soajs.log.debug(`Resource ${resourceName} been previously created`);
				return callback(null, true);
			}
		}

		req.soajs.log.debug(`Deploying Resource ${resourceName} ...`);
		let dataImfv = {};
		context.opts.inputs.forEach((entryImfv) =>{
			if(entryImfv.name === resourceName){
				dataImfv = entryImfv;
			}
		});

		let data = {
			"env": context.environmentRecord.code.toUpperCase(),
			"resource": {
				"name": dataImfv.name,
				"type": dataImfv.type,
				"category": dataImfv.category,
				"locked": dataImfv.locked,
				"plugged": dataImfv.plugged,
				"shared": dataImfv.shared,
				"config": dataImfv.config || null
			}
		};

		if(dataImfv.sharedEnv){
			data.resource["sharedEnv"] = dataImfv.sharedEnv;
		}

		let resourceDB;
		let serviceDeploymentId;
		async.series({
			"createResource": function(mCb){
				req.soajs.log.debug("Adding Resource " + resourceName + " in Database under environment " + data.env );
				lib.initBLModel(BL.resources.module, modelName, (error, cdModule) => {
					lib.checkReturnError(req, mCb, {error: error, code: 600}, () => {
						req.soajs.inputmaskData = data;
						cdModule.addResource(context.config, req, null, (error, response) =>{
							lib.checkReturnError(req, mCb, {error: error, code: (error && error.code) ? error.code: 600}, () => {
								if (response && response._id){
									resourceDB = response._id;
								}
								return mCb(null, true);
							});
						});
					});
				});
			},
			"registerCD": function (mCb) {
				if(dataImfv.deploy && Object.keys(dataImfv.deploy).length > 0){
					req.soajs.log.debug("Registering CD entry for resource " + resourceName + " in environment " + data.env );
					lib.initBLModel(BL.resources.module, modelName, (error, cdModule) => {
						lib.checkReturnError(req, mCb, {error: error, code: 600}, () => {
							req.soajs.inputmaskData = {
								"env": context.environmentRecord.code.toUpperCase(),
								"resourceName": dataImfv.name,
								"config": {
									"deploy": true,
									"options": dataImfv.deploy
								}
							};
							cdModule.setConfig(context.config, req, null, mCb);
						});
					});
				}
				else{
					return mCb(null, true);
				}
			},
			"deployService": function (mCb) {
				if(dataImfv.deploy && Object.keys(dataImfv.deploy).length > 0){
					req.soajs.log.debug("Deploying resource " + resourceName + " in environment " + data.env);
					lib.initBLModel(BL.cloud.deploy.module, modelName, (error, deploymentModule) => {
						lib.checkReturnError(req, mCb, {error: error, code: 600}, () => {
							req.soajs.inputmaskData = {
								"deployConfig": dataImfv.deploy.options.deployConfig,
								"custom": dataImfv.deploy.options.custom,
								"recipe": dataImfv.deploy.options.recipe,
								"env": context.environmentRecord.code.toUpperCase()
							};

							//link the db id entry to the deployment
							req.soajs.inputmaskData.custom.resourceId = resourceDB;

							deploymentModule.deployService(context.config, req.soajs, deployer, (error, out) => {
								lib.checkReturnError(req, mCb, {error: error, code: 600}, () => {
									if(out && out.service){
										serviceDeploymentId = out.service.id;
									}
									return mCb(null, true);
								});
							});
						});
					});
				}
				else{
					return mCb(null, true);
				}
			}
		}, (error) => {
			req.soajs.log.debug(`Resource ${resourceName} Deployment completed`);
			//generate final response and update template
			lib.checkReturnError(req, callback, {error: error, code: (error && error.code) ? error.code: 600}, () => {
				context.template.deploy[context.opts.stage][context.opts.group][context.opts.stepPath].status = {
					"done": true,
					"data": { "db": resourceDB }
				};
				if(serviceDeploymentId){
					context.template.deploy[context.opts.stage][context.opts.group][context.opts.stepPath].status.data["id"] = serviceDeploymentId;
					context.template.deploy[context.opts.stage][context.opts.group][context.opts.stepPath].status.data["mode"] = dataImfv.deploy.options.deployConfig.replication.mode;
				}
				return callback(null, true);
			});
		});
	},

	rollback: function(req, context, lib, async, BL, modelName, callback){
		//check if previously completed
		if(context.template.deploy[context.opts.stage][context.opts.group][context.opts.stepPath].status){
			if(context.template.deploy[context.opts.stage][context.opts.group][context.opts.stepPath].status.done){
				req.soajs.log.debug(`Rolling back Deployed Resources ...`);

				let data = context.template.deploy[context.opts.stage][context.opts.group][context.opts.stepPath].status.data;
				async.series({
					"removingDB": function(mCb){
						if(!data || !data.db){
							return mCb();
						}

						lib.initBLModel(BL.cloud.resources.module, modelName, (error, cdModule) => {
							lib.checkReturnError(req, mCb, {error: error, code: 600}, () => {
								req.soajs.inputmaskData = {
									env: context.environmentRecord.code,
									id: data.db
								};
								cdModule.deleteResource(context.config, req, null, (error, response) =>{
									lib.checkReturnError(req, mCb, {error: error, code: (error && error.code) ? error.code: 600}, () => {
										if(error){
											req.soajs.log.error(error);
										}
										return mCb(null, true);
									});
								});
							});
						});
					},
					"removingDeployment": function(mCb){
						if(!data || !data.id){
							return mCb();
						}

						lib.initBLModel(BL.cloud.services.module, modelName, (error, servicesModule) => {
							lib.checkReturnError(req, mCb, {error: error, code: 600}, () => {
								req.soajs.inputmaskData = {
									env: context.environmentRecord.code,
									serviceId: data.id,
									mode: data.mode
								};

								servicesModule.deleteService(context.config, req.soajs, deployer, (error) => {
									if(error){
										req.soajs.log.error(error);
									}
									return mCb(null, true);
								});
							});
						});
					}
				}, () =>{
					return callback(null, true);
				});
			}
			else{
				return callback(null, true);
			}
		}
		else{
			return callback(null, true);
		}
	}
};

module.exports = repos;<commit_msg>bug fix<commit_after>"use strict";
const deployer = require("soajs").drivers;

const repos = {

	validate: function(req, context, lib, async, BL, modelName, callback){
		let resourceSection = context.opts.section[context.opts.section.length - 1];
		if (!context.template.content.deployments
			|| !context.template.content.deployments.resources
			|| !context.template.content.deployments.resources[resourceSection]) {
			//this deployment entry is not found in the template content
			context.errors.push({
				code: 172,
				msg: `The template does not support deploying resources for ${resourceSection}`
			});
			return callback();
		}
		if (!context.template.content.deployments.resources[resourceSection].limit) {
			context.template.content.deployments.resources[resourceSection].limit = 1;
		}

		if (!context.opts.inputs || !Array.isArray(context.opts.inputs) || context.opts.inputs.length !== context.template.content.deployments.resources[resourceSection].limit) {
			context.errors.push({
				code: 172,
				msg: `Mismatch between the number of inputs provided and the template entries in resources ${resourceSection}!`
			});
			return callback();
		}

		let myValidator = new req.soajs.validator.Validator();
		let dataImfv;
		context.opts.inputs.forEach((entryImfv) =>{
			if(entryImfv.name === resourceSection){
				dataImfv = entryImfv;
			}
		});

		if(!dataImfv || typeof dataImfv !== 'object'){
			context.errors.push({code: 172, msg: `Invalid or not all inputs provided for resource ${resourceSection}`});
			return callback();
		}

		async.series({
			"validateResource": (mCb) => {
				let schema = context.config.schema.post["/resources/add"];
				req.soajs.log.debug("Validating Resource db inputs ", resourceSection);
				let dbData = {
					"name": dataImfv.name,
					"type": dataImfv.type,
					"category": dataImfv.category,
					"locked": dataImfv.locked,
					"plugged": dataImfv.plugged,
					"shared": dataImfv.shared,
					"config": dataImfv.config || null
				};
				if(dataImfv.sharedEnv){
					dbData["sharedEnv"] = dataImfv.sharedEnv;
				}

				let status = myValidator.validate(dbData, schema);
				if (!status.valid) {
					status.errors.forEach(function (err) {
						context.errors.push({code: 173, msg: `Resource ${resourceSection}: ` + err.stack});
					});
				}
				return mCb();
			},
			"validateCD": (mCb) =>{
				let cdData = dataImfv.deploy;
				if(cdData){
					let schema = context.config.schema.put["/resources/config/update"].config.validation;
					req.soajs.log.debug("Validating CD inputs ", resourceSection);

					let status = myValidator.validate(cdData, schema);
					if (!status.valid) {
						status.errors.forEach(function (err) {
							context.errors.push({code: 173, msg: `Resource ${resourceSection}: ` + err.stack});
						});
					}
				}
				return mCb();
			},
			"validateDeploy": (mCb) => {
				if(dataImfv.deploy){
					let imfv = context.config.schema.post["/cloud/services/soajs/deploy"];
					let schema = {
						"type": "object",
						"required": true,
						"properties":{
							recipe: imfv.recipe.validation,
							deployConfig: imfv.deployConfig.validation,
							autoScale: imfv.autoScale.validation,
							custom: imfv.custom.validation,
						}
					};

					req.soajs.log.debug("Validating deploy inputs ", resourceSection);
					let cdData = dataImfv.deploy.options;
					let status = myValidator.validate(cdData, schema);
					if (!status.valid) {
						status.errors.forEach(function (err) {
							context.errors.push({code: 173, msg: `Resource ${resourceSection}: ` + err.stack});
						});
					}
				}
				return mCb();
			}
		}, callback);
	},

	deploy: function(req, context, lib, async, BL, modelName, callback){
		let resourceName = context.opts.section[context.opts.section.length -1];

		//check if previously completed
		if(context.template.deploy[context.opts.stage][context.opts.group][context.opts.stepPath].status){
			if(context.template.deploy[context.opts.stage][context.opts.group][context.opts.stepPath].status.done){
				req.soajs.log.debug(`Resource ${resourceName} been previously created`);
				return callback(null, true);
			}
		}

		req.soajs.log.debug(`Deploying Resource ${resourceName} ...`);
		let dataImfv = {};
		context.opts.inputs.forEach((entryImfv) =>{
			if(entryImfv.name === resourceName){
				dataImfv = entryImfv;
			}
		});

		let data = {
			"env": context.environmentRecord.code.toUpperCase(),
			"resource": {
				"name": dataImfv.name,
				"type": dataImfv.type,
				"category": dataImfv.category,
				"locked": dataImfv.locked,
				"plugged": dataImfv.plugged,
				"shared": dataImfv.shared,
				"config": dataImfv.config || null
			}
		};

		if(dataImfv.sharedEnv){
			data.resource["sharedEnv"] = dataImfv.sharedEnv;
		}

		let resourceDB;
		let serviceDeploymentId;
		async.series({
			"createResource": function(mCb){
				req.soajs.log.debug("Adding Resource " + resourceName + " in Database under environment " + data.env );
				lib.initBLModel(BL.resources.module, modelName, (error, cdModule) => {
					lib.checkReturnError(req, mCb, {error: error, code: 600}, () => {
						req.soajs.inputmaskData = data;
						cdModule.addResource(context.config, req, null, (error, response) =>{
							lib.checkReturnError(req, mCb, {error: error, code: (error && error.code) ? error.code: 600}, () => {
								if (response && response._id){
									resourceDB = response._id.toString();
								}
								return mCb(null, true);
							});
						});
					});
				});
			},
			"registerCD": function (mCb) {
				if(dataImfv.deploy && Object.keys(dataImfv.deploy).length > 0){
					req.soajs.log.debug("Registering CD entry for resource " + resourceName + " in environment " + data.env );
					lib.initBLModel(BL.resources.module, modelName, (error, cdModule) => {
						lib.checkReturnError(req, mCb, {error: error, code: 600}, () => {
							req.soajs.inputmaskData = {
								"env": context.environmentRecord.code.toUpperCase(),
								"resourceName": dataImfv.name,
								"config": {
									"deploy": true,
									"options": dataImfv.deploy
								}
							};
							cdModule.setConfig(context.config, req, null, mCb);
						});
					});
				}
				else{
					return mCb(null, true);
				}
			},
			"deployService": function (mCb) {
				if(dataImfv.deploy && Object.keys(dataImfv.deploy).length > 0){
					req.soajs.log.debug("Deploying resource " + resourceName + " in environment " + data.env);
					lib.initBLModel(BL.cloud.deploy.module, modelName, (error, deploymentModule) => {
						lib.checkReturnError(req, mCb, {error: error, code: 600}, () => {
							req.soajs.inputmaskData = {
								"deployConfig": dataImfv.deploy.options.deployConfig,
								"custom": dataImfv.deploy.options.custom,
								"recipe": dataImfv.deploy.options.recipe,
								"env": context.environmentRecord.code.toUpperCase()
							};

							//link the db id entry to the deployment
							req.soajs.inputmaskData.custom.resourceId = resourceDB;

							deploymentModule.deployService(context.config, req.soajs, deployer, (error, out) => {
								lib.checkReturnError(req, mCb, {error: error, code: 600}, () => {
									if(out && out.service){
										serviceDeploymentId = out.service.id;
									}
									return mCb(null, true);
								});
							});
						});
					});
				}
				else{
					return mCb(null, true);
				}
			}
		}, (error) => {
			req.soajs.log.debug(`Resource ${resourceName} Deployment completed`);
			//generate final response and update template
			lib.checkReturnError(req, callback, {error: error, code: (error && error.code) ? error.code: 600}, () => {
				context.template.deploy[context.opts.stage][context.opts.group][context.opts.stepPath].status = {
					"done": true,
					"data": { "db": resourceDB }
				};
				if(serviceDeploymentId){
					context.template.deploy[context.opts.stage][context.opts.group][context.opts.stepPath].status.data["id"] = serviceDeploymentId;
					context.template.deploy[context.opts.stage][context.opts.group][context.opts.stepPath].status.data["mode"] = dataImfv.deploy.options.deployConfig.replication.mode;
				}
				return callback(null, true);
			});
		});
	},

	rollback: function(req, context, lib, async, BL, modelName, callback){
		//check if previously completed
		if(context.template.deploy[context.opts.stage][context.opts.group][context.opts.stepPath].status){
			if(context.template.deploy[context.opts.stage][context.opts.group][context.opts.stepPath].status.done){
				req.soajs.log.debug(`Rolling back Deployed Resources ...`);

				let data = context.template.deploy[context.opts.stage][context.opts.group][context.opts.stepPath].status.data;
				async.series({
					"removingDB": function(mCb){
						if(!data || !data.db){
							return mCb();
						}

						lib.initBLModel(BL.cloud.resources.module, modelName, (error, cdModule) => {
							lib.checkReturnError(req, mCb, {error: error, code: 600}, () => {
								req.soajs.inputmaskData = {
									env: context.environmentRecord.code,
									id: data.db
								};
								cdModule.deleteResource(context.config, req, null, (error, response) =>{
									lib.checkReturnError(req, mCb, {error: error, code: (error && error.code) ? error.code: 600}, () => {
										if(error){
											req.soajs.log.error(error);
										}
										return mCb(null, true);
									});
								});
							});
						});
					},
					"removingDeployment": function(mCb){
						if(!data || !data.id){
							return mCb();
						}

						lib.initBLModel(BL.cloud.services.module, modelName, (error, servicesModule) => {
							lib.checkReturnError(req, mCb, {error: error, code: 600}, () => {
								req.soajs.inputmaskData = {
									env: context.environmentRecord.code,
									serviceId: data.id,
									mode: data.mode
								};

								servicesModule.deleteService(context.config, req.soajs, deployer, (error) => {
									if(error){
										req.soajs.log.error(error);
									}
									return mCb(null, true);
								});
							});
						});
					}
				}, () =>{
					return callback(null, true);
				});
			}
			else{
				return callback(null, true);
			}
		}
		else{
			return callback(null, true);
		}
	}
};

module.exports = repos;<|endoftext|>