<commit_before>require('time')(Date);

var index = function(req, res) {
  findCountry(req, function(country) {

    // this is only used as a fallback for clients who don't use JavaScript
    // if I must pick a timezone for them, let's choose the opposite of the dateline
    var utcTime = new Date();
    utcTime.setTimezone("UTC");

    res.render('index', {
      answer: Christmas.answer(country, utcTime),
      country: country,

      req: req,
      config: config,
      env: app.get('env')
    });
  });
};

var rss = function(req, res) {
  res.set({'Content-Type': 'application/rss+xml'});

  findCountry(req, function(country) {
    res.render('rss.xml', {
      country: country,
      Christmas: Christmas,
      dateFormat: dateFormat,

      config: config,
      env: app.get('env')
    });
  });
};

var canary = function(req, res) {
  res.setHeader('Content-Type', 'text/plain');
  findCountry(req, function(country) {
    res.render('canary.txt', {
      Christmas: Christmas,
      dateFormat: dateFormat,
      country: country
    });
  });
};

// static view uses same admin password to grab/render snapshot from admin app
var boards = function(req, res) {
  if (req.param("admin") != config.admin.password)
    res.status(403).send("Huh?");
  else {
    res.render('boards', {
      req: req,
      config: config
    });
  }
};

/** helpers **/

var findCountry = function(req, callback) {
  if (req.param("country"))
    return callback(req.param("country"));

  var forwarded = req.header("X-Forwarded-For");
  var ip = req.param("ip") || forwarded || req.socket.remoteAddress;

  if (db == null) {
    console.log("Connecting to MongoDB for first time...");
    mongo.connect(config.mongodb, function(database) {
      db = database; // cache database
      lookupCountry(ip, db, callback);
    });
  } else
    lookupCountry(ip, db, callback);
};

var lookupCountry = function(ip, database, callback) {
  database.collection("blocks", function(err, collection) {
    if (err) {console.log("Error connecting to 'blocks'"); return "EO";}

    // debug: French IP
    // ip = "193.51.208.14";

    var intIp = ipToInteger(ip);

    collection.findOne({ip_start: {"$lte": intIp}, ip_end: {"$gte": intIp}}, function(err, item) {
      if (err) {console.log("Error finding row"); return callback("EO");}

      if (item == null) {
        // console.log("Invalid IP address (" + ip + ":" + intIp + "), returning 'US'");
        callback("EO");
      } else {
        country = item.country;
        // console.log("Found country for " + ip + ": " + country);
        callback(country);
      }
    });
  })
};

var ipToInteger = function(ip) {
  var pieces = ip.split(".");
  return (parseInt(pieces[0]) * 16777216)
    + (parseInt(pieces[1]) * 65536)
    + (parseInt(pieces[2]) * 256)
    + parseInt(pieces[3]);
}

/** configuration **/

var express = require('express'),
    http = require('http'),
    request = require('request'),
    path = require('path'),
    dateFormat = require('dateformat'),
    Christmas = require("./public/js/christmas"); // re-use christmas.js
require('date-utils'); // date helpers

var app = express(),
    config = require('./config')[app.get('env')],
    mongo = require('./mongo'),
    db = null; // connect on first request (why is this my best option?)

app.configure(function(){
  app.engine('.html', require('ejs').__express);
  app.engine('.xml', require('ejs').__express);
  app.engine('.txt', require('ejs').__express);
  app.set('port', config.port || process.env.PORT || 80);
  app.set('view engine', 'html');
  app.use(express.favicon(__dirname + '/public/favicon.ico'));
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function() {app.use(express.errorHandler())});

app.get('/', index);
app.get('/rss.xml', rss);
app.get('/canary.txt', canary);
// proxy flag data from a room from the streaming server
app.get('/flags', function(req, res) {req.pipe(request(config.streaming[0] + '/flags')).pipe(res)});
app.get('/boards', boards);

var startServer = function() {

  app.enable('trust proxy'); // allow it to use forwarded headers/IPs/etc

  http.createServer(app).listen(app.get('port'), function(){
    console.log("Express %s server listening on port %s", app.settings.env, app.get('port'));
  });
}

app.configure('development', function() {
  app.use(express.errorHandler());

  require('reloader')({
    watchModules: true,
    onReload: startServer
  });
});

app.configure('production', startServer);
<commit_msg>/flags is dead, long live /flags<commit_after>require('time')(Date);

var index = function(req, res) {
  findCountry(req, function(country) {

    // this is only used as a fallback for clients who don't use JavaScript
    // if I must pick a timezone for them, let's choose the opposite of the dateline
    var utcTime = new Date();
    utcTime.setTimezone("UTC");

    res.render('index', {
      answer: Christmas.answer(country, utcTime),
      country: country,

      req: req,
      config: config,
      env: app.get('env')
    });
  });
};

var rss = function(req, res) {
  res.set({'Content-Type': 'application/rss+xml'});

  findCountry(req, function(country) {
    res.render('rss.xml', {
      country: country,
      Christmas: Christmas,
      dateFormat: dateFormat,

      config: config,
      env: app.get('env')
    });
  });
};

var canary = function(req, res) {
  res.setHeader('Content-Type', 'text/plain');
  findCountry(req, function(country) {
    res.render('canary.txt', {
      Christmas: Christmas,
      dateFormat: dateFormat,
      country: country
    });
  });
};

// static view uses same admin password to grab/render snapshot from admin app
var boards = function(req, res) {
  if (req.param("admin") != config.admin.password)
    res.status(403).send("Huh?");
  else {
    res.render('boards', {
      req: req,
      config: config
    });
  }
};

/** helpers **/

var findCountry = function(req, callback) {
  if (req.param("country"))
    return callback(req.param("country"));

  var forwarded = req.header("X-Forwarded-For");
  var ip = req.param("ip") || forwarded || req.socket.remoteAddress;

  if (db == null) {
    console.log("Connecting to MongoDB for first time...");
    mongo.connect(config.mongodb, function(database) {
      db = database; // cache database
      lookupCountry(ip, db, callback);
    });
  } else
    lookupCountry(ip, db, callback);
};

var lookupCountry = function(ip, database, callback) {
  database.collection("blocks", function(err, collection) {
    if (err) {console.log("Error connecting to 'blocks'"); return "EO";}

    // debug: French IP
    // ip = "193.51.208.14";

    var intIp = ipToInteger(ip);

    collection.findOne({ip_start: {"$lte": intIp}, ip_end: {"$gte": intIp}}, function(err, item) {
      if (err) {console.log("Error finding row"); return callback("EO");}

      if (item == null) {
        // console.log("Invalid IP address (" + ip + ":" + intIp + "), returning 'US'");
        callback("EO");
      } else {
        country = item.country;
        // console.log("Found country for " + ip + ": " + country);
        callback(country);
      }
    });
  })
};

var ipToInteger = function(ip) {
  var pieces = ip.split(".");
  return (parseInt(pieces[0]) * 16777216)
    + (parseInt(pieces[1]) * 65536)
    + (parseInt(pieces[2]) * 256)
    + parseInt(pieces[3]);
}

/** configuration **/

var express = require('express'),
    http = require('http'),
    request = require('request'),
    path = require('path'),
    dateFormat = require('dateformat'),
    Christmas = require("./public/js/christmas"); // re-use christmas.js
require('date-utils'); // date helpers

var app = express(),
    config = require('./config')[app.get('env')],
    mongo = require('./mongo'),
    db = null; // connect on first request (why is this my best option?)

app.configure(function(){
  app.engine('.html', require('ejs').__express);
  app.engine('.xml', require('ejs').__express);
  app.engine('.txt', require('ejs').__express);
  app.set('port', config.port || process.env.PORT || 80);
  app.set('view engine', 'html');
  app.use(express.favicon(__dirname + '/public/favicon.ico'));
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function() {app.use(express.errorHandler())});

app.get('/', index);
app.get('/rss.xml', rss);
app.get('/canary.txt', canary);
app.get('/boards', boards);

var startServer = function() {

  app.enable('trust proxy'); // allow it to use forwarded headers/IPs/etc

  http.createServer(app).listen(app.get('port'), function(){
    console.log("Express %s server listening on port %s", app.settings.env, app.get('port'));
  });
}

app.configure('development', function() {
  app.use(express.errorHandler());

  require('reloader')({
    watchModules: true,
    onReload: startServer
  });
});

app.configure('production', startServer);
<|endoftext|>


<commit_before>'use strict';

var
U       = require('./u'),
objects = require('./objects');

exports.create = objects.factory({

  // spec.name
  // spec.version
  // spec.appdir
  // spec.sysconfigsdir
  // spec.packageJSON
  // spec.environment
  // spec.configs
  // spec.argv
  initialize: function (spec) {
    Object.defineProperties(this, {
      name: {
        enumerable: true,
        value: spec.name
      },
      version: {
        enumerable: true,
        value: spec.version
      },
      appdir: {
        enumerable: true,
        value: spec.appdir
      },
      sysconfigsdir: {
        enumerable: true,
        value: spec.sysconfigsdir
      },
      packageJSON: {
        enumerable: true,
        value: U.deepFreeze(spec.packageJSON)
      },
      environment: {
        enumerable: true,
        value: spec.environment
      },
      configs: {
        enumerable: true,
        value: U.deepFreeze(spec.configs)
      },
      argv: {
        enumerable: true,
        value: U.deepFreeze(spec.argv)
      },
      API: {
        enumerable: true,
        value: Object.create(null)
      }
    });
  }
});
<commit_msg>Update the appication object.<commit_after>'use strict';

var
U       = require('./u'),
objects = require('./objects');

exports.create = objects.factory({

  // spec.name
  // spec.version
  // spec.appdir
  // spec.packageJSON
  // spec.environment
  // spec.argv
  initialize: function (spec) {
    Object.defineProperties(this, {
      name: {
        enumerable: true,
        value: spec.name
      },
      version: {
        enumerable: true,
        value: spec.version
      },
      appdir: {
        enumerable: true,
        value: spec.appdir
      },
      packageJSON: {
        enumerable: true,
        value: spec.packageJSON ? U.deepFreeze(spec.packageJSON) : null
      },
      environment: {
        enumerable: true,
        value: spec.environment
      },
      configs: {
        enumerable: true,
        value: Object.create(null)
      },
      argv: {
        enumerable: true,
        value: U.deepFreeze(spec.argv)
      },
      API: {
        enumerable: true,
        value: Object.create(null)
      }
    });
  }
});
<|endoftext|>


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

var express = require('express')
  , routes = require('./routes')
  , http = require('http')
  , path = require('path');

var app = express();

app.configure(function(){
  app.set('port', process.env.GCS_CONSOLE_PORT || 7576);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

app.get('/', routes.index);

http.createServer(app).listen(app.get('port'), function(){
  console.log("Groonga CloudSearch Consolelistening on port " +
              app.get('port'));
});
<commit_msg>Add a missing space<commit_after>
/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , http = require('http')
  , path = require('path');

var app = express();

app.configure(function(){
  app.set('port', process.env.GCS_CONSOLE_PORT || 7576);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

app.get('/', routes.index);

http.createServer(app).listen(app.get('port'), function(){
  console.log("Groonga CloudSearch Console listening on port " +
              app.get('port'));
});
<|endoftext|>


<commit_before>'use strict';

// Firebase real-time db
var db = firebase.database();
// Service Workers
var isSubscribed = false;
var swRegistration = null;
var pushButton = document.querySelector('#pushBtn');

function initialiseUI() {
  pushButton.addEventListener('click', function(event) {
    event.preventDefault();
    if (isSubscribed) {
      // unSubscribeUser();
    } else {
      subscribeUser();
    }
  });

  // Notification 구현여부 확인
  if (!(swRegistration.showNotification)) {
    console.log('Notifications aren\'t supported on service workers.');
  } else {
    console.log('Notifications are supported on this service worker.');
  }

  // Notification 권한 확인
  if (Notification.permission === 'denied') {
    console.log('The user has blocked notifications.');
    return;
  }

  // Push 메시지 지원여부 확인
  if (!('PushManager' in window)) {
    console.log('Push messaging isn\'t supported.');
    return;
  } else {
    console.log("PushManager is supported.");
  }

  navigator.serviceWorker.ready.then(function(swRegistration) {
    swRegistration.pushManager.getSubscription().then(function(subscription) {
      isSubscribed = !(subscription === null);

      // updateSubscriptionOnServer(subscription);

      if (isSubscribed) {
        console.log('User is subscribed.');

        var result = getEndpointAndKey(subscription);
        sendDeviceKeytoFirebase(result.endpoint, result.key);
      } else {
        console.log('User is NOT subscribed.');
      }
    });
  });
}

function subscribeUser() {
  swRegistration.pushManager.subscribe({
    userVisibleOnly: true
  })
  .then(function(subscription) {
    console.log('User is subscribed:', subscription);

    var result = getEndpointAndKey(subscription);
    sendDeviceKeytoFirebase(result.endpoint, result.key);
    isSubscribed = true;
  })
  .catch(function(err) {
    console.log('Failed to subscribe the user: ', err);
  });
}

function sendDeviceKeytoFirebase(endpoint, key) {
  return db.ref('users/' + key + '/').set({
    endpoint: endpoint,
    key: key,
    time: getCurrentTime()
  }).then(function () {
    console.log("The key has been sent to Firebase DB");
  }).catch(function () {
    console.error('Sending a key to server has been failed');
  });
}

function getCurrentTime() {
  return new Date().toLocaleString();
}

function getEndpointAndKey(subscription) {
  var endpoint = subscription.endpoint.split('send/')[1];
  var p256dh = subscription.getKey('p256dh');
  var key = btoa(String.fromCharCode.apply(null, new Uint8Array(p256dh)));
  var data = {
    endpoint: endpoint,
    key: key
  };
  return data;
}
<commit_msg>Replace all the forward slashes in browser pdh256 key<commit_after>'use strict';

// Firebase real-time db
var db = firebase.database();
// Service Workers
var isSubscribed = false;
var swRegistration = null;
var pushButton = document.querySelector('#pushBtn');

function initialiseUI() {
  pushButton.addEventListener('click', function(event) {
    event.preventDefault();
    if (isSubscribed) {
      // unSubscribeUser();
    } else {
      subscribeUser();
    }
  });

  // Notification 구현여부 확인
  if (!(swRegistration.showNotification)) {
    console.log('Notifications aren\'t supported on service workers.');
  } else {
    console.log('Notifications are supported on this service worker.');
  }

  // Notification 권한 확인
  if (Notification.permission === 'denied') {
    console.log('The user has blocked notifications.');
    return;
  }

  // Push 메시지 지원여부 확인
  if (!('PushManager' in window)) {
    console.log('Push messaging isn\'t supported.');
    return;
  } else {
    console.log("PushManager is supported.");
  }

  navigator.serviceWorker.ready.then(function(swRegistration) {
    swRegistration.pushManager.getSubscription().then(function(subscription) {
      isSubscribed = !(subscription === null);

      // updateSubscriptionOnServer(subscription);

      if (isSubscribed) {
        console.log('User is subscribed.');

        var result = getEndpointAndKey(subscription);
        sendDeviceKeytoFirebase(result.endpoint, result.key);
      } else {
        console.log('User is NOT subscribed.');
      }
    });
  });
}

function subscribeUser() {
  swRegistration.pushManager.subscribe({
    userVisibleOnly: true
  })
  .then(function(subscription) {
    console.log('User is subscribed:', subscription);

    var result = getEndpointAndKey(subscription);
    sendDeviceKeytoFirebase(result.endpoint, result.key);
    isSubscribed = true;
  })
  .catch(function(err) {
    console.log('Failed to subscribe the user: ', err);
  });
}

function sendDeviceKeytoFirebase(endpoint, key) {
  return db.ref('users/' + key + '/').set({
    endpoint: endpoint,
    key: key,
    time: getCurrentTime()
  }).then(function () {
    console.log("The key has been sent to Firebase DB");
  }).catch(function () {
    console.error('Sending a key to server has been failed');
  });
}

function getCurrentTime() {
  return new Date().toLocaleString();
}

function getEndpointAndKey(subscription) {
  var endpoint = subscription.endpoint.split('send/')[1];
  var p256dh = subscription.getKey('p256dh');
  var key = btoa(String.fromCharCode.apply(null, new Uint8Array(p256dh)));
  var data = {
    endpoint: endpoint,
    key: key.replace(/\//g, "-")
  };
  return data;
}
<|endoftext|>


<commit_before>"use strict";
/* globals socket, app, utils */

$(document).ready(function() {
	var groupList = [];
	var localUserList = [];

	$(window).on('composer:autocomplete:init chat:autocomplete:init', function(ev, data) {
		loadTopicUsers(data.element);

		if (!groupList.length) {
			loadGroupList();
		}

		var subset;
		var strategy = {
			match: /\B@([^\s\n]*)?$/,
			search: function (term, callback) {
				var usernames;
				if (!term) {
					usernames = localUserList.concat(groupList).filter(function(value, index, array) {
						// Remove duplicates and calling user's username
						return array.indexOf(value) === index && value !== app.user.username;
					}).sort(function(a, b) {
						return a.toLocaleLowerCase() > b.toLocaleLowerCase();
					});
					return callback(usernames);
				}

				// Get composer metadata
				var uuid = data.options.className.match(/dropdown-(.+?)\s/)[1];
				require(['composer'], function (composer) {
					socket.emit('plugins.mentions.userSearch', {
						query: term,
						composerObj: composer.posts[uuid],
					}, function(err, userdata) {
						if (err) {
							return callback([]);
						}

						usernames = userdata.users.map(function(user) {
							return user.username;
						});

						// Remove current user from suggestions
						if (app.user.username && usernames.indexOf(app.user.username) !== -1) {
							usernames.splice(usernames.indexOf(app.user.username), 1);
						}

						callback(usernames);
					});
				});
			},
			index: 1,
			replace: function (mention) {
				mention = $('<div/>').html(mention).text();
				return '@' + utils.slugify(mention, true) + ' ';
			},
			cache: true
		};

		data.strategies.push(strategy);
	});

	$(window).on('action:composer.loaded', function(e, data) {
		var composer = $('#cmp-uuid-' + data.post_uuid + ' .write');
		composer.attr('data-mentions', '1');
	});

	function loadTopicUsers(element) {
		require(['composer'], function (composer) {
			var composerEl = element.parents('.composer').get(0);
			var uuid = composerEl.getAttribute('data-uuid');
			var composerObj = composer.posts[uuid];

			if (!composerObj.tid) {
				return;
			}

			socket.emit('plugins.mentions.getTopicUsers', {
				tid: composerObj.tid,
			}, function (err, usernames) {
				localUserList = usernames;
			});
		});
	}

	function loadGroupList() {
		socket.emit('plugins.mentions.listGroups', function(err, groupNames) {
			if (err) {
				return app.alertError(err.message);
			}
			groupList = groupNames;
		});
	}

});
<commit_msg>fix: bug where localUserList was not emptied properly<commit_after>"use strict";
/* globals socket, app, utils */

$(document).ready(function() {
	var groupList = [];
	var localUserList = [];

	$(window).on('composer:autocomplete:init chat:autocomplete:init', function(ev, data) {
		loadTopicUsers(data.element);

		if (!groupList.length) {
			loadGroupList();
		}

		var subset;
		var strategy = {
			match: /\B@([^\s\n]*)?$/,
			search: function (term, callback) {
				var usernames;
				if (!term) {
					usernames = localUserList.concat(groupList).filter(function(value, index, array) {
						// Remove duplicates and calling user's username
						return array.indexOf(value) === index && value !== app.user.username;
					}).sort(function(a, b) {
						return a.toLocaleLowerCase() > b.toLocaleLowerCase();
					});
					return callback(usernames);
				}

				// Get composer metadata
				var uuid = data.options.className.match(/dropdown-(.+?)\s/)[1];
				require(['composer'], function (composer) {
					socket.emit('plugins.mentions.userSearch', {
						query: term,
						composerObj: composer.posts[uuid],
					}, function(err, userdata) {
						if (err) {
							return callback([]);
						}

						usernames = userdata.users.map(function(user) {
							return user.username;
						});

						// Remove current user from suggestions
						if (app.user.username && usernames.indexOf(app.user.username) !== -1) {
							usernames.splice(usernames.indexOf(app.user.username), 1);
						}

						callback(usernames);
					});
				});
			},
			index: 1,
			replace: function (mention) {
				mention = $('<div/>').html(mention).text();
				return '@' + utils.slugify(mention, true) + ' ';
			},
			cache: true
		};

		data.strategies.push(strategy);
	});

	$(window).on('action:composer.loaded', function(e, data) {
		var composer = $('#cmp-uuid-' + data.post_uuid + ' .write');
		composer.attr('data-mentions', '1');
	});

	function loadTopicUsers(element) {
		require(['composer'], function (composer) {
			var composerEl = element.parents('.composer').get(0);
			var uuid = composerEl.getAttribute('data-uuid');
			var composerObj = composer.posts[uuid];

			if (!composerObj.tid) {
				localUserList = [];
				return;
			}

			socket.emit('plugins.mentions.getTopicUsers', {
				tid: composerObj.tid,
			}, function (err, usernames) {
				localUserList = usernames;
			});
		});
	}

	function loadGroupList() {
		socket.emit('plugins.mentions.listGroups', function(err, groupNames) {
			if (err) {
				return app.alertError(err.message);
			}
			groupList = groupNames;
		});
	}

});
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var quotes = require('./routes/v1/quotes');
var zivis = require('./routes/v1/zivis');
var post = require('./routes/v1/post');
var flade = require('./routes/v1/flade');

require('./timers/zivi.timer.js');
require('./services/telegram.service');
var NetUsageService = require('./services/netusage.service');

setInterval(NetUsageService.loadAndPushNetUsage, 1000);

var PostTimer = require('./timers/post.timer.js');
const FIVE_SECONDS = 5 * 1000;
setInterval(PostTimer.checkAndNotify, FIVE_SECONDS);

var FladeService = require('./services/flade.service');
const ONE_DAY = 86400 * 1000;
setInterval(FladeService.getAndSaveCurrentFlade, ONE_DAY);
//Calling it once to get the current flade on restart
FladeService.getAndSaveCurrentFlade(function(flade){
  console.log('Setting flade of the day', flade);
});

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
  next();
});

app.use('/api/v1/quotes', quotes);
app.use('/api/v1/zivis', zivis);
app.use('/api/v1/post', post);
app.use('/api/v1/flade', flade);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function (err, req, res) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.json(err);
});

module.exports = app;
<commit_msg>Small time change<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var quotes = require('./routes/v1/quotes');
var zivis = require('./routes/v1/zivis');
var post = require('./routes/v1/post');
var flade = require('./routes/v1/flade');

require('./timers/zivi.timer.js');
require('./services/telegram.service');
var NetUsageService = require('./services/netusage.service');

setInterval(NetUsageService.loadAndPushNetUsage, 2000);

var PostTimer = require('./timers/post.timer.js');
const FIVE_SECONDS = 5 * 1000;
setInterval(PostTimer.checkAndNotify, FIVE_SECONDS);

var FladeService = require('./services/flade.service');
const ONE_DAY = 86400 * 1000;
setInterval(FladeService.getAndSaveCurrentFlade, ONE_DAY);
//Calling it once to get the current flade on restart
FladeService.getAndSaveCurrentFlade(function(flade){
  console.log('Setting flade of the day', flade);
});

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
  next();
});

app.use('/api/v1/quotes', quotes);
app.use('/api/v1/zivis', zivis);
app.use('/api/v1/post', post);
app.use('/api/v1/flade', flade);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function (err, req, res) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.json(err);
});

module.exports = app;
<|endoftext|>


<commit_before>var common = require('./common')
  , redis  = common.redis;

(function blpopSubscribe() {
  redis.blpop('stentor:subscribe', 0, function(err, data){
    console.log('stentor:subscribe blpop data', data);
    if (err) { return blpopSubscribe(); }
    common.models.Device.subscribe(data, blpopSubscribe);
  });
  console.log('listening to stentor:subscribe');
})();

(function blpopUnsubscribe() {
  redis.blpop('stentor:unsubscribe', 0, function(err, data){
    console.log('stentor:unsubscribe blpop data', data);
    if (err) { return blpopUnubscribe(); }
    common.models.Device.unsubscribe(data, blpopUnubscribe);
  });
  console.log('listening to stentor:unsubscribe');
})();

(function blpopNotify() {
  redis.blpop('stentor:notify', 0, function(err, data){
    console.log('stentor:notify blpop data', data);
    if (err) { return blpopNotify(); }
    common.models.Device.notify(data, blpopNotify);
  });
  console.log('listening to stentor:notify');
})();
<commit_msg>fixing typo<commit_after>var common = require('./common')
  , redis  = common.redis;

(function blpopSubscribe() {
  redis.blpop('stentor:subscribe', 0, function(err, data){
    console.log('stentor:subscribe blpop data', data);
    if (err) { return blpopSubscribe(); }
    common.models.Device.subscribe(data, blpopSubscribe);
  });
  console.log('listening to stentor:subscribe');
})();

(function blpopUnsubscribe() {
  redis.blpop('stentor:unsubscribe', 0, function(err, data){
    console.log('stentor:unsubscribe blpop data', data);
    if (err) { return blpopUnsubscribe(); }
    common.models.Device.unsubscribe(data, blpopUnsubscribe);
  });
  console.log('listening to stentor:unsubscribe');
})();

(function blpopNotify() {
  redis.blpop('stentor:notify', 0, function(err, data){
    console.log('stentor:notify blpop data', data);
    if (err) { return blpopNotify(); }
    common.models.Device.notify(data, blpopNotify);
  });
  console.log('listening to stentor:notify');
})();
<|endoftext|>


<commit_before>var Accessibility = require('./accessibility')
var Api = require('./api')
var ChromeDriver = require('./chrome-driver')
var DevNull = require('dev-null')
var fs = require('fs')
var path = require('path')
var WebDriver = require('webdriverio')

function Application (options) {
  options = options || {}
  this.host = options.host || '127.0.0.1'
  this.port = parseInt(options.port, 10) || 9515

  this.quitTimeout = parseInt(options.quitTimeout, 10) || 1000
  this.startTimeout = parseInt(options.startTimeout, 10) || 5000
  this.waitTimeout = parseInt(options.waitTimeout, 10) || 5000

  this.connectionRetryCount = parseInt(options.connectionRetryCount, 10) || 10
  this.connectionRetryTimeout = parseInt(options.connectionRetryTimeout, 10) || 30000

  this.nodePath = options.nodePath || process.execPath
  this.path = options.path

  this.args = options.args || []
  this.env = options.env || {}
  this.workingDirectory = options.cwd || process.cwd()
  this.debuggerAddress = options.debuggerAddress
  this.chromeDriverLogPath = options.chromeDriverLogPath
  this.requireName = options.requireName || 'require'

  this.api = new Api(this, this.requireName)
  this.setupPromiseness()
}

Application.prototype.setupPromiseness = function () {
  var self = this
  self.transferPromiseness = function (target, promise) {
    self.api.transferPromiseness(target, promise)
  }
}

Application.prototype.start = function () {
  var self = this
  return self.exists()
    .then(function () { return self.startChromeDriver() })
    .then(function () { return self.createClient() })
    .then(function () { return self.api.initialize() })
    .then(function () { return self.client.timeoutsAsyncScript(self.waitTimeout) })
    .then(function () { self.running = true })
    .then(function () { return self })
}

Application.prototype.stop = function () {
  var self = this

  if (!self.isRunning()) return Promise.reject(Error('Application not running'))

  return new Promise(function (resolve, reject) {
    var endClient = function () {
      setTimeout(function () {
        self.client.end().then(function () {
          self.chromeDriver.stop()
          self.running = false
          resolve(self)
        }, reject)
      }, self.quitTimeout)
    }

    if (self.api.nodeIntegration) {
      self.client.windowByIndex(0).electron.remote.app.quit().then(endClient, reject)
    } else {
      self.client.windowByIndex(0).execute(function () {
        window.close()
      }).then(endClient, reject)
    }
  })
}

Application.prototype.restart = function () {
  var self = this
  return self.stop().then(function () {
    return self.start()
  })
}

Application.prototype.isRunning = function () {
  return this.running
}

Application.prototype.getSettings = function () {
  return {
    host: this.host,
    port: this.port,
    quitTimeout: this.quitTimeout,
    startTimeout: this.startTimeout,
    waitTimeout: this.waitTimeout,
    connectionRetryCount: this.connectionRetryCount,
    connectionRetryTimeout: this.connectionRetryTimeout,
    nodePath: this.nodePath,
    path: this.path,
    args: this.args,
    env: this.env,
    workingDirectory: this.workingDirectory,
    debuggerAddress: this.debuggerAddress,
    chromeDriverLogPath: this.chromeDriverLogPath,
    requireName: this.requireName
  }
}

Application.prototype.exists = function () {
  var self = this
  return new Promise(function (resolve, reject) {
    // Binary path is ignored by ChromeDriver if debuggerAddress is set
    if (self.debuggerAddress) return resolve()

    if (typeof self.path !== 'string') {
      return reject(Error('Application path must be a string'))
    }

    fs.stat(self.path, function (error, stat) {
      if (error) return reject(error)
      if (stat.isFile()) return resolve()
      reject(Error('Application path specified is not a file: ' + self.path))
    })
  })
}

Application.prototype.startChromeDriver = function () {
  this.chromeDriver = new ChromeDriver(this.host, this.port, this.nodePath, this.startTimeout, this.workingDirectory, this.chromeDriverLogPath)
  return this.chromeDriver.start()
}

Application.prototype.createClient = function () {
  var self = this
  return new Promise(function (resolve, reject) {
    var args = []
    args.push('spectron-path=' + self.path)
    self.args.forEach(function (arg, index) {
      args.push('spectron-arg' + index + '=' + arg)
    })

    for (var name in self.env) {
      args.push('spectron-env-' + name + '=' + self.env[name])
    }

    var launcherPath = null
    if (process.platform === 'win32') {
      launcherPath = path.join(__dirname, '..', 'bin', 'launcher.exe')
    } else {
      launcherPath = path.join(__dirname, 'launcher.js')
    }

    if (process.env.APPVEYOR) {
      args.push('no-sandbox')
    }

    var options = {
      host: self.host,
      port: self.port,
      waitforTimeout: self.waitTimeout,
      connectionRetryCount: self.connectionRetryCount,
      connectionRetryTimeout: self.connectionRetryTimeout,
      desiredCapabilities: {
        browserName: 'electron',
        chromeOptions: {
          binary: launcherPath,
          args: args,
          debuggerAddress: self.debuggerAddress
        }
      },
      logOutput: DevNull()
    }

    self.client = WebDriver.remote(options)
    self.addCommands()
    self.initializeClient(resolve, reject)
  })
}

Application.prototype.initializeClient = function (resolve, reject) {
  var maxTries = 10
  var tries = 0
  var self = this
  var init = function () {
    tries++
    self.client.init().then(resolve, function (error) {
      if (tries >= maxTries) {
        error.message = 'Client initialization failed after ' + tries + ' attempts: '
        error.message += error.type + ' ' + error.message
        reject(error)
      } else {
        global.setTimeout(init, 250)
      }
    })
  }
  init()
}

Application.prototype.addCommands = function () {
  this.client.addCommand('waitUntilTextExists', function (selector, text, timeout) {
    return this.waitUntil(function () {
      return this.isExisting(selector).then(function (exists) {
        if (!exists) return false
        return this.getText(selector).then(function (selectorText) {
          return selectorText.indexOf(text) !== -1
        })
      })
    }, timeout).then(function () { }, function (error) {
      error.message = 'waitUntilTextExists ' + error.message
      throw error
    })
  })

  this.client.addCommand('waitUntilWindowLoaded', function (timeout) {
    return this.waitUntil(function () {
      return this.webContents.isLoading().then(function (loading) {
        return !loading
      })
    }, timeout).then(function () { }, function (error) {
      error.message = 'waitUntilWindowLoaded ' + error.message
      throw error
    })
  })

  this.client.addCommand('getWindowCount', function () {
    return this.windowHandles().then(getResponseValue).then(function (handles) {
      return handles.length
    })
  })

  this.client.addCommand('windowByIndex', function (index) {
    return this.windowHandles().then(getResponseValue).then(function (handles) {
      return this.window(handles[index])
    })
  })

  this.client.addCommand('getSelectedText', function () {
    return this.execute(function () {
      return window.getSelection().toString()
    }).then(getResponseValue)
  })

  this.client.addCommand('getRenderProcessLogs', function () {
    return this.log('browser').then(getResponseValue)
  })

  var self = this
  this.client.addCommand('getMainProcessLogs', function () {
    var logs = self.chromeDriver.getLogs()
    self.chromeDriver.clearLogs()
    return logs
  })

  Accessibility.addCommand(this.client, this.requireName)
}

var getResponseValue = function (response) {
  return response.value
}

module.exports = Application
<commit_msg>Allow logging of Webdriver output:<commit_after>var Accessibility = require('./accessibility')
var Api = require('./api')
var ChromeDriver = require('./chrome-driver')
var DevNull = require('dev-null')
var fs = require('fs')
var path = require('path')
var WebDriver = require('webdriverio')

function Application (options) {
  options = options || {}
  this.host = options.host || '127.0.0.1'
  this.port = parseInt(options.port, 10) || 9515

  this.quitTimeout = parseInt(options.quitTimeout, 10) || 1000
  this.startTimeout = parseInt(options.startTimeout, 10) || 5000
  this.waitTimeout = parseInt(options.waitTimeout, 10) || 5000

  this.connectionRetryCount = parseInt(options.connectionRetryCount, 10) || 10
  this.connectionRetryTimeout = parseInt(options.connectionRetryTimeout, 10) || 30000

  this.nodePath = options.nodePath || process.execPath
  this.path = options.path

  this.args = options.args || []
  this.env = options.env || {}
  this.workingDirectory = options.cwd || process.cwd()
  this.debuggerAddress = options.debuggerAddress
  this.chromeDriverLogPath = options.chromeDriverLogPath
  this.webdriverLogPath = options.webdriverLogPath
  this.requireName = options.requireName || 'require'

  this.api = new Api(this, this.requireName)
  this.setupPromiseness()
}

Application.prototype.setupPromiseness = function () {
  var self = this
  self.transferPromiseness = function (target, promise) {
    self.api.transferPromiseness(target, promise)
  }
}

Application.prototype.start = function () {
  var self = this
  return self.exists()
    .then(function () { return self.startChromeDriver() })
    .then(function () { return self.createClient() })
    .then(function () { return self.api.initialize() })
    .then(function () { return self.client.timeoutsAsyncScript(self.waitTimeout) })
    .then(function () { self.running = true })
    .then(function () { return self })
}

Application.prototype.stop = function () {
  var self = this

  if (!self.isRunning()) return Promise.reject(Error('Application not running'))

  return new Promise(function (resolve, reject) {
    var endClient = function () {
      setTimeout(function () {
        self.client.end().then(function () {
          self.chromeDriver.stop()
          self.running = false
          resolve(self)
        }, reject)
      }, self.quitTimeout)
    }

    if (self.api.nodeIntegration) {
      self.client.windowByIndex(0).electron.remote.app.quit().then(endClient, reject)
    } else {
      self.client.windowByIndex(0).execute(function () {
        window.close()
      }).then(endClient, reject)
    }
  })
}

Application.prototype.restart = function () {
  var self = this
  return self.stop().then(function () {
    return self.start()
  })
}

Application.prototype.isRunning = function () {
  return this.running
}

Application.prototype.getSettings = function () {
  return {
    host: this.host,
    port: this.port,
    quitTimeout: this.quitTimeout,
    startTimeout: this.startTimeout,
    waitTimeout: this.waitTimeout,
    connectionRetryCount: this.connectionRetryCount,
    connectionRetryTimeout: this.connectionRetryTimeout,
    nodePath: this.nodePath,
    path: this.path,
    args: this.args,
    env: this.env,
    workingDirectory: this.workingDirectory,
    debuggerAddress: this.debuggerAddress,
    chromeDriverLogPath: this.chromeDriverLogPath,
    requireName: this.requireName
  }
}

Application.prototype.exists = function () {
  var self = this
  return new Promise(function (resolve, reject) {
    // Binary path is ignored by ChromeDriver if debuggerAddress is set
    if (self.debuggerAddress) return resolve()

    if (typeof self.path !== 'string') {
      return reject(Error('Application path must be a string'))
    }

    fs.stat(self.path, function (error, stat) {
      if (error) return reject(error)
      if (stat.isFile()) return resolve()
      reject(Error('Application path specified is not a file: ' + self.path))
    })
  })
}

Application.prototype.startChromeDriver = function () {
  this.chromeDriver = new ChromeDriver(this.host, this.port, this.nodePath, this.startTimeout, this.workingDirectory, this.chromeDriverLogPath)
  return this.chromeDriver.start()
}

Application.prototype.createClient = function () {
  var self = this
  return new Promise(function (resolve, reject) {
    var args = []
    args.push('spectron-path=' + self.path)
    self.args.forEach(function (arg, index) {
      args.push('spectron-arg' + index + '=' + arg)
    })

    for (var name in self.env) {
      args.push('spectron-env-' + name + '=' + self.env[name])
    }

    var launcherPath = null
    if (process.platform === 'win32') {
      launcherPath = path.join(__dirname, '..', 'bin', 'launcher.exe')
    } else {
      launcherPath = path.join(__dirname, 'launcher.js')
    }

    if (process.env.APPVEYOR) {
      args.push('no-sandbox')
    }

    var options = {
      host: self.host,
      port: self.port,
      waitforTimeout: self.waitTimeout,
      connectionRetryCount: self.connectionRetryCount,
      connectionRetryTimeout: self.connectionRetryTimeout,
      desiredCapabilities: {
        browserName: 'electron',
        chromeOptions: {
          binary: launcherPath,
          args: args,
          debuggerAddress: self.debuggerAddress
        }
      },
      logOutput: DevNull()
    }

    if (self.webdriverLogPath) {
      options.logOutput = self.webdriverLogPath;
      options.logLevel = 'verbose';
    }

    self.client = WebDriver.remote(options)
    self.addCommands()
    self.initializeClient(resolve, reject)
  })
}

Application.prototype.initializeClient = function (resolve, reject) {
  var maxTries = 10
  var tries = 0
  var self = this
  var init = function () {
    tries++
    self.client.init().then(resolve, function (error) {
      if (tries >= maxTries) {
        error.message = 'Client initialization failed after ' + tries + ' attempts: '
        error.message += error.type + ' ' + error.message
        reject(error)
      } else {
        global.setTimeout(init, 250)
      }
    })
  }
  init()
}

Application.prototype.addCommands = function () {
  this.client.addCommand('waitUntilTextExists', function (selector, text, timeout) {
    return this.waitUntil(function () {
      return this.isExisting(selector).then(function (exists) {
        if (!exists) return false
        return this.getText(selector).then(function (selectorText) {
          return selectorText.indexOf(text) !== -1
        })
      })
    }, timeout).then(function () { }, function (error) {
      error.message = 'waitUntilTextExists ' + error.message
      throw error
    })
  })

  this.client.addCommand('waitUntilWindowLoaded', function (timeout) {
    return this.waitUntil(function () {
      return this.webContents.isLoading().then(function (loading) {
        return !loading
      })
    }, timeout).then(function () { }, function (error) {
      error.message = 'waitUntilWindowLoaded ' + error.message
      throw error
    })
  })

  this.client.addCommand('getWindowCount', function () {
    return this.windowHandles().then(getResponseValue).then(function (handles) {
      return handles.length
    })
  })

  this.client.addCommand('windowByIndex', function (index) {
    return this.windowHandles().then(getResponseValue).then(function (handles) {
      return this.window(handles[index])
    })
  })

  this.client.addCommand('getSelectedText', function () {
    return this.execute(function () {
      return window.getSelection().toString()
    }).then(getResponseValue)
  })

  this.client.addCommand('getRenderProcessLogs', function () {
    return this.log('browser').then(getResponseValue)
  })

  var self = this
  this.client.addCommand('getMainProcessLogs', function () {
    var logs = self.chromeDriver.getLogs()
    self.chromeDriver.clearLogs()
    return logs
  })

  Accessibility.addCommand(this.client, this.requireName)
}

var getResponseValue = function (response) {
  return response.value
}

module.exports = Application
<|endoftext|>


<commit_before>'use strict'
import isGetSetProp from 'is-get-set-prop'
import isJsType from 'is-js-type'
import isObjProp from 'is-obj-prop'
import isProtoProp from 'is-proto-prop'

/**
 * Return type of value of left or right
 * @param {Object} o - left or right of node.object
 * @return {String} - type of o
 */
const getType = o => {
  const type = typeof o.value

  if (o.regex) {
    return 'RegExp'
  }

  return type.charAt(0).toUpperCase() + type.slice(1)
}

/**
 * Returns type of binary expression result
 * @param {Object} o - node's object with a BinaryExpression type
 * @return {String} - type of value produced
 */
const binaryExpressionProduces = o => {
  const leftType = o.left.type === 'BinaryExpression' ? binaryExpressionProduces(o.left) : getType(o.left)
  const rightType = o.right.type === 'BinaryExpression' ? binaryExpressionProduces(o.right) : getType(o.right)

  const isRegExp = leftType === rightType && leftType === 'RegExp'
  if (leftType === 'String' || rightType === 'String' || isRegExp) {
    return 'String'
  }

  if (leftType === rightType) {
    return leftType
  }

  return 'Unknown'
}

/**
 * Returns the JS type and property name
 * @param {Object} node - node to examine
 * @return {Object} - jsType and propertyName
 */
const getJsTypeAndPropertyName = node => {
  let propertyName, jsType

  switch (node.object.type) {
    case 'NewExpression':
      jsType = node.object.callee.name
      break
    case 'Literal':
      jsType = getType(node.object)
      break
    case 'BinaryExpression':
      jsType = binaryExpressionProduces(node.object)
      break
    case 'Identifier':
      if (node.property.name === 'prototype' && node.parent.property) {
        jsType = node.object.name
        propertyName = node.parent.property.name
      } else {
        jsType = node.object.name
      }
      break
    default:
      jsType = node.object.type.replace('Expression', '')
  }

  propertyName = propertyName || node.property.name || node.property.value

  return {propertyName, jsType}
}

const isUnkownGettSetterOrJsTypeExpressed = (jsType, propertyName, usageType) => {
  const isExpression = usageType === 'ExpressionStatement' || usageType === 'MemberExpression'

  return isExpression && !isGetSetProp(jsType, propertyName) &&
    !isProtoProp(jsType, propertyName) && !isObjProp(jsType, propertyName)
}

/**
 * Determine if a jsType's usage of propertyName is valid
 * @param {String} jsType - the JS type to validate
 * @param {String} propertyName - the property name to validate usage of on jsType
 * @param {String} usageType - how propertyName is being used
 * @return {Boolean} - is the usage invalid?
 */
const isInvalid = (jsType, propertyName, usageType) => {
  if (typeof propertyName !== 'string' || typeof jsType !== 'string' || !isJsType(jsType)) {
    return false
  }

  const unknownGetterSetterOrjsTypeExpressed = isUnkownGettSetterOrJsTypeExpressed(jsType, propertyName, usageType)

  const isFunctionCall = usageType === 'CallExpression'
  const getterSetterCalledAsFunction = isFunctionCall && isGetSetProp(jsType, propertyName)

  const unknownjsTypeCalledAsFunction = isFunctionCall && !isProtoProp(jsType, propertyName) &&
    !isObjProp(jsType, propertyName)

  return unknownGetterSetterOrjsTypeExpressed || getterSetterCalledAsFunction || unknownjsTypeCalledAsFunction
}

module.exports = context => ({
  MemberExpression(node) {
    /* eslint complexity: [2, 9] */
    if (node.computed && node.property.type === 'Identifier') {
      /**
       * handles cases like {}[i][j]
       * not enough information to identify type of variable in computed properties
       * so ignore false positives by not performing any checks
       */

      return
    }

    const isArgToParent = node.parent.arguments && node.parent.arguments.indexOf(node) > -1
    const usageType = isArgToParent ? node.type : node.parent.type

    const {propertyName, jsType} = getJsTypeAndPropertyName(node)

    if (isInvalid(jsType, propertyName, usageType) && isInvalid('Function', propertyName, usageType)) {
      context.report(node, 'Avoid using extended native objects')
    }
  }
})
<commit_msg>feat: use eslint's newer rule format along with `meta.type: "problem"`<commit_after>'use strict'
import isGetSetProp from 'is-get-set-prop'
import isJsType from 'is-js-type'
import isObjProp from 'is-obj-prop'
import isProtoProp from 'is-proto-prop'

/**
 * Return type of value of left or right
 * @param {Object} o - left or right of node.object
 * @return {String} - type of o
 */
const getType = o => {
  const type = typeof o.value

  if (o.regex) {
    return 'RegExp'
  }

  return type.charAt(0).toUpperCase() + type.slice(1)
}

/**
 * Returns type of binary expression result
 * @param {Object} o - node's object with a BinaryExpression type
 * @return {String} - type of value produced
 */
const binaryExpressionProduces = o => {
  const leftType = o.left.type === 'BinaryExpression' ? binaryExpressionProduces(o.left) : getType(o.left)
  const rightType = o.right.type === 'BinaryExpression' ? binaryExpressionProduces(o.right) : getType(o.right)

  const isRegExp = leftType === rightType && leftType === 'RegExp'
  if (leftType === 'String' || rightType === 'String' || isRegExp) {
    return 'String'
  }

  if (leftType === rightType) {
    return leftType
  }

  return 'Unknown'
}

/**
 * Returns the JS type and property name
 * @param {Object} node - node to examine
 * @return {Object} - jsType and propertyName
 */
const getJsTypeAndPropertyName = node => {
  let propertyName, jsType

  switch (node.object.type) {
    case 'NewExpression':
      jsType = node.object.callee.name
      break
    case 'Literal':
      jsType = getType(node.object)
      break
    case 'BinaryExpression':
      jsType = binaryExpressionProduces(node.object)
      break
    case 'Identifier':
      if (node.property.name === 'prototype' && node.parent.property) {
        jsType = node.object.name
        propertyName = node.parent.property.name
      } else {
        jsType = node.object.name
      }
      break
    default:
      jsType = node.object.type.replace('Expression', '')
  }

  propertyName = propertyName || node.property.name || node.property.value

  return {propertyName, jsType}
}

const isUnkownGettSetterOrJsTypeExpressed = (jsType, propertyName, usageType) => {
  const isExpression = usageType === 'ExpressionStatement' || usageType === 'MemberExpression'

  return isExpression && !isGetSetProp(jsType, propertyName) &&
    !isProtoProp(jsType, propertyName) && !isObjProp(jsType, propertyName)
}

/**
 * Determine if a jsType's usage of propertyName is valid
 * @param {String} jsType - the JS type to validate
 * @param {String} propertyName - the property name to validate usage of on jsType
 * @param {String} usageType - how propertyName is being used
 * @return {Boolean} - is the usage invalid?
 */
const isInvalid = (jsType, propertyName, usageType) => {
  if (typeof propertyName !== 'string' || typeof jsType !== 'string' || !isJsType(jsType)) {
    return false
  }

  const unknownGetterSetterOrjsTypeExpressed = isUnkownGettSetterOrJsTypeExpressed(jsType, propertyName, usageType)

  const isFunctionCall = usageType === 'CallExpression'
  const getterSetterCalledAsFunction = isFunctionCall && isGetSetProp(jsType, propertyName)

  const unknownjsTypeCalledAsFunction = isFunctionCall && !isProtoProp(jsType, propertyName) &&
    !isObjProp(jsType, propertyName)

  return unknownGetterSetterOrjsTypeExpressed || getterSetterCalledAsFunction || unknownjsTypeCalledAsFunction
}

module.exports = {
  meta: {
    type: 'problem'
  },
  create(context) {
    return {
      MemberExpression(node) {
        /* eslint complexity: [2, 9] */
        if (node.computed && node.property.type === 'Identifier') {
          /**
           * handles cases like {}[i][j]
           * not enough information to identify type of variable in computed properties
           * so ignore false positives by not performing any checks
           */

          return
        }

        const isArgToParent = node.parent.arguments && node.parent.arguments.indexOf(node) > -1
        const usageType = isArgToParent ? node.type : node.parent.type

        const {propertyName, jsType} = getJsTypeAndPropertyName(node)

        if (isInvalid(jsType, propertyName, usageType) && isInvalid('Function', propertyName, usageType)) {
          context.report(node, 'Avoid using extended native objects')
        }
      }
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

/**
 */
angular.module('openolitor-admin')
  .controller('RechnungsPositionenOverviewCreateRechnungenController', ['$scope', '$filter', '$routeParams',
    '$location', '$route', '$uibModal', '$log', '$http', 'gettext',
    'moment', 'EnumUtil', 'DataUtil', 'msgBus', '$q', 'lodash',
    'API_URL', 'alertService', 'AbosOverviewService',

    function($scope, $filter, $routeParams, $location, $route, $uibModal,
      $log, $http, gettext,
      moment, EnumUtil, DataUtil, msgBus, $q, lodash, API_URL,
      alertService, AbosOverviewService) {

      // rechnungen object with defaults and without ids
      $scope.rechnungen = {
        titel: '',
        rechnungsDatum: new Date(),
        faelligkeitsDatum: new Date(moment().add(1, 'month').subtract(1, 'day').valueOf())
      };

      $scope.getRechnungen = function() {
        $scope.rechnungen.ids = _.map(_.filter($scope.rechnungsPositionen, ['status', 'Offen']), 'id');
        return $scope.rechnungen;
      };

      $scope.form = {
        mode: 'AnzahlLieferungen',
        manuellerBetrag: false
      };

      $scope.commandIssued = false;

      $scope.open = {
        start: false
      };

      $scope.openCalendar = function(e, date) {
        e.preventDefault();
        e.stopPropagation();

        $scope.open[date] = true;
      };

      $scope.batchCreate = function() {
        $http.post(API_URL + 'rechnungspositionen/aktionen/createrechnungen', $scope.getRechnungen()).then(function() {
          $scope.commandIssued = true;
        });
      };

      $scope.jumpToRechnungen = function() {
        $location.path('/rechnungen').search('q', 'id=' + $scope.batchCreated.rechnungsIds.join());
      };

      $scope.batchCreated = {
        ids: [],
        rechnungsIds: [],
        rechnungsPositionenInWrongState: []
      };

      $scope.numberOfOpenRechnungPositionen = function(rechnungPositionenIds){
          var result = 0;
          lodash.forEach(rechnungPositionenIds, function(rechnungPosition){
              if (rechnungPosition.status === 'Offen'){
                  result++;
              }
          });
          return result;
      }

      msgBus.onMsg('EntityModified', $scope, function(event, msg) {
        console.log('Mod: ', msg);
        if (msg.entity === 'RechnungsPosition') {
          console.log('RP', msg);
          console.log('$scope.rechnungen.ids', $scope.rechnungen.ids);
          console.log('msg.data.id', msg.data.id);
          if (_.includes($scope.rechnungen.ids, msg.data.id)) {
            console.log('includes', msg.data.id);
            $scope.batchCreated.ids.push(msg.data.id);
            if (!_.includes($scope.batchCreated.rechnungsIds, msg.data.rechnungId)) {
              $scope.batchCreated.rechnungsIds.push(msg.data.rechnungId);
            }
            $scope.$apply();
          }
        }
      });
    }
  ]);
<commit_msg>Update rechnungspositionenoverviewcreaterechnungen.controller.js<commit_after>'use strict';

/**
 */
angular.module('openolitor-admin')
  .controller('RechnungsPositionenOverviewCreateRechnungenController', ['$scope', '$filter', '$routeParams',
    '$location', '$route', '$uibModal', '$log', '$http', 'gettext',
    'moment', 'EnumUtil', 'DataUtil', 'msgBus', '$q', 'lodash',
    'API_URL', 'alertService', 'AbosOverviewService',

    function($scope, $filter, $routeParams, $location, $route, $uibModal,
      $log, $http, gettext,
      moment, EnumUtil, DataUtil, msgBus, $q, lodash, API_URL,
      alertService, AbosOverviewService) {

      // rechnungen object with defaults and without ids
      $scope.rechnungen = {
        titel: '',
        rechnungsDatum: new Date(),
        faelligkeitsDatum: new Date(moment().add(1, 'month').subtract(1, 'day').valueOf())
      };

      $scope.getRechnungen = function() {
        $scope.rechnungen.ids = _.map(_.filter($scope.rechnungsPositionen, ['status', 'Offen']), 'id');
        return $scope.rechnungen;
      };

      $scope.form = {
        mode: 'AnzahlLieferungen',
        manuellerBetrag: false
      };

      $scope.commandIssued = false;

      $scope.open = {
        start: false
      };

      $scope.openCalendar = function(e, date) {
        e.preventDefault();
        e.stopPropagation();

        $scope.open[date] = true;
      };

      $scope.batchCreate = function() {
        $http.post(API_URL + 'rechnungspositionen/aktionen/createrechnungen', $scope.getRechnungen()).then(function() {
          $scope.commandIssued = true;
        });
      };

      $scope.jumpToRechnungen = function() {
        $location.path('/rechnungen').search('q', 'id=' + $scope.batchCreated.rechnungsIds.join());
      };

      $scope.batchCreated = {
        ids: [],
        rechnungsIds: [],
        rechnungsPositionenInWrongState: []
      };

      $scope.numberOfOpenRechnungPositionen = function(rechnungPositionenList){
          var result = 0;
          lodash.forEach(rechnungPositionenList, function(rechnungPosition){
              if (rechnungPosition.status === 'Offen'){
                  result++;
              }
          });
          return result;
      }

      msgBus.onMsg('EntityModified', $scope, function(event, msg) {
        console.log('Mod: ', msg);
        if (msg.entity === 'RechnungsPosition') {
          console.log('RP', msg);
          console.log('$scope.rechnungen.ids', $scope.rechnungen.ids);
          console.log('msg.data.id', msg.data.id);
          if (_.includes($scope.rechnungen.ids, msg.data.id)) {
            console.log('includes', msg.data.id);
            $scope.batchCreated.ids.push(msg.data.id);
            if (!_.includes($scope.batchCreated.rechnungsIds, msg.data.rechnungId)) {
              $scope.batchCreated.rechnungsIds.push(msg.data.rechnungId);
            }
            $scope.$apply();
          }
        }
      });
    }
  ]);
<|endoftext|>


<commit_before>var Delegator = require('dom-delegator')

module.exports = BaseEvent

function BaseEvent(lambda) {
    return EventHandler;

    function EventHandler(fn, data, opts) {
        var handler = {
            fn: fn,
            data: data,
            opts: opts || {},
            handleEvent: handleEvent
        }

        if (fn && fn.type === 'dom-delegator-handle') {
            return Delegator().transformHandle(fn,
                handleLambda.bind(handler))
        }

        return handler;
    }

    function handleLambda(ev) {
        return lambda.call(this, ev)
    }

    function handleEvent(ev) {
        var value = lambda.call(this, ev)
        if (!value) {
            return
        }

        if (typeof this.fn === 'function') {
            this.fn(value)
        } else {
            this.fn.write(value)
        }
    }
}
<commit_msg>default data to object<commit_after>var Delegator = require('dom-delegator')

module.exports = BaseEvent

function BaseEvent(lambda) {
    return EventHandler;

    function EventHandler(fn, data, opts) {
        var handler = {
            fn: fn,
            data: data || {},
            opts: opts || {},
            handleEvent: handleEvent
        }

        if (fn && fn.type === 'dom-delegator-handle') {
            return Delegator().transformHandle(fn,
                handleLambda.bind(handler))
        }

        return handler;
    }

    function handleLambda(ev) {
        return lambda.call(this, ev)
    }

    function handleEvent(ev) {
        var value = lambda.call(this, ev)
        if (!value) {
            return
        }

        if (typeof this.fn === 'function') {
            this.fn(value)
        } else {
            this.fn.write(value)
        }
    }
}
<|endoftext|>


<commit_before>
'use strict';

/**
 * Module dependencies.
 */

const debug = require('debug')('koa:application');
const Emitter = require('events').EventEmitter;
const compose_es7 = require('composition');
const onFinished = require('on-finished');
const response = require('./response');
const compose = require('koa-compose');
const isJSON = require('koa-is-json');
const context = require('./context');
const request = require('./request');
const statuses = require('statuses');
const Cookies = require('cookies');
const accepts = require('accepts');
const assert = require('assert');
const Stream = require('stream');
const http = require('http');
const only = require('only');
const co = require('co');

/**
 * Expose `Application` class.
 * Inherits from `Emitter.prototype`.
 */

module.exports = class Application extends Emitter {

  /**
   * Initialize a new `Application`.
   *
   * @api public
   */

  constructor() {
    super();

    if (!(this instanceof Application)) return new Application;
    this.env = process.env.NODE_ENV || 'development';
    this.subdomainOffset = 2;
    this.middleware = [];
    this.context = Object.create(context);
    this.request = Object.create(request);
    this.response = Object.create(response);
  }

  /**
   * Shorthand for:
   *
   *    http.createServer(app.callback()).listen(...)
   *
   * @param {Mixed} ...
   * @return {Server}
   * @api public
   */

  listen() {
    debug('listen');
    const server = http.createServer(this.callback());
    return server.listen.apply(server, arguments);
  }

  /**
   * Return JSON representation.
   * We only bother showing settings.
   *
   * @return {Object}
   * @api public
   */

  toJSON() {
    return only(this, [
      'subdomainOffset',
      'env'
    ]);
  }

  inspect() {
    return this.toJSON();
  }

  /**
   * Use the given middleware `fn`.
   *
   * @param {GeneratorFunction} fn
   * @return {Application} self
   * @api public
   */

  use(fn) {
    if (!this.experimental) {
      // es7 async functions are allowed
      assert(fn && 'GeneratorFunction' == fn.constructor.name, 'app.use() requires a generator function');
    }
    debug('use %s', fn._name || fn.name || '-');
    this.middleware.push(fn);
    return this;
  }

  /**
   * Return a request handler callback
   * for node's native http server.
   *
   * @return {Function}
   * @api public
   */

  callback() {
    const fn = this.experimental
      ? compose_es7(this.middleware)
      : co.wrap(compose(this.middleware));

    if (!this.listeners('error').length) this.on('error', this.onerror);

    return (req, res) => {
      res.statusCode = 404;
      const ctx = this.createContext(req, res);
      onFinished(res, ctx.onerror);
      fn.call(ctx).then(function () {
        respond.call(ctx);
      }).catch(ctx.onerror);
    }
  }

  /**
   * Initialize a new context.
   *
   * @api private
   */

  createContext(req, res) {
    const context = Object.create(this.context);
    const request = context.request = Object.create(this.request);
    const response = context.response = Object.create(this.response);
    context.app = request.app = response.app = this;
    context.req = request.req = response.req = req;
    context.res = request.res = response.res = res;
    request.ctx = response.ctx = context;
    request.response = response;
    response.request = request;
    context.onerror = context.onerror.bind(context);
    context.originalUrl = request.originalUrl = req.url;
    context.cookies = new Cookies(req, res, this.keys);
    context.accept = request.accept = accepts(req);
    context.state = {};
    return context;
  }

  /**
   * Default error handler.
   *
   * @param {Error} err
   * @api private
   */

  onerror(err) {
    assert(err instanceof Error, `non-error thrown: ${err}`);

    if (404 == err.status || err.expose) return;
    if (this.silent) return;
    // DEPRECATE env-specific logging in v2
    if ('test' == this.env) return;

    const msg = err.stack || err.toString();
    console.error();
    console.error(msg.replace(/^/gm, '  '));
    console.error();
  }

}

/**
 * Response helper.
 */

function respond() {
  // allow bypassing koa
  if (false === this.respond) return;

  const res = this.res;
  if (res.headersSent || !this.writable) return;

  var body = this.body;
  const code = this.status;

  // ignore body
  if (statuses.empty[code]) {
    // strip headers
    this.body = null;
    return res.end();
  }

  if ('HEAD' == this.method) {
    if (isJSON(body)) this.length = Buffer.byteLength(JSON.stringify(body));
    return res.end();
  }

  // status body
  if (null == body) {
    this.type = 'text';
    body = this.message || String(code);
    this.length = Buffer.byteLength(body);
    return res.end(body);
  }

  // responses
  if (Buffer.isBuffer(body)) return res.end(body);
  if ('string' == typeof body) return res.end(body);
  if (body instanceof Stream) return body.pipe(res);

  // body: json
  body = JSON.stringify(body);
  this.length = Buffer.byteLength(body);
  res.end(body);
}
<commit_msg>get rid of instanceof hack in application constructor<commit_after>
'use strict';

/**
 * Module dependencies.
 */

const debug = require('debug')('koa:application');
const Emitter = require('events').EventEmitter;
const compose_es7 = require('composition');
const onFinished = require('on-finished');
const response = require('./response');
const compose = require('koa-compose');
const isJSON = require('koa-is-json');
const context = require('./context');
const request = require('./request');
const statuses = require('statuses');
const Cookies = require('cookies');
const accepts = require('accepts');
const assert = require('assert');
const Stream = require('stream');
const http = require('http');
const only = require('only');
const co = require('co');

/**
 * Expose `Application` class.
 * Inherits from `Emitter.prototype`.
 */

module.exports = class Application extends Emitter {

  /**
   * Initialize a new `Application`.
   *
   * @api public
   */

  constructor() {
    super();

    this.env = process.env.NODE_ENV || 'development';
    this.subdomainOffset = 2;
    this.middleware = [];
    this.context = Object.create(context);
    this.request = Object.create(request);
    this.response = Object.create(response);
  }

  /**
   * Shorthand for:
   *
   *    http.createServer(app.callback()).listen(...)
   *
   * @param {Mixed} ...
   * @return {Server}
   * @api public
   */

  listen() {
    debug('listen');
    const server = http.createServer(this.callback());
    return server.listen.apply(server, arguments);
  }

  /**
   * Return JSON representation.
   * We only bother showing settings.
   *
   * @return {Object}
   * @api public
   */

  toJSON() {
    return only(this, [
      'subdomainOffset',
      'env'
    ]);
  }

  inspect() {
    return this.toJSON();
  }

  /**
   * Use the given middleware `fn`.
   *
   * @param {GeneratorFunction} fn
   * @return {Application} self
   * @api public
   */

  use(fn) {
    if (!this.experimental) {
      // es7 async functions are allowed
      assert(fn && 'GeneratorFunction' == fn.constructor.name, 'app.use() requires a generator function');
    }
    debug('use %s', fn._name || fn.name || '-');
    this.middleware.push(fn);
    return this;
  }

  /**
   * Return a request handler callback
   * for node's native http server.
   *
   * @return {Function}
   * @api public
   */

  callback() {
    const fn = this.experimental
      ? compose_es7(this.middleware)
      : co.wrap(compose(this.middleware));

    if (!this.listeners('error').length) this.on('error', this.onerror);

    return (req, res) => {
      res.statusCode = 404;
      const ctx = this.createContext(req, res);
      onFinished(res, ctx.onerror);
      fn.call(ctx).then(function () {
        respond.call(ctx);
      }).catch(ctx.onerror);
    }
  }

  /**
   * Initialize a new context.
   *
   * @api private
   */

  createContext(req, res) {
    const context = Object.create(this.context);
    const request = context.request = Object.create(this.request);
    const response = context.response = Object.create(this.response);
    context.app = request.app = response.app = this;
    context.req = request.req = response.req = req;
    context.res = request.res = response.res = res;
    request.ctx = response.ctx = context;
    request.response = response;
    response.request = request;
    context.onerror = context.onerror.bind(context);
    context.originalUrl = request.originalUrl = req.url;
    context.cookies = new Cookies(req, res, this.keys);
    context.accept = request.accept = accepts(req);
    context.state = {};
    return context;
  }

  /**
   * Default error handler.
   *
   * @param {Error} err
   * @api private
   */

  onerror(err) {
    assert(err instanceof Error, `non-error thrown: ${err}`);

    if (404 == err.status || err.expose) return;
    if (this.silent) return;
    // DEPRECATE env-specific logging in v2
    if ('test' == this.env) return;

    const msg = err.stack || err.toString();
    console.error();
    console.error(msg.replace(/^/gm, '  '));
    console.error();
  }

}

/**
 * Response helper.
 */

function respond() {
  // allow bypassing koa
  if (false === this.respond) return;

  const res = this.res;
  if (res.headersSent || !this.writable) return;

  var body = this.body;
  const code = this.status;

  // ignore body
  if (statuses.empty[code]) {
    // strip headers
    this.body = null;
    return res.end();
  }

  if ('HEAD' == this.method) {
    if (isJSON(body)) this.length = Buffer.byteLength(JSON.stringify(body));
    return res.end();
  }

  // status body
  if (null == body) {
    this.type = 'text';
    body = this.message || String(code);
    this.length = Buffer.byteLength(body);
    return res.end(body);
  }

  // responses
  if (Buffer.isBuffer(body)) return res.end(body);
  if ('string' == typeof body) return res.end(body);
  if (body instanceof Stream) return body.pipe(res);

  // body: json
  body = JSON.stringify(body);
  this.length = Buffer.byteLength(body);
  res.end(body);
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { defaultProps, propTypes } from './props';
import { keysHandler } from './handler';
import { BINDER_TYPE } from '../../constants';
import { addListener, removeListener } from '../../listener';
import { addBinder, _removeBinder } from '../../redux/actions';
import compatibility from '../compatibility';
import { refreshState, mountState } from './refresh';

class Binder extends Component {
  uniqElement = true;

  constructor(props) {
    super(props);
    this.innerProps = compatibility(props);
    this.state = { mounted: false };
  }

  componentWillMount() {
    this.listenerId = addListener(keysHandler, this);
    addBinder(this.innerProps, BINDER_TYPE);
  }

  componentWillReceiveProps(nextProps) {
    this.innerProps = compatibility(nextProps);
  }

  componentDidMount() {
    this.setState({ mounted: true });
    setTimeout(() => {
      this.state.mounted && mountState.apply(this);
    }, 0);
  }

  componentDidUpdate() {
    refreshState.apply(this);
  }

  componentWillUnmount() {
    this.setState({ mounted: false });
    this.listenerId = removeListener(this.listenerId);
    _removeBinder(this.innerProps.id);
  }

  render() {
    const { id, children } = this.innerProps;
    return
{children}
;
  }
}

Binder.propTypes = propTypes;
Binder.defaultProps = defaultProps;

export default Binder;
<commit_msg>fix race condition triggering invariant violation. fixes #98<commit_after>import React, { Component } from 'react';
import { defaultProps, propTypes } from './props';
import { keysHandler } from './handler';
import { BINDER_TYPE } from '../../constants';
import { addListener, removeListener } from '../../listener';
import { addBinder, _removeBinder } from '../../redux/actions';
import compatibility from '../compatibility';
import { refreshState, mountState } from './refresh';

class Binder extends Component {
  uniqElement = true;

  constructor(props) {
    super(props);
    this.innerProps = compatibility(props);
    this.mounted = false;
  }

  componentWillMount() {
    this.listenerId = addListener(keysHandler, this);
    addBinder(this.innerProps, BINDER_TYPE);
  }

  componentWillReceiveProps(nextProps) {
    this.innerProps = compatibility(nextProps);
  }

  componentDidMount() {
    this.mounted = true;
    setTimeout(() => {
      this.mounted && mountState.apply(this);
    }, 0);
  }

  componentDidUpdate() {
    refreshState.apply(this);
  }

  componentWillUnmount() {
    this.mounted = false;
    this.listenerId = removeListener(this.listenerId);
    _removeBinder(this.innerProps.id);
  }

  render() {
    const { id, children } = this.innerProps;
    return
{children}
;
  }
}

Binder.propTypes = propTypes;
Binder.defaultProps = defaultProps;

export default Binder;
<|endoftext|>


<commit_before>import { _ } from 'meteor/underscore';
import { Meteor } from 'meteor/meteor';
import SimpleSchema from 'simpl-schema';
import { diff } from 'rus-diff';
import './security.js';

function extend(reciever, provider) {
    for(var prop in provider){
        if(provider.hasOwnProperty(prop)){
            reciever[prop] = provider[prop];
        }
    }
}

export class BaseModel {
    constructor(document, preClean){
        document = document || {};
        delete document._document;
        if(preClean){
            document = this._getSchema().clean(document);
        }
        extend(this, document);
        this._document = document;
    }

    static createEmpty(_id) {
        return new this({_id:_id});
    }

    static methods(methodMap) {
        var self = this;
        if(_.isObject(methodMap)){
            _.each(methodMap, function(method, name){
                if(_.isFunction(method)){
                    if(!self.prototype[name]){
                        self.prototype[name] = method;
                    }else{
                        throw new Meteor.Error("existent-method", "The method "+name+" already exists.");
                    }
                }
            });
        }
    };

    static updateTransformFunction() {
        this.prototype.getCollection()._transform = (document) => {
            return new this(document);
        };
    }

    static attachCollection(collection, transform = true) {
        this.prototype.getCollection = function() {
            return collection;
        };

        Meteor[collection._name] = collection;

        if(transform){
            this.updateTransformFunction();
        }

    }

    static appendSchema(schemaObject) {
        var schema = new SimpleSchema(schemaObject);
        var collection = this.prototype.getCollection();

        if(collection){
            collection.attachSchema(schema);
        }else{
            throw new Error("Can't append schema to non existent collection. Please use extendAndSetupCollection() to create your models");
        }
    }

    _getSchema() {
        var schema = Meteor._get(this.getCollection(), "_c2", "_simpleSchema");
        if(schema){
            return schema;
        }else{
            throw new Meteor.Error("noSchema", "You don't have a schema defined for " + this.getCollectionName());
        }

    }

    getCollection() {
        //We just throw here. This method is reassigned in attachCollection method when collection is attached.
        throw new Meteor.Error("noCollection", "You must use ClassName.attachCollection to attach a collection to your model.");
    }

    getCollectionName() {
        return this.getCollection()._name;
    }

    // get all values from the model that do not have a denyUpdate or denyUntrusted in their schema
    getUpdatableFields() {
        const schema = this._getSchema()._schema;
        const fields = {_id: this._id};

        for(let key of Object.keys(this)){
            if (schema[key] && !(schema[key].custom && schema[key].custom === SimpleSchema.denyUntrusted) && !schema[key].denyUpdate){
                fields[key] = this[key];
            }
        }

        return fields;
    }

    checkOwnership() {
        return this.userId === Meteor.userId();
    }

    save(callback) {
        const schema = this._getSchema();

        let obj = Object.keys(this).filter(
            (key) => key !== "_document").reduce(
                (accumulator, key) => {
                  accumulator[key] = this[key];
                  return accumulator;
                }, {}
            );

        if(this._id){
            let updateDiff = diff(this._document, obj);
            if(!_.isEmpty(updateDiff)){
                this.update(updateDiff, callback);
            } else {
                callback && callback(null);
            }
        }else{
            if(Meteor.isClient && schema){
                obj = schema.clean(obj);
            }
            this._id = this.getCollection().insert(obj, callback);
        }

        return this;
    }

    update(modifier, callback) {
        if(this._id){
            this.getCollection().update(this._id, modifier, callback);
        }
    }

    _setProps(key, value, validationPathOnly) {
        var current;
        var level = this;
        var steps = key.split(".");
        var last = steps.pop();
        var set = {};
        var currentSet = set;

        while(current = steps.shift()){
            if(!validationPathOnly){
                if(level[current]){
                    if(!_.isObject(level[current])){
                        throw new Meteor.Error("PropertyNotObject", current + " of " + key + " is not an object");
                    }
                }else{
                    level[current] = {};
                }

                level = level[current];
            }
            currentSet = currentSet[current] = {};
        }

        if(!validationPathOnly) { level[last] = value; }

        currentSet[last] = value;

        return set;
    }

    _updateLocal(modifier) {
        this.getCollection()._collection.update(this._id, modifier);
    }

    set(key, value) {
        var context = this._getSchema().newContext();
        var obj = {};

        obj.$set = this._setProps(key, value, true);

        if(context.validate(obj, {modifier:true})){
            obj.$set = this._setProps(key, value);
            this[key] = value;

            if(Meteor.isClient){
                this._id && this._updateLocal(obj);
            }
        }else{
            throw new Meteor.Error(context.keyErrorMessage(key));
        }
        return this;
    }

    remove(callback) {
        if(this._id){
            this.getCollection().remove({_id:this._id}, callback);
        }
    }

}
<commit_msg>update error message<commit_after>import { _ } from 'meteor/underscore';
import { Meteor } from 'meteor/meteor';
import SimpleSchema from 'simpl-schema';
import { diff } from 'rus-diff';
import './security.js';

function extend(reciever, provider) {
    for(var prop in provider){
        if(provider.hasOwnProperty(prop)){
            reciever[prop] = provider[prop];
        }
    }
}

export class BaseModel {
    constructor(document, preClean){
        document = document || {};
        delete document._document;
        if(preClean){
            document = this._getSchema().clean(document);
        }
        extend(this, document);
        this._document = document;
    }

    static createEmpty(_id) {
        return new this({_id:_id});
    }

    static methods(methodMap) {
        var self = this;
        if(_.isObject(methodMap)){
            _.each(methodMap, function(method, name){
                if(_.isFunction(method)){
                    if(!self.prototype[name]){
                        self.prototype[name] = method;
                    }else{
                        throw new Meteor.Error("existent-method", "The method "+name+" already exists.");
                    }
                }
            });
        }
    };

    static updateTransformFunction() {
        this.prototype.getCollection()._transform = (document) => {
            return new this(document);
        };
    }

    static attachCollection(collection, transform = true) {
        this.prototype.getCollection = function() {
            return collection;
        };

        Meteor[collection._name] = collection;

        if(transform){
            this.updateTransformFunction();
        }

    }

    static appendSchema(schemaObject) {
        var schema = new SimpleSchema(schemaObject);
        var collection = this.prototype.getCollection();

        if(collection){
            collection.attachSchema(schema);
        }else{
            throw new Meteor.Error("Can't append schema to non existent collection. Please attach a collection to your model using `ModelName.attachCollection`");
        }
    }

    _getSchema() {
        var schema = Meteor._get(this.getCollection(), "_c2", "_simpleSchema");
        if(schema){
            return schema;
        }else{
            throw new Meteor.Error("noSchema", "You don't have a schema defined for " + this.getCollectionName());
        }

    }

    getCollection() {
        //We just throw here. This method is reassigned in attachCollection method when collection is attached.
        throw new Meteor.Error("noCollection", "You must use ClassName.attachCollection to attach a collection to your model.");
    }

    getCollectionName() {
        return this.getCollection()._name;
    }

    // get all values from the model that do not have a denyUpdate or denyUntrusted in their schema
    getUpdatableFields() {
        const schema = this._getSchema()._schema;
        const fields = {_id: this._id};

        for(let key of Object.keys(this)){
            if (schema[key] && !(schema[key].custom && schema[key].custom === SimpleSchema.denyUntrusted) && !schema[key].denyUpdate){
                fields[key] = this[key];
            }
        }

        return fields;
    }

    checkOwnership() {
        return this.userId === Meteor.userId();
    }

    save(callback) {
        const schema = this._getSchema();

        let obj = Object.keys(this).filter(
            (key) => key !== "_document").reduce(
                (accumulator, key) => {
                  accumulator[key] = this[key];
                  return accumulator;
                }, {}
            );

        if(this._id){
            let updateDiff = diff(this._document, obj);
            if(!_.isEmpty(updateDiff)){
                this.update(updateDiff, callback);
            } else {
                callback && callback(null);
            }
        }else{
            if(Meteor.isClient && schema){
                obj = schema.clean(obj);
            }
            this._id = this.getCollection().insert(obj, callback);
        }

        return this;
    }

    update(modifier, callback) {
        if(this._id){
            this.getCollection().update(this._id, modifier, callback);
        }
    }

    _setProps(key, value, validationPathOnly) {
        var current;
        var level = this;
        var steps = key.split(".");
        var last = steps.pop();
        var set = {};
        var currentSet = set;

        while(current = steps.shift()){
            if(!validationPathOnly){
                if(level[current]){
                    if(!_.isObject(level[current])){
                        throw new Meteor.Error("PropertyNotObject", current + " of " + key + " is not an object");
                    }
                }else{
                    level[current] = {};
                }

                level = level[current];
            }
            currentSet = currentSet[current] = {};
        }

        if(!validationPathOnly) { level[last] = value; }

        currentSet[last] = value;

        return set;
    }

    _updateLocal(modifier) {
        this.getCollection()._collection.update(this._id, modifier);
    }

    set(key, value) {
        var context = this._getSchema().newContext();
        var obj = {};

        obj.$set = this._setProps(key, value, true);

        if(context.validate(obj, {modifier:true})){
            obj.$set = this._setProps(key, value);
            this[key] = value;

            if(Meteor.isClient){
                this._id && this._updateLocal(obj);
            }
        }else{
            throw new Meteor.Error(context.keyErrorMessage(key));
        }
        return this;
    }

    remove(callback) {
        if(this._id){
            this.getCollection().remove({_id:this._id}, callback);
        }
    }

}
<|endoftext|>


<commit_before>/**
* https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140549&token=&lang=zh_CN
* 管理消息
*/

const massUrlPrefix = "https://api.weixin.qq.com/cgi-bin/message/mass/"

/**
* https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140549&token=&lang=zh_CN
*
*/

/**
* 图文消息
*/
function newsToTag(mediaId,tagId) {
		return _mediaToTag("mpnews",mediaId,tagId)
}

/**
* 音频消息
*/
function voiceToTag(mediaId,tagId) {
	return _mediaToTag("voic",mediaId,tagId)
}

/**
* 图片消息
*/
function imageToTag(mediaId,tagId) {
	return _mediaToTag("image",mediaId,tagId)
}

/**
* 视频消息
*/
function videoToTag(mediaId,tagId) {
	return _mediaToTag("mpvideo",mediaId,tagId)
}

/**
* 文本消息
*/
function textToTag(content,tagId) {
	const msg = {
		'type':'text',
		'content':{"content":content}
	}
	return _msgToTag(msg,tagId)
}

/**
* 卡券消息
*/
function cardToTag(cardId,tagId) {
	const msg = {
		'type':'wxcard',
		'content':{"card_id":cardId}
	}
	return _msgToTag(msg,tagId)
}

function _mediaToTag(type,mediaId,tagId) {
	const msg = {
		'type':type,
		'content': {"media_id":mediaId}
		},
	}
	return _msgToTag(msg,tagId)
}

function _msgToTag(msg,tagId) {
	let filter = {"is_to_all":true}
	if(tagId) {
		filter = { "is_to_all":false,"tag_id":tagId }
	}
	let body = {
		"filter":filter,
		"msgtype":msg.type
	}
	body[msg.type] = msg.content
	return {
		"url":`${massUrlPrefix}sendall`,
		"method" : "post",
		"body": body
	}
}

/**
* 图文消息
*/
function newsToUsers(mediaId,users) {
		return _mediaToUsers("mpnews",mediaId,users)
}

/**
* 音频消息
*/
function voiceToUsers(mediaId,users) {
	return _mediaToUsers("voic",mediaId,users)
}

/**
* 图片消息
*/
function imageToUsers(mediaId,users) {
	return _mediaToUsers("image",mediaId,users)
}

/**
* 视频消息
*/
function videoToUsers(mediaId,users) {
	return _mediaToUsers("mpvideo",mediaId,users)
}

/**
* 文本消息
*/
function textToUsers(content,users) {
	const msg = {
		'type':'text',
		'content':{"content":content}
	}
	return _msgToUsers(msg,users)
}

/**
* 卡券消息
*/
function cardToUsers(cardId,users) {
	const msg = {
		'type':'wxcard',
		'content':{"card_id":cardId}
	}
	return _msgToUsers(msg,users)
}

function _mediaToUsers(type,mediaId,users) {
	const msg = {
		'type':type,
		'content': {"media_id":mediaId}
		},
	}
	return _msgToUsers(msg,users)
}

function _msgToUsers(msg,users) {
	let body = {
		"touser":users,
		"msgtype":msg.type
	}
	body[msg.type] = msg.content
	return {
		"url":`${massUrlPrefix}sendall`,
		"method" : "post",
		"body": body
	}
}

export default {
	newsToTag,voiceToTag,imageToTag,videoToTag,cardToTag,textToTag,
	newsToUsers,voiceToUsers,imageToUsers,videoToUsers,cardToUsers,textToUsers,
}
<commit_msg>remove a }<commit_after>/**
* https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140549&token=&lang=zh_CN
* 管理消息
*/

const massUrlPrefix = "https://api.weixin.qq.com/cgi-bin/message/mass/"

/**
* https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140549&token=&lang=zh_CN
*
*/

/**
* 图文消息
*/
function newsToTag(mediaId,tagId) {
		return _mediaToTag("mpnews",mediaId,tagId)
}

/**
* 音频消息
*/
function voiceToTag(mediaId,tagId) {
	return _mediaToTag("voic",mediaId,tagId)
}

/**
* 图片消息
*/
function imageToTag(mediaId,tagId) {
	return _mediaToTag("image",mediaId,tagId)
}

/**
* 视频消息
*/
function videoToTag(mediaId,tagId) {
	return _mediaToTag("mpvideo",mediaId,tagId)
}

/**
* 文本消息
*/
function textToTag(content,tagId) {
	const msg = {
		'type':'text',
		'content':{"content":content}
	}
	return _msgToTag(msg,tagId)
}

/**
* 卡券消息
*/
function cardToTag(cardId,tagId) {
	const msg = {
		'type':'wxcard',
		'content':{"card_id":cardId}
	}
	return _msgToTag(msg,tagId)
}

function _mediaToTag(type,mediaId,tagId) {
	const msg = {
		'type':type,
		'content': {"media_id":mediaId}
	}
	return _msgToTag(msg,tagId)
}

function _msgToTag(msg,tagId) {
	let filter = {"is_to_all":true}
	if(tagId) {
		filter = { "is_to_all":false,"tag_id":tagId }
	}
	let body = {
		"filter":filter,
		"msgtype":msg.type
	}
	body[msg.type] = msg.content
	return {
		"url":`${massUrlPrefix}sendall`,
		"method" : "post",
		"body": body
	}
}

/**
* 图文消息
*/
function newsToUsers(mediaId,users) {
		return _mediaToUsers("mpnews",mediaId,users)
}

/**
* 音频消息
*/
function voiceToUsers(mediaId,users) {
	return _mediaToUsers("voic",mediaId,users)
}

/**
* 图片消息
*/
function imageToUsers(mediaId,users) {
	return _mediaToUsers("image",mediaId,users)
}

/**
* 视频消息
*/
function videoToUsers(mediaId,users) {
	return _mediaToUsers("mpvideo",mediaId,users)
}

/**
* 文本消息
*/
function textToUsers(content,users) {
	const msg = {
		'type':'text',
		'content':{"content":content}
	}
	return _msgToUsers(msg,users)
}

/**
* 卡券消息
*/
function cardToUsers(cardId,users) {
	const msg = {
		'type':'wxcard',
		'content':{"card_id":cardId}
	}
	return _msgToUsers(msg,users)
}

function _mediaToUsers(type,mediaId,users) {
	const msg = {
		'type':type,
		'content': {"media_id":mediaId}
		},
	}
	return _msgToUsers(msg,users)
}

function _msgToUsers(msg,users) {
	let body = {
		"touser":users,
		"msgtype":msg.type
	}
	body[msg.type] = msg.content
	return {
		"url":`${massUrlPrefix}sendall`,
		"method" : "post",
		"body": body
	}
}

export default {
	newsToTag,voiceToTag,imageToTag,videoToTag,cardToTag,textToTag,
	newsToUsers,voiceToUsers,imageToUsers,videoToUsers,cardToUsers,textToUsers,
}
<|endoftext|>


<commit_before>'use strict'
// GLOBAL VARIABLES
var times = ['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm'];
var salesTable = document.getElementById('cookieShops');
var myStores = [];
var clearSalesForm = document.getElementById('clearForm');

// CONSTRUCTOR
var Store = function(location, minCustomers, maxCustomers, avgCookiesPerSale){
  this.location = location;
  this.minCustomers = minCustomers;
  this.maxCustomers = maxCustomers;
  this.avgCookiesPerSale = avgCookiesPerSale;
  this.customersPerHour = [];
  this.calcCustomersPerHour = function(){
    for(var i = 0; i < times.length; i++){
      this.customersPerHour.push(Math.floor(Math.random() * (this.maxCustomers - this.minCustomers + 1)) + this.minCustomers)
    }
  };
  this.cookiesSoldEachHour = [];
  this.calcCookiesSoldEachHour = function(){
  this.calcCustomersPerHour();
    for(var i = 0; i < times.length; i++){
      this.cookiesSoldEachHour.push(Math.ceil(this.customersPerHour[i] * this.avgCookiesPerSale));
      this.totalCookiesPerDay += this.cookiesSoldEachHour[i];
    }
  };
  this.totalCookiesPerDay = 0;
  myStores.push(this);
  this.calcCookiesSoldEachHour();
};

Store.prototype.render = function(){
  var trEl = document.createElement('tr');

  var tdEl = document.createElement('td');
  tdEl.textContent = this.location;
  trEl.appendChild(tdEl);

  for(var i = 0; i < times.length; i++){
    tdEl = document.createElement('td');
    tdEl.textContent = this.cookiesSoldEachHour[i];
    trEl.appendChild(tdEl);
  }

  tdEl = document.createElement('td');
  tdEl.textContent = this.totalCookiesPerDay;
  trEl.appendChild(tdEl);

  salesTable.appendChild(trEl);
};

new Store('1st and Pike', 23, 65, 6.3);
new Store('SeaTac', 3, 24, 1.2);
new Store('Seattle Center', 11, 38, 2.3);
new Store('Capitol Hill', 20, 38, 2.3);
new Store('Alki', 2, 16, 4.6);

// FUNCTION DECLARATIONS

function makeHeaderRow(){
  var trEl = document.createElement('tr');

  var thEl = document.createElement('th');
  thEl.textContent = 'location';
  trEl.appendChild(thEl);

  for(var i = 0; i < times.length; i++){
    thEl = document.createElement('th');
    thEl.textContent = times[i];
    trEl.appendChild(thEl);
  };

  thEl = document.createElement('th');
  thEl.textContent = 'Daily Location Totals';
  trEl.appendChild(thEl);

  salesTable.appendChild(trEl);
}

function allCookies(){
  for(var i = 0; i < myStores.length; i++){
    myStores[i].render();
  }
};

// function renderMyStores(){
//   cookieShops.innerHTML = '';
//   makeHeaderRow();
//   for(var i = 0; i < myStores.length; i++) {
//     myStores[i].render();
//   }
//   // makeHeaderRow();
//   // allCookies();
// };

function handleStoreSubmit(event) {
  console.log(event.target.newLocation.value);
  event.preventDefault();
  if(!event.target.newLocation.value || !event.target.newMinCustomers.value || !event.target.newMaxCustomers.value || !event.target.newAvgCookiesPerSale.value) {
    return alert('All fields for new store must be filled out');
  }

  var location = event.target.newLocation.value;
  var minCustomers = event.target.newMinCustomers.value;
  var maxCustomers = event.target.newMaxCustomers.value;
  var avgCookiesPerSale = event.target.newAvgCookiesPerSale.value;

  var newStore = new Store(location, minCustomers, maxCustomers, avgCookiesPerSale);

  event.target.newLocation.value = null;
  event.target.newMinCustomers.value = null;
  event.target.newMaxCustomers.value = null;
  event.target.newAvgCookiesPerSale.value = null;

  myStores.push(newStore);
  newStore.render();
};

makeHeaderRow();
allCookies();
addStoreForm.addEventListener('submit', handleStoreSubmit);

// clearSalesForm.addEventListener('click', function(){
//
//   alert('You cleared the form');
// });
<commit_msg>removed commented out code that wasnt needed<commit_after>'use strict'
// GLOBAL VARIABLES
var times = ['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm'];
var salesTable = document.getElementById('cookieShops');
var myStores = [];
var clearSalesForm = document.getElementById('clearForm');

// CONSTRUCTOR
var Store = function(location, minCustomers, maxCustomers, avgCookiesPerSale){
  this.location = location;
  this.minCustomers = minCustomers;
  this.maxCustomers = maxCustomers;
  this.avgCookiesPerSale = avgCookiesPerSale;
  this.customersPerHour = [];
  this.calcCustomersPerHour = function(){
    for(var i = 0; i < times.length; i++){
      this.customersPerHour.push(Math.floor(Math.random() * (this.maxCustomers - this.minCustomers + 1)) + this.minCustomers)
    }
  };
  this.cookiesSoldEachHour = [];
  this.calcCookiesSoldEachHour = function(){
  this.calcCustomersPerHour();
    for(var i = 0; i < times.length; i++){
      this.cookiesSoldEachHour.push(Math.ceil(this.customersPerHour[i] * this.avgCookiesPerSale));
      this.totalCookiesPerDay += this.cookiesSoldEachHour[i];
    }
  };
  this.totalCookiesPerDay = 0;
  myStores.push(this);
  this.calcCookiesSoldEachHour();
};

Store.prototype.render = function(){
  var trEl = document.createElement('tr');

  var tdEl = document.createElement('td');
  tdEl.textContent = this.location;
  trEl.appendChild(tdEl);

  for(var i = 0; i < times.length; i++){
    tdEl = document.createElement('td');
    tdEl.textContent = this.cookiesSoldEachHour[i];
    trEl.appendChild(tdEl);
  }

  tdEl = document.createElement('td');
  tdEl.textContent = this.totalCookiesPerDay;
  trEl.appendChild(tdEl);

  salesTable.appendChild(trEl);
};

new Store('1st and Pike', 23, 65, 6.3);
new Store('SeaTac', 3, 24, 1.2);
new Store('Seattle Center', 11, 38, 2.3);
new Store('Capitol Hill', 20, 38, 2.3);
new Store('Alki', 2, 16, 4.6);

// FUNCTION DECLARATIONS

function makeHeaderRow(){
  var trEl = document.createElement('tr');

  var thEl = document.createElement('th');
  thEl.textContent = 'location';
  trEl.appendChild(thEl);

  for(var i = 0; i < times.length; i++){
    thEl = document.createElement('th');
    thEl.textContent = times[i];
    trEl.appendChild(thEl);
  };

  thEl = document.createElement('th');
  thEl.textContent = 'Daily Location Totals';
  trEl.appendChild(thEl);

  salesTable.appendChild(trEl);
}

function allCookies(){
  for(var i = 0; i < myStores.length; i++){
    myStores[i].render();
  }
};

function handleStoreSubmit(event) {
  console.log(event.target.newLocation.value);
  event.preventDefault();
  if(!event.target.newLocation.value || !event.target.newMinCustomers.value || !event.target.newMaxCustomers.value || !event.target.newAvgCookiesPerSale.value) {
    return alert('All fields for new store must be filled out');
  }

  var location = event.target.newLocation.value;
  var minCustomers = event.target.newMinCustomers.value;
  var maxCustomers = event.target.newMaxCustomers.value;
  var avgCookiesPerSale = event.target.newAvgCookiesPerSale.value;

  var newStore = new Store(location, minCustomers, maxCustomers, avgCookiesPerSale);

  event.target.newLocation.value = null;
  event.target.newMinCustomers.value = null;
  event.target.newMaxCustomers.value = null;
  event.target.newAvgCookiesPerSale.value = null;

  myStores.push(newStore);
  newStore.render();
};

makeHeaderRow();
allCookies();
addStoreForm.addEventListener('submit', handleStoreSubmit);
<|endoftext|>