<commit_before>(function(module) {
	"use strict";

	var user = module.parent.require('./user'),
		meta = module.parent.require('./meta'),
		db = module.parent.require('../src/database'),
		passport = module.parent.require('passport'),
		passportFacebook = require('passport-facebook').Strategy,
		fs = module.parent.require('fs'),
		path = module.parent.require('path'),
		nconf = module.parent.require('nconf');

	var constants = Object.freeze({
		'name': "Facebook",
		'admin': {
			'route': '/plugins/sso-facebook',
			'icon': 'fa-facebook-square'
		}
	});

	var Facebook = {};

	Facebook.init = function(app, middleware, controllers, callback) {
		function render(req, res, next) {
			res.render('admin/plugins/sso-facebook', {});
		}

		app.get('/admin/plugins/sso-facebook', middleware.admin.buildHeader, render);
		app.get('/api/admin/plugins/sso-facebook', render);

		callback();
	};

	Facebook.getStrategy = function(strategies, callback) {
		if (meta.config['social:facebook:app_id'] && meta.config['social:facebook:secret']) {
			passport.use(new passportFacebook({
				clientID: meta.config['social:facebook:app_id'],
				clientSecret: meta.config['social:facebook:secret'],
				callbackURL: nconf.get('url') + '/auth/facebook/callback'
			}, function(accessToken, refreshToken, profile, done) {
				Facebook.login(profile.id, profile.displayName, profile.emails[0].value, function(err, user) {
					if (err) {
						return done(err);
					}
					done(null, user);
				});
			}));

			strategies.push({
				name: 'facebook',
				url: '/auth/facebook',
				callbackURL: '/auth/facebook/callback',
				icon: 'facebook',
				scope: 'email'
			});
		}

		callback(null, strategies);
	};

	Facebook.login = function(fbid, name, email, callback) {
		Facebook.getUidByFbid(fbid, function(err, uid) {
			if(err) {
				return callback(err);
			}

			if (uid !== null) {
				// Existing User
				callback(null, {
					uid: uid
				});
			} else {
				// New User
				var success = function(uid) {
					// Save facebook-specific information to the user
					user.setUserField(uid, 'fbid', fbid);
					db.setObjectField('fbid:uid', fbid, uid);
					callback(null, {
						uid: uid
					});
				};

				user.getUidByEmail(email, function(err, uid) {
					if(err) {
						return callback(err);
					}

					if (!uid) {
						user.create({username: name, email: email}, function(err, uid) {
							if(err) {
								return callback(err);
							}

							success(uid);
						});
					} else {
						success(uid); // Existing account -- merge
					}
				});
			}
		});
	};

	Facebook.getUidByFbid = function(fbid, callback) {
		db.getObjectField('fbid:uid', fbid, function(err, uid) {
			if (err) {
				return callback(err);
			}
			callback(null, uid);
		});
	};

	Facebook.addMenuItem = function(custom_header, callback) {
		custom_header.authentication.push({
			"route": constants.admin.route,
			"icon": constants.admin.icon,
			"name": constants.name
		});

		callback(null, custom_header);
	};

	module.exports = Facebook;
}(module));<commit_msg>proper FA icon<commit_after>(function(module) {
	"use strict";

	var user = module.parent.require('./user'),
		meta = module.parent.require('./meta'),
		db = module.parent.require('../src/database'),
		passport = module.parent.require('passport'),
		passportFacebook = require('passport-facebook').Strategy,
		fs = module.parent.require('fs'),
		path = module.parent.require('path'),
		nconf = module.parent.require('nconf');

	var constants = Object.freeze({
		'name': "Facebook",
		'admin': {
			'route': '/plugins/sso-facebook',
			'icon': 'fa-facebook-square'
		}
	});

	var Facebook = {};

	Facebook.init = function(app, middleware, controllers, callback) {
		function render(req, res, next) {
			res.render('admin/plugins/sso-facebook', {});
		}

		app.get('/admin/plugins/sso-facebook', middleware.admin.buildHeader, render);
		app.get('/api/admin/plugins/sso-facebook', render);

		callback();
	};

	Facebook.getStrategy = function(strategies, callback) {
		if (meta.config['social:facebook:app_id'] && meta.config['social:facebook:secret']) {
			passport.use(new passportFacebook({
				clientID: meta.config['social:facebook:app_id'],
				clientSecret: meta.config['social:facebook:secret'],
				callbackURL: nconf.get('url') + '/auth/facebook/callback'
			}, function(accessToken, refreshToken, profile, done) {
				Facebook.login(profile.id, profile.displayName, profile.emails[0].value, function(err, user) {
					if (err) {
						return done(err);
					}
					done(null, user);
				});
			}));

			strategies.push({
				name: 'facebook',
				url: '/auth/facebook',
				callbackURL: '/auth/facebook/callback',
				icon: 'fa-facebook-square',
				scope: 'email'
			});
		}

		callback(null, strategies);
	};

	Facebook.login = function(fbid, name, email, callback) {
		Facebook.getUidByFbid(fbid, function(err, uid) {
			if(err) {
				return callback(err);
			}

			if (uid !== null) {
				// Existing User
				callback(null, {
					uid: uid
				});
			} else {
				// New User
				var success = function(uid) {
					// Save facebook-specific information to the user
					user.setUserField(uid, 'fbid', fbid);
					db.setObjectField('fbid:uid', fbid, uid);
					callback(null, {
						uid: uid
					});
				};

				user.getUidByEmail(email, function(err, uid) {
					if(err) {
						return callback(err);
					}

					if (!uid) {
						user.create({username: name, email: email}, function(err, uid) {
							if(err) {
								return callback(err);
							}

							success(uid);
						});
					} else {
						success(uid); // Existing account -- merge
					}
				});
			}
		});
	};

	Facebook.getUidByFbid = function(fbid, callback) {
		db.getObjectField('fbid:uid', fbid, function(err, uid) {
			if (err) {
				return callback(err);
			}
			callback(null, uid);
		});
	};

	Facebook.addMenuItem = function(custom_header, callback) {
		custom_header.authentication.push({
			"route": constants.admin.route,
			"icon": constants.admin.icon,
			"name": constants.name
		});

		callback(null, custom_header);
	};

	module.exports = Facebook;
}(module));<|endoftext|>


<commit_before>"use strict";

var plugin = {},
	emitter = module.parent.require('./emitter'),
	templates = module.parent.require('templates.js'),
	SocketPlugins = module.parent.require('./socket.io/plugins'),
	user = module.parent.require('./user'),
	db = module.parent.require('./database'),
	controllers;

plugin.init = function(params, callback) {
	var app = params.router,
		middleware = params.middleware;

	controllers = params.controllers;

	app.get('/admin/plugins/category-sections', middleware.admin.buildHeader, renderAdmin);
	app.get('/api/admin/plugins/category-sections', renderAdmin);

	SocketPlugins['category-sections'] = {};
	SocketPlugins['category-sections'].save = function(socket, data, callback) {
		user.isAdministrator(socket.uid, function(err, isAdmin) {
			if (isAdmin) {
				saveSections(data, callback);
			}
		});
	};

	modifyCategoryTpl(callback);
};

plugin.addAdminNavigation = function(header, callback) {
	header.plugins.push({
		route: '/plugins/category-sections',
		icon: 'fa-folder-open-o',
		name: 'Category Sections'
	});

	callback(null, header);
};

plugin.getCategories = function(params, callback) {
	getCategories(params, function(err, data) {
		params.res.render(data.tpl, data.data);
	});
};

function saveSections(data, callback) {
	db.set('plugins:category-sections:sections', JSON.stringify(data), callback);
}

function renderAdmin(req, res, next) {
	getCategories({
		req: req,
		res: res
	}, function(err, data) {
		res.render('admin/plugins/category-sections', data);
	});
}

function getCategories(params, callback) {
	function getSections(tpl, data) {
		db.get('plugins:category-sections:sections', function(err, sections) {
			if (err) {
				return callback(err);
			}

			sections = (sections && sections.length) ? JSON.parse(sections) : [];

			var categories = data.categories,
				sectioned = [];

			delete data.categories;
			data.uncategorized = [];

			sections.forEach(function(section) {
				section.categories = [];

				section.cids.forEach(function(cid) {
					for (var c in categories) {
						if (categories.hasOwnProperty(c)) {
							if (parseInt(cid, 10) === parseInt(categories[c].cid, 10)) {
								section.categories.push(categories[c]);
								sectioned.push(parseInt(categories[c].cid, 10));
								break;
							}
						}
					}
				});
			});

			categories.forEach(function(category, idx) {
				if (sectioned.indexOf(parseInt(category.cid, 10)) === -1) {
					data.uncategorized.push(category);
				}
			});

			res.locals.metaTags = override.locals.metaTags;
			data.sections = sections;
			callback(null, {
				tpl: tpl,
				data: data
			});
		});
	}

	var req = params.req,
		res = params.res,
		override = { // a fake res object to trick the controller
			locals: {},
			render: getSections
		};

	controllers.categories.list(req, override, params.next);
}

function modifyCategoryTpl(callback) {
	var fs = require('fs'),
		path = require('path'),
		nconf = module.parent.require('nconf'),
		tplPath = path.join(nconf.get('base_dir'), 'public/templates/categories.tpl');

	fs.readFile(tplPath, function(err, tpl) {
		if (err) {
			return callback(err);
		}
		tpl = tpl.toString();
		var block = templates.getBlock(tpl, 'categories');

		if (!tpl.match('')) {
			tpl = tpl.replace(block, '

{sections.name}
' + block + '

');
			tpl = tpl.replace(/\{categories/g, '{sections.categories');
			tpl = tpl.replace(/IF categories/g, 'IF sections.categories');
			tpl = tpl.replace(/masonry/, '');
		}

		fs.writeFile(tplPath, tpl, callback);
	});
}

module.exports = plugin;
<commit_msg>Added better theming support, including Persona theme.<commit_after>"use strict";

var plugin = {},
	emitter = module.parent.require('./emitter'),
	templates = module.parent.require('templates.js'),
	SocketPlugins = module.parent.require('./socket.io/plugins'),
	user = module.parent.require('./user'),
	db = module.parent.require('./database'),
	controllers;

plugin.init = function(params, callback) {
	var app = params.router,
		middleware = params.middleware;

	controllers = params.controllers;

	app.get('/admin/plugins/category-sections', middleware.admin.buildHeader, renderAdmin);
	app.get('/api/admin/plugins/category-sections', renderAdmin);

	SocketPlugins['category-sections'] = {};
	SocketPlugins['category-sections'].save = function(socket, data, callback) {
		user.isAdministrator(socket.uid, function(err, isAdmin) {
			if (isAdmin) {
				saveSections(data, callback);
			}
		});
	};

	modifyCategoryTpl(callback);
};

plugin.addAdminNavigation = function(header, callback) {
	header.plugins.push({
		route: '/plugins/category-sections',
		icon: 'fa-folder-open-o',
		name: 'Category Sections'
	});

	callback(null, header);
};

plugin.getCategories = function(params, callback) {
	getCategories(params, function(err, data) {
		params.res.render(data.tpl, data.data);
	});
};

function saveSections(data, callback) {
	db.set('plugins:category-sections:sections', JSON.stringify(data), callback);
}

function renderAdmin(req, res, next) {
	getCategories({
		req: req,
		res: res
	}, function(err, data) {
		res.render('admin/plugins/category-sections', data);
	});
}

function getCategories(params, callback) {
	function getSections(tpl, data) {
		db.get('plugins:category-sections:sections', function(err, sections) {
			if (err) {
				return callback(err);
			}

			sections = (sections && sections.length) ? JSON.parse(sections) : [];

			var categories = data.categories,
				sectioned = [];

			delete data.categories;
			data.uncategorized = [];

			sections.forEach(function(section) {
				section.categories = [];

				section.cids.forEach(function(cid) {
					for (var c in categories) {
						if (categories.hasOwnProperty(c)) {
							if (parseInt(cid, 10) === parseInt(categories[c].cid, 10)) {
								section.categories.push(categories[c]);
								sectioned.push(parseInt(categories[c].cid, 10));
								break;
							}
						}
					}
				});
			});

			categories.forEach(function(category, idx) {
				if (sectioned.indexOf(parseInt(category.cid, 10)) === -1) {
					data.uncategorized.push(category);
				}
			});

			res.locals.metaTags = override.locals.metaTags;
			data.sections = sections;
			callback(null, {
				tpl: tpl,
				data: data
			});
		});
	}

	var req = params.req,
		res = params.res,
		override = { // a fake res object to trick the controller
			locals: {},
			render: getSections
		};

	controllers.categories.list(req, override, params.next);
}

function modifyCategoryTpl(callback) {
	var fs = require('fs'),
		path = require('path'),
		nconf = module.parent.require('nconf'),
		tplPath = path.join(nconf.get('base_dir'), 'public/templates/categories.tpl'),
		theme = module.parent.require("./meta").config["theme:id"];

	fs.readFile(tplPath, function(err, tpl) {
		if (err) {
			return callback(err);
		}
		tpl = tpl.toString();
		var block = templates.getBlock(tpl, 'categories');

		if (!tpl.match('')) {
			if (theme === "nodebb-theme-persona") {
				tpl = tpl.replace('<ul class="categories"', '<ul class="sections"');
				tpl = tpl.replace(block, '

{sections.name}

' + block + '

');
			} else {
				tpl = tpl.replace(block, '

{sections.name}
' + block + '

');
			}

			tpl = tpl.replace(block, '

{sections.name}
' + block + '

');
			tpl = tpl.replace(/\{categories/g, '{sections.categories');
			tpl = tpl.replace(/IF categories/g, 'IF sections.categories');
			tpl = tpl.replace(/masonry/, '');
		}

		fs.writeFile(tplPath, tpl, callback);
	});
}

module.exports = plugin;
<|endoftext|>


<commit_before>"use strict";

/* globals module, require */

var db = module.parent.require('./database'),
	winston = module.parent.require('winston'),
	engine = require('solr-client'),
	async = module.parent.require('async'),

	topics = module.parent.require('./topics'),
	posts = module.parent.require('./posts'),

	Solr = {
		config: {},	// default is localhost:8983, '' core, '/solr' path
		client: undefined
	};

Solr.init = function(app, middleware, controllers, callback) {
	var pluginMiddleware = require('./middleware'),
		render = function(req, res, next) {
			// Regenerate csrf token
			var token = req.csrfToken();

			res.render('admin/plugins/solr', {
				ping: res.locals.ping,
				enabled: res.locals.enabled,
				stats: res.locals.stats,
				csrf: token
			});
		};

	app.get('/admin/plugins/solr', middleware.admin.buildHeader, pluginMiddleware.ping, pluginMiddleware.getEnabled, pluginMiddleware.getStats, render);
	app.get('/api/admin/plugins/solr', pluginMiddleware.ping, pluginMiddleware.getEnabled, pluginMiddleware.getStats, render);

	// Utility
	app.post('/admin/plugins/solr/rebuild', middleware.admin.isAdmin, Solr.rebuildIndex);
	app.post('/admin/plugins/solr/toggle', Solr.toggle);
	app.delete('/admin/plugins/solr/flush', middleware.admin.isAdmin, Solr.flush);

	Solr.getSettings(Solr.connect);

	callback();
};

Solr.ping = function(callback) {
	if (Solr.client) {
		Solr.client.ping(callback);
	} else {
		callback(new Error('not-connected'));
	}
};

Solr.checkConflict = function() {
	if (module.parent.exports.libraries['nodebb-plugin-dbsearch']) {
		return true;
	} else {
		return false;
	}
};

Solr.getSettings = function(callback) {
	db.getObject('settings:solr', function(err, config) {
		Solr.config = {};
		if (!err) {
			for(var k in config) {
				if (config.hasOwnProperty(k) && config[k].length && !Solr.config.hasOwnProperty(k)) {
					Solr.config[k] = config[k];
				}
			}
		} else {
			winston.error('[plugin:solr] Could not fetch settings, assuming defaults.');
		}

		callback();
	});
};

Solr.getRecordCount = function(callback) {
	var query = Solr.client.createQuery().q('*:*').start(0).rows(0);

	Solr.client.search(query, function(err, obj) {
		if (!err) {
			callback(undefined, obj.response.numFound);
		} else {
			callback(err);
		}
	});
};

Solr.getTopicCount = function(callback) {
	var query = Solr.client.createQuery().q('title_t:*').start(0).rows(0);

	Solr.client.search(query, function(err, obj) {
		if (!err) {
			callback(undefined, obj.response.numFound);
		} else {
			callback(err);
		}
	});
}

Solr.onConfigChange = function(hash) {
	if (hash === 'settings:solr') {
		Solr.getSettings(Solr.connect);
	}
};

Solr.connect = function() {
	if (Solr.client) {
		delete Solr.client;
	}

	Solr.client = engine.createClient(Solr.config);
	Solr.client.autoCommit = true;
};

Solr.adminMenu = function(custom_header, callback) {
	custom_header.plugins.push({
		"route": '/plugins/solr',
		"icon": 'fa-search',
		"name": 'Apache Solr'
	});

	callback(null, custom_header);
};

Solr.search = function(data, callback) {
	if (Solr.checkConflict()) {
		// The dbsearch plugin was detected, abort search!
		winston.warn('[plugin/solr] Another search plugin (dbsearch) is enabled, so search via Solr was aborted.');
		return callback(null, data);
	} else if (data.index === 'topic') {
		// We are only using the "post" index, because Solr does its own relevency sorting
		return callback(null, []);
	}

	winston.info('[plugin/solr] Conducting search for: "' + data.query + '"');

	var query = Solr.client.createQuery().q(data.query).dismax().qf({
			title_t: 1.5,
			description_t: 1
		}).start(0).rows(20);

	Solr.client.search(query, function(err, obj) {
		if (obj.response.docs.length > 0) {
			callback(null, obj.response.docs.map(function(result) {
				return result.id;
			}));
		} else {
			callback(null, []);
		}
	});
};

Solr.toggle = function(req, res) {
	if (req.body.state) {
		db.setObjectField('settings:solr', 'enabled', parseInt(req.body.state, 10) ? '1' : '0', function(err) {
			Solr.config.enabled = req.body.state;
			res.send(!err ? 200 : 500);
		});
	} else {
		res.send(400, "'state' required");
	}
};

Solr.add = function(payload, callback) {
	Solr.client.add(payload, function(err, obj) {
		if (err) {
			winston.error('[plugins/solr] Could not index post ' + payload.id + ', error: ' + err.message);
		} else if (typeof callback === 'function') {
			callback.apply(arguments);
		}
	});
};

Solr.remove = function(pid) {
	Solr.client.delete('id', pid, function(err, obj) {
		if (err) {
			winston.error('[plugins/solr] Could not remove post ' + pid + ' from index');
		}
	});
};

Solr.flush = function(req, res) {
	Solr.client.delete('id', '*', function(err, obj){
		if (err) {
			winston.error('[plugins/solr] Could not empty the search index');
			res.send(500, err.message);
		} else {
			res.send(200);
		}
	});
};

Solr.post = {};
Solr.post.save = function(postData) {
	if (!parseInt(Solr.config.enabled, 10)) {
		return;
	}

	Solr.add({
		id: postData.pid,
		description_t: postData.content
	});
};

Solr.post.delete = function(pid, callback) {
	if (!parseInt(Solr.config.enabled, 10)) {
		return;
	}

	Solr.remove(pid);

	if (typeof callback === 'function') {
		if (!parseInt(Solr.config.enabled, 10)) {
			return;
		}

		callback();
	}
};

Solr.post.restore = function(postData) {
	if (!parseInt(Solr.config.enabled, 10)) {
		return;
	}

	Solr.add({
		id: postData.pid,
		description_t: postData.content
	});
};

Solr.post.edit = Solr.post.restore;

Solr.topic = {};
Solr.topic.post = function(topicObj) {
	if (!parseInt(Solr.config.enabled, 10)) {
		return;
	}

	Solr.indexTopic(topicObj.tid);
};

Solr.topic.delete = function(tid) {
	if (!parseInt(Solr.config.enabled, 10)) {
		return;
	}

	Solr.deindexTopic(tid);
};

Solr.topic.restore = function(tid) {
	if (!parseInt(Solr.config.enabled, 10)) {
		return;
	}

	Solr.indexTopic(tid);
};

Solr.topic.edit = function(tid) {
	if (!parseInt(Solr.config.enabled, 10)) {
		return;
	}

	topics.getTopicFields(tid, ['mainPid', 'title'], function(err, topicData) {
		Solr.indexPost(topicData.mainPid, function(err, payload) {
			payload.title_t = topicData.title;
			Solr.add(payload);
		});
	});
};

/* Topic and Post indexing methods */

Solr.indexTopic = function(tid, callback) {
	async.parallel({
		topic: async.apply(topics.getTopicFields, tid, ['title', 'mainPid']),
		pids: async.apply(topics.getPids, tid)
	}, function(err, data) {
		// Add OP to the list of pids to index
		if (data.topic.mainPid) {
			data.pids.unshift(data.topic.mainPid);
		}

		async.map(data.pids, Solr.indexPost, function(err, payload) {
			if (err) {
				winston.error('[plugins/solr] Encountered an error while compiling post data for tid ' + tid);
				if (callback) callback(err);
			} else {
				// Also index the title into the main post of this topic
				for(var x=0,numPids=payload.length;x<numPids;x++) {
					if (payload[x].id === data.topic.mainPid) {
						payload[x].title_t = data.topic.title;
					}
				}

				if (typeof callback === 'function') {
					callback(undefined, payload);
				} else {
					Solr.add(payload, callback);
				}
			}
		});
	});
};

Solr.deindexTopic = function(tid) {
	async.parallel({
		mainPid: async.apply(topics.getTopicField, tid, 'mainPid'),
		pids: async.apply(topics.getPids, tid)
	}, function(err, data) {
		data.pids.unshift(data.mainPid);
		var query = 'id:(' + data.pids.join(' OR ') + ')';
		Solr.client.deleteByQuery(query, function(err, obj) {
			if (err) {
				winston.error('[plugins/solr] Encountered an error while deindexing tid ' + tid);
			}
		});
	});
};

Solr.indexPost = function(pid, callback) {
	posts.getPostField(pid, 'content', function(err, content) {
		if (typeof callback === 'function') {
			callback(undefined, {
				id: pid,
				description_t: content
			});
		} else {
			Solr.add({
				id: pid,
				description_t: content
			});
		}
	});
};

Solr.deindexPost = Solr.post.delete;

Solr.rebuildIndex = function(req, res) {
	db.getSortedSetRange('topics:tid', 0, -1, function(err, tids) {
		if (err) {
			winston.error('[plugins/solr] Could not retrieve topic listing for indexing');
		} else {
			async.map(tids, Solr.indexTopic, function(err, topicPayloads) {
				var payload = [];
				for(var x=0,numTopics=topicPayloads.length;x<numTopics;x++) {
					payload = payload.concat(topicPayloads[x]);
				}

				Solr.add(payload, function(err, obj) {
					if (!err) {
						res.send(200);
					}
				});
			});
		}
	});
};

module.exports = Solr;<commit_msg>closed #4<commit_after>"use strict";

/* globals module, require */

var db = module.parent.require('./database'),
	winston = module.parent.require('winston'),
	engine = require('solr-client'),
	async = module.parent.require('async'),

	topics = module.parent.require('./topics'),
	posts = module.parent.require('./posts'),

	// This method is necessary until solr-client 0.3.x is released
	escapeSpecialChars = function(s) {
		return s.replace(/([\+\-&\|!\(\)\{\}\[\]\^"~\*\?:\\\ ])/g, function(match) {
			return '\\' + match;
		});
	},

	Solr = {
		config: {},	// default is localhost:8983, '' core, '/solr' path
		client: undefined
	};

Solr.init = function(app, middleware, controllers, callback) {
	var pluginMiddleware = require('./middleware'),
		render = function(req, res, next) {
			// Regenerate csrf token
			var token = req.csrfToken();

			res.render('admin/plugins/solr', {
				ping: res.locals.ping,
				enabled: res.locals.enabled,
				stats: res.locals.stats,
				csrf: token
			});
		};

	app.get('/admin/plugins/solr', middleware.admin.buildHeader, pluginMiddleware.ping, pluginMiddleware.getEnabled, pluginMiddleware.getStats, render);
	app.get('/api/admin/plugins/solr', pluginMiddleware.ping, pluginMiddleware.getEnabled, pluginMiddleware.getStats, render);

	// Utility
	app.post('/admin/plugins/solr/rebuild', middleware.admin.isAdmin, Solr.rebuildIndex);
	app.post('/admin/plugins/solr/toggle', Solr.toggle);
	app.delete('/admin/plugins/solr/flush', middleware.admin.isAdmin, Solr.flush);

	Solr.getSettings(Solr.connect);

	callback();
};

Solr.ping = function(callback) {
	if (Solr.client) {
		Solr.client.ping(callback);
	} else {
		callback(new Error('not-connected'));
	}
};

Solr.checkConflict = function() {
	if (module.parent.exports.libraries['nodebb-plugin-dbsearch']) {
		return true;
	} else {
		return false;
	}
};

Solr.getSettings = function(callback) {
	db.getObject('settings:solr', function(err, config) {
		Solr.config = {};
		if (!err) {
			for(var k in config) {
				if (config.hasOwnProperty(k) && config[k].length && !Solr.config.hasOwnProperty(k)) {
					Solr.config[k] = config[k];
				}
			}
		} else {
			winston.error('[plugin:solr] Could not fetch settings, assuming defaults.');
		}

		callback();
	});
};

Solr.getRecordCount = function(callback) {
	var query = Solr.client.createQuery().q('*:*').start(0).rows(0);

	Solr.client.search(query, function(err, obj) {
		if (!err) {
			callback(undefined, obj.response.numFound);
		} else {
			callback(err);
		}
	});
};

Solr.getTopicCount = function(callback) {
	var query = Solr.client.createQuery().q('title_t:*').start(0).rows(0);

	Solr.client.search(query, function(err, obj) {
		if (!err) {
			callback(undefined, obj.response.numFound);
		} else {
			callback(err);
		}
	});
}

Solr.onConfigChange = function(hash) {
	if (hash === 'settings:solr') {
		Solr.getSettings(Solr.connect);
	}
};

Solr.connect = function() {
	if (Solr.client) {
		delete Solr.client;
	}

	Solr.client = engine.createClient(Solr.config);
	Solr.client.autoCommit = true;
};

Solr.adminMenu = function(custom_header, callback) {
	custom_header.plugins.push({
		"route": '/plugins/solr',
		"icon": 'fa-search',
		"name": 'Apache Solr'
	});

	callback(null, custom_header);
};

Solr.search = function(data, callback) {
	if (Solr.checkConflict()) {
		// The dbsearch plugin was detected, abort search!
		winston.warn('[plugin/solr] Another search plugin (dbsearch) is enabled, so search via Solr was aborted.');
		return callback(null, data);
	} else if (data.index === 'topic') {
		// We are only using the "post" index, because Solr does its own relevency sorting
		return callback(null, []);
	}

	winston.info('[plugin/solr] Conducting search for: "' + data.query + '"');

	var query = Solr.client.createQuery().q(data.query).dismax().qf({
			title_t: 1.5,
			description_t: 1
		}).start(0).rows(20);

	Solr.client.search(query, function(err, obj) {
		if (obj.response.docs.length > 0) {
			callback(null, obj.response.docs.map(function(result) {
				return result.id;
			}));
		} else {
			callback(null, []);
		}
	});
};

Solr.searchTopic = function(tid, term, callback) {
	async.parallel({
		mainPid: async.apply(topics.getTopicField, tid, 'mainPid'),
		pids: async.apply(topics.getPids, tid)
	}, function(err, data) {
		data.pids.unshift(data.mainPid);
		var query = Solr.client.createQuery().q({
				description_t: escapeSpecialChars(term),
				id: '(' + data.pids.join(' OR ') + ')'
			});

		Solr.client.search(query, function(err, obj) {
			if (obj.response.docs.length > 0) {
				callback(null, obj.response.docs.map(function(result) {
					return result.id;
				}));
			} else {
				callback(null, []);
			}
		});
	});
};

Solr.toggle = function(req, res) {
	if (req.body.state) {
		db.setObjectField('settings:solr', 'enabled', parseInt(req.body.state, 10) ? '1' : '0', function(err) {
			Solr.config.enabled = req.body.state;
			res.send(!err ? 200 : 500);
		});
	} else {
		res.send(400, "'state' required");
	}
};

Solr.add = function(payload, callback) {
	Solr.client.add(payload, function(err, obj) {
		if (err) {
			winston.error('[plugins/solr] Could not index post ' + payload.id + ', error: ' + err.message);
		} else if (typeof callback === 'function') {
			callback.apply(arguments);
		}
	});
};

Solr.remove = function(pid) {
	Solr.client.delete('id', pid, function(err, obj) {
		if (err) {
			winston.error('[plugins/solr] Could not remove post ' + pid + ' from index');
		}
	});
};

Solr.flush = function(req, res) {
	Solr.client.delete('id', '*', function(err, obj){
		if (err) {
			winston.error('[plugins/solr] Could not empty the search index');
			res.send(500, err.message);
		} else {
			res.send(200);
		}
	});
};

Solr.post = {};
Solr.post.save = function(postData) {
	if (!parseInt(Solr.config.enabled, 10)) {
		return;
	}

	Solr.add({
		id: postData.pid,
		description_t: postData.content
	});
};

Solr.post.delete = function(pid, callback) {
	if (!parseInt(Solr.config.enabled, 10)) {
		return;
	}

	Solr.remove(pid);

	if (typeof callback === 'function') {
		if (!parseInt(Solr.config.enabled, 10)) {
			return;
		}

		callback();
	}
};

Solr.post.restore = function(postData) {
	if (!parseInt(Solr.config.enabled, 10)) {
		return;
	}

	Solr.add({
		id: postData.pid,
		description_t: postData.content
	});
};

Solr.post.edit = Solr.post.restore;

Solr.topic = {};
Solr.topic.post = function(topicObj) {
	if (!parseInt(Solr.config.enabled, 10)) {
		return;
	}

	Solr.indexTopic(topicObj.tid);
};

Solr.topic.delete = function(tid) {
	if (!parseInt(Solr.config.enabled, 10)) {
		return;
	}

	Solr.deindexTopic(tid);
};

Solr.topic.restore = function(tid) {
	if (!parseInt(Solr.config.enabled, 10)) {
		return;
	}

	Solr.indexTopic(tid);
};

Solr.topic.edit = function(tid) {
	if (!parseInt(Solr.config.enabled, 10)) {
		return;
	}

	topics.getTopicFields(tid, ['mainPid', 'title'], function(err, topicData) {
		Solr.indexPost(topicData.mainPid, function(err, payload) {
			payload.title_t = topicData.title;
			Solr.add(payload);
		});
	});
};

/* Topic and Post indexing methods */

Solr.indexTopic = function(tid, callback) {
	async.parallel({
		topic: async.apply(topics.getTopicFields, tid, ['title', 'mainPid']),
		pids: async.apply(topics.getPids, tid)
	}, function(err, data) {
		// Add OP to the list of pids to index
		if (data.topic.mainPid) {
			data.pids.unshift(data.topic.mainPid);
		}

		async.map(data.pids, Solr.indexPost, function(err, payload) {
			if (err) {
				winston.error('[plugins/solr] Encountered an error while compiling post data for tid ' + tid);
				if (callback) callback(err);
			} else {
				// Also index the title into the main post of this topic
				for(var x=0,numPids=payload.length;x<numPids;x++) {
					if (payload[x].id === data.topic.mainPid) {
						payload[x].title_t = data.topic.title;
					}
				}

				if (typeof callback === 'function') {
					callback(undefined, payload);
				} else {
					Solr.add(payload, callback);
				}
			}
		});
	});
};

Solr.deindexTopic = function(tid) {
	async.parallel({
		mainPid: async.apply(topics.getTopicField, tid, 'mainPid'),
		pids: async.apply(topics.getPids, tid)
	}, function(err, data) {
		data.pids.unshift(data.mainPid);
		var query = 'id:(' + data.pids.join(' OR ') + ')';
		Solr.client.deleteByQuery(query, function(err, obj) {
			if (err) {
				winston.error('[plugins/solr] Encountered an error while deindexing tid ' + tid);
			}
		});
	});
};

Solr.indexPost = function(pid, callback) {
	posts.getPostField(pid, 'content', function(err, content) {
		if (typeof callback === 'function') {
			callback(undefined, {
				id: pid,
				description_t: content
			});
		} else {
			Solr.add({
				id: pid,
				description_t: content
			});
		}
	});
};

Solr.deindexPost = Solr.post.delete;

Solr.rebuildIndex = function(req, res) {
	db.getSortedSetRange('topics:tid', 0, -1, function(err, tids) {
		if (err) {
			winston.error('[plugins/solr] Could not retrieve topic listing for indexing');
		} else {
			async.map(tids, Solr.indexTopic, function(err, topicPayloads) {
				var payload = [];
				for(var x=0,numTopics=topicPayloads.length;x<numTopics;x++) {
					payload = payload.concat(topicPayloads[x]);
				}

				Solr.add(payload, function(err, obj) {
					if (!err) {
						res.send(200);
					}
				});
			});
		}
	});
};

module.exports = Solr;<|endoftext|>


<commit_before>(function(module) {
		"use strict";
		var Twitch = {},
			embed = '';

		var regularUrl = /<a href="https:\/\/www\.twitch\.tv\/(\w*)(.*)<\/a>/g;

		Twitch.parse = function(data, callback) {
			if (!data || !data.postData || !data.postData.content) {
				return callback(null, data);
			}

			console.log(data.postData.content);

			if (data.postData.content.match(regularUrl)) {
				data.postData.content = data.postData.content.replace(regularUrl, embed);
		}

		callback(null, data);
	};

	module.exports = Twitch;
}(module));<commit_msg>Remove loging<commit_after>(function(module) {
		"use strict";
		var Twitch = {},
			embed = '';

		var regularUrl = /<a href="https:\/\/www\.twitch\.tv\/(\w*)(.*)<\/a>/g;

		Twitch.parse = function(data, callback) {
			if (!data || !data.postData || !data.postData.content) {
				return callback(null, data);
			}

			if (data.postData.content.match(regularUrl)) {
				data.postData.content = data.postData.content.replace(regularUrl, embed);
		}

		callback(null, data);
	};

	module.exports = Twitch;
}(module));<|endoftext|>


<commit_before>import { setTimeout } from "timers";

const eris = require("eris").Client;
const s = require("superagent");
const ErisEndpoints = require("eris/lib/rest/Endpoints");
const ModLog = require("./modlog/index");
const _ModLog = new ModLog(); // js is a cunt
class LibWUtil extends eris {
    /*eslint-disable no-unused-vars*/
    constuctor(token, options) {
        //super(token,options);
    }
    get modLog() {
        return _ModLog;
    }

    async canUseCommand(user, command) {
        if (command.category == 4 && this.isAdmin(user)) return true;
        if (command.category == 3 && (await this.isModerator(user))) return true;
        if (command.category == 2 && isO({ author: user })) return true;
        if (command.category == 1) return true;
        return false;
    }

    async _doPost(key = "", url = "", pld = { server_count: this.guilds.size }) {
        if (!key || !url || !pld) return;
        let data;
        try {
            data = await s.post(url)
                .set("Authorization", key)
                .send(pld);
        } catch (err) {
            throw {
                message: "Can't post, access text or body property for more info.",
                text: err.text,
                body: err.body
            };
        }
        if (data.statusCode != 200) throw {
            message: "Can't post, access text or body property for more info.",
            text: data.text,
            body: data.body
        };
        return;
    }
    passesRoleHierarchy(member1, member2) {
        if (member1.guild != member2.guild) throw new TypeError("Members aren't in the same guild");
        if (member1.guild.ownerID == member1.id) return true;
        if (member1.roles.length == 0) return false;
        if (member2.roles.length == 0) return true;
        let member1Roles = member1.roles.map(r => member1.guild.roles.get(r));
        let member2Roles = member2.roles.map(r => member2.guild.roles.get(r));
        member1Roles = member1Roles.sort((a, b) => b.position - a.position);
        member2Roles = member2Roles.sort((a, b) => b.position - a.position);
        return member1Roles[0].position > member2Roles[0].position;
    }
    async postStats() {
        if (!config.dbotskey || config.dbotskey == "") return;
        try {
            return await this._doPost(config.dbotskey, `https://bots.discord.pw/api/bots/${this.user.id}/stats`);
        } catch (err) {
            throw err;
        }

    }
    async postStats2() {
        if (!config.dbots2key || config.dbots2key == "") return;
        try {
            return await this._doPost(config.dbots2key, `https://discordbots.org/api/bots/${this.user.id}/stats`);
        } catch (err) {
            throw err;
        }
    }
    async isModerator(member, botOwnerIsMod = true) {
        if (this.isAdmin(member, botOwnerIsMod)) return true;
        let serverHasModRole = false;
        let modRole = null;
        let server = await db.table("configs").get(member.guild.id).run();
        if (server) {
            let role = member.guild.roles.find(r => r.name == server.modRole);
            if (role) { serverHasModRole = true; modRole = role; }
        } else {
            let role = member.guild.roles.find(r => r.name == "tt.bot mod");
            if (role) { serverHasModRole = true; modRole = role; }
        }
        if (serverHasModRole) return member.roles.includes(modRole.id);
    }

    isAdmin(member, botOwnerIsAdmin = true) {
        if (botOwnerIsAdmin && isO({ author: member.user })) return true;
        if (member.permission.json["administrator"]) return true;
        if (member.guild.ownerID == member.id) return true;
    }
    listBotColls() {
        return this.guilds.filter(g => ((g.members.filter(fn => fn.bot).length) / g.memberCount * 100) >= 75);
    }
    // eslint disable no-useless-escape
    escapeMarkdown(string) {
        let replacedItallicsAndBold = string.replace(/\*/g, "\\*");
        let replacedBackticks = replacedItallicsAndBold.replace(/\`/g, "\\`");
        let replacedUnderscores = replacedBackticks.replace(/\_/g, "\\_");
        let replacedBrackets = replacedUnderscores.replace(/\[/g, "\\[").replace(/\(/, "\\(").replace(/\]/g, "\\]").replace(/\)/g, "\\)");
        return replacedBrackets;
    }
    //actually Client.getRESTUser, but bypasses the need of options.restMode
    getUserWithoutRESTMode(userID) {
        return this.requestHandler.request("GET", ErisEndpoints.USER(userID), true).then((user) => new ErisO.User(user, this));
    }
    getBaseObject(id) {
        return new (require("eris/lib/structures/Base"))(id);
    }
    getTag(user) {
        return `${user.username}#${user.discriminator}`;
    }

    embedToText(embed) {
        let txt = [];
        if (embed.title) txt.push(`----------${embed.title} ${embed.url ? `- ${embed.url}` : ""}----------`);
        if (embed.author) txt.push(`${embed.title ? "(" : ""}${embed.author.name || "noname"} - ${embed.author.icon_url || "noiconuri"} - ${embed.author.url || "nouri"}${embed.title ? ")" : ""}`);
        if (embed.description) txt.push(embed.description);
        if (embed.fields) embed.fields.forEach(f => {
            txt.push("--------------------");
            txt.push(f.name);
            txt.push("");
            txt.push(f.value);
            txt.push("--------------------");
        });
        if (embed.thumbnail) txt.push("THUMB: " + embed.thumbnail.url);
        if (embed.image) txt.push(`IMAGE: ${embed.image.url}`);
        if (embed.video) txt.push(`VIDEO: ${embed.video.url}`);
        if (embed.provider) txt.push(`PROVIDER: ${embed.provider.name} ${embed.provider.url}`);
        if (embed.footer) txt.push(`----------${embed.footer.text || "notext"} - ${embed.footer.icon_url || "noiconuri"}----------`);
        return txt.join("\n");
    }
    parseMsg(string, m, g) {
        return string.replace(/{u\.mention}/g, `<@!${m.user.id}>`)
            .replace(/{g\.name}/g, g.name)
            .replace(/{g\.id}/g, g.id)
            .replace(/{u\.name}/g, m.user.username)
            .replace(/{u\.discrim}/g, m.user.discriminator)
            .replace(/{u\.id}/g, m.user.id);
    }

    waitForEvent(event, timeout, check) {
        let t;
        if (!check || typeof check !== "function") check = () => true;
        return new Promise((rs, rj) => {
            const listener = (...args) => {
                if (check && typeof check == "function" && check(...args) === true) {
                    dispose();
                    rs([...args]);
                    return;
                }
            };
            const dispose = () => {
                this.removeListener(event, listener);
            };

            if (timeout) t = setTimeout(() => {
                dispose();
                rj("timeout");
            }, timeout);
            this.on(event, listener);
        });
    }
}
module.exports = LibWUtil;<commit_msg>fuck vscode intelli sense<commit_after>const eris = require("eris").Client;
const s = require("superagent");
const ErisEndpoints = require("eris/lib/rest/Endpoints");
const ModLog = require("./modlog/index");
const _ModLog = new ModLog(); // js is a cunt
class LibWUtil extends eris {
    /*eslint-disable no-unused-vars*/
    constuctor(token, options) {
        //super(token,options);
    }
    get modLog() {
        return _ModLog;
    }

    async canUseCommand(user, command) {
        if (command.category == 4 && this.isAdmin(user)) return true;
        if (command.category == 3 && (await this.isModerator(user))) return true;
        if (command.category == 2 && isO({ author: user })) return true;
        if (command.category == 1) return true;
        return false;
    }

    async _doPost(key = "", url = "", pld = { server_count: this.guilds.size }) {
        if (!key || !url || !pld) return;
        let data;
        try {
            data = await s.post(url)
                .set("Authorization", key)
                .send(pld);
        } catch (err) {
            throw {
                message: "Can't post, access text or body property for more info.",
                text: err.text,
                body: err.body
            };
        }
        if (data.statusCode != 200) throw {
            message: "Can't post, access text or body property for more info.",
            text: data.text,
            body: data.body
        };
        return;
    }
    passesRoleHierarchy(member1, member2) {
        if (member1.guild != member2.guild) throw new TypeError("Members aren't in the same guild");
        if (member1.guild.ownerID == member1.id) return true;
        if (member1.roles.length == 0) return false;
        if (member2.roles.length == 0) return true;
        let member1Roles = member1.roles.map(r => member1.guild.roles.get(r));
        let member2Roles = member2.roles.map(r => member2.guild.roles.get(r));
        member1Roles = member1Roles.sort((a, b) => b.position - a.position);
        member2Roles = member2Roles.sort((a, b) => b.position - a.position);
        return member1Roles[0].position > member2Roles[0].position;
    }
    async postStats() {
        if (!config.dbotskey || config.dbotskey == "") return;
        try {
            return await this._doPost(config.dbotskey, `https://bots.discord.pw/api/bots/${this.user.id}/stats`);
        } catch (err) {
            throw err;
        }

    }
    async postStats2() {
        if (!config.dbots2key || config.dbots2key == "") return;
        try {
            return await this._doPost(config.dbots2key, `https://discordbots.org/api/bots/${this.user.id}/stats`);
        } catch (err) {
            throw err;
        }
    }
    async isModerator(member, botOwnerIsMod = true) {
        if (this.isAdmin(member, botOwnerIsMod)) return true;
        let serverHasModRole = false;
        let modRole = null;
        let server = await db.table("configs").get(member.guild.id).run();
        if (server) {
            let role = member.guild.roles.find(r => r.name == server.modRole);
            if (role) { serverHasModRole = true; modRole = role; }
        } else {
            let role = member.guild.roles.find(r => r.name == "tt.bot mod");
            if (role) { serverHasModRole = true; modRole = role; }
        }
        if (serverHasModRole) return member.roles.includes(modRole.id);
    }

    isAdmin(member, botOwnerIsAdmin = true) {
        if (botOwnerIsAdmin && isO({ author: member.user })) return true;
        if (member.permission.json["administrator"]) return true;
        if (member.guild.ownerID == member.id) return true;
    }
    listBotColls() {
        return this.guilds.filter(g => ((g.members.filter(fn => fn.bot).length) / g.memberCount * 100) >= 75);
    }
    // eslint disable no-useless-escape
    escapeMarkdown(string) {
        let replacedItallicsAndBold = string.replace(/\*/g, "\\*");
        let replacedBackticks = replacedItallicsAndBold.replace(/\`/g, "\\`");
        let replacedUnderscores = replacedBackticks.replace(/\_/g, "\\_");
        let replacedBrackets = replacedUnderscores.replace(/\[/g, "\\[").replace(/\(/, "\\(").replace(/\]/g, "\\]").replace(/\)/g, "\\)");
        return replacedBrackets;
    }
    //actually Client.getRESTUser, but bypasses the need of options.restMode
    getUserWithoutRESTMode(userID) {
        return this.requestHandler.request("GET", ErisEndpoints.USER(userID), true).then((user) => new ErisO.User(user, this));
    }
    getBaseObject(id) {
        return new (require("eris/lib/structures/Base"))(id);
    }
    getTag(user) {
        return `${user.username}#${user.discriminator}`;
    }

    embedToText(embed) {
        let txt = [];
        if (embed.title) txt.push(`----------${embed.title} ${embed.url ? `- ${embed.url}` : ""}----------`);
        if (embed.author) txt.push(`${embed.title ? "(" : ""}${embed.author.name || "noname"} - ${embed.author.icon_url || "noiconuri"} - ${embed.author.url || "nouri"}${embed.title ? ")" : ""}`);
        if (embed.description) txt.push(embed.description);
        if (embed.fields) embed.fields.forEach(f => {
            txt.push("--------------------");
            txt.push(f.name);
            txt.push("");
            txt.push(f.value);
            txt.push("--------------------");
        });
        if (embed.thumbnail) txt.push("THUMB: " + embed.thumbnail.url);
        if (embed.image) txt.push(`IMAGE: ${embed.image.url}`);
        if (embed.video) txt.push(`VIDEO: ${embed.video.url}`);
        if (embed.provider) txt.push(`PROVIDER: ${embed.provider.name} ${embed.provider.url}`);
        if (embed.footer) txt.push(`----------${embed.footer.text || "notext"} - ${embed.footer.icon_url || "noiconuri"}----------`);
        return txt.join("\n");
    }
    parseMsg(string, m, g) {
        return string.replace(/{u\.mention}/g, `<@!${m.user.id}>`)
            .replace(/{g\.name}/g, g.name)
            .replace(/{g\.id}/g, g.id)
            .replace(/{u\.name}/g, m.user.username)
            .replace(/{u\.discrim}/g, m.user.discriminator)
            .replace(/{u\.id}/g, m.user.id);
    }

    waitForEvent(event, timeout, check) {
        let t;
        if (!check || typeof check !== "function") check = () => true;
        return new Promise((rs, rj) => {
            const listener = (...args) => {
                if (check && typeof check == "function" && check(...args) === true) {
                    dispose();
                    rs([...args]);
                    return;
                }
            };
            const dispose = () => {
                this.removeListener(event, listener);
            };

            if (timeout) t = setTimeout(() => {
                dispose();
                rj("timeout");
            }, timeout);
            this.on(event, listener);
        });
    }
}
module.exports = LibWUtil;<|endoftext|>


<commit_before>var express = require('express'),
  router = express.Router(),
  config = require('../../config/config'),
  mongoose = require('mongoose'),
  multer  = require('multer'),
  User = mongoose.model('User'),
  fs = require('fs'),
  direccion = "",
  dataType = "",
  imagename="",
  variante=1;
  Image = mongoose.model('Image');
var mcache = require('memory-cache');

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
      if (variante==1){
          cb(null, 'public/uploads/');
          direccion = 'public/uploads/';
          dataType = file.mimetype;
      }
      else {
          cb(null, 'public/uploads2/');
          direccion = 'public/uploads2/';
          dataType = file.mimetype;
      }
    },
    filename: function (req, file, cb) {
      imagename = Date.now()+ '-' + file.originalname;
      cb(null, imagename);

    }
});
var upload = multer({ storage: storage });

module.exports = function (app) {
  app.use('/Image', router);
};
router.get('/see', function (req, res, next) {
  id = mongoose.Types.ObjectId(req.query.image_id);
  let cacheBody = mcache.get(id)
  if (cacheBody) {
    res.contentType(cacheBody.contentType);
    res.send(fs.readFileSync(cacheBody.location));
  }else{
    Image.findById(id, function (err, doc) {
      if (err) return next(err);
        res.contentType(doc.img.contentType);
        value = doc.img;
        mcache.put(id, value, 10*1000);
        res.send(fs.readFileSync(doc.img.location));
    });
  }
});
router.get('/',function (req, res, next) {
  id = mongoose.Types.ObjectId(req.query.image_id);
  Image.findById(id,function (err, image) {
    if (err){ res.send(err);}
    res.render('updateimageform',{title:image.title, format:image.format, width:image.width, height:image.height, id:image._id,baseurl:config.baseUrl});
  });
});

router.post('/', upload.single('image'), function (req, res, next) {
  if(variante==1){
    variante=0;
  }
  else{
    variante=1;
  }
  var image = new Image({
    title: req.body.title,
    format: req.body.format,
    width: req.body.width,
    height: req.body.height,
    capture_date: req.body.capdate,
    quality: req.body.quality,
    img: {location:direccion + imagename, contentType:dataType},
    user_id : req.body.user_id,
    visibility: req.body.visibility

  });
  image.save(function (err) {
    if (!err) {
      //return console.log("created");
      res.redirect(config.baseUrl+'home');
    } else {
      //TODO: return page with errors
      res.end(err);
    }
  });
});

router.put('/',function (req, res, next) {
  id = mongoose.Types.ObjectId(req.query.image_id);
  Image.findById(id,function (err, image) {
    if (err){ res.send(err);}
    if (req.body.title != "" && req.body.format != "" && req.body.width != "" && req.body.height != "") {
      image.title = req.body.title;
      image.format = req.body.format;
      image.width = req.body.width;
      image.height = req.body.height;
      image.visibility = req.body.visibility;
      image.save(function (err) {
        if (!err) {
          //return console.log("created");
          res.end("1");
        } else {
          //TODO: return page with errors
          res.end("0");
        }
      });
    }
    else {res.end("0");}
  });
});

router.delete('/',function (req, res, next) {
  id=mongoose.Types.ObjectId(req.query.image_id);
    Image.findById(id,function (err, image) {
        fs.unlink(image.img.location, function(err) {
            if (err) {
                return console.error(err);
            }
        });
    });
  Image.remove({_id:id},function (err, image) {
    if (err){
      res.send(err);
      res.send("0")
    }
    res.end("1");
  });
});

router.post('/user_images',function (req, res, next) {
  Image.find({user_id:req.query.user_id},function (err, docs) {
    if (err){ res.send(err);}
    else{ res.send(docs);}
  });

});

router.post('/public_images',function (req, res, next) {
  Image.find({visibility:"public"},function (err, docs) {
    if (err){ res.send(err);}
    else{ res.send(docs);}
  });
});

router.post('/shared_with_me',function (req, res, next) {
  Image.find({"shared_with.username":req.query.user},function (err, docs) {
    if (err){ res.send(err);}
    else{ res.send(docs);}
  });
});

router.post('/search',function (req, res, next) {
    text = req.body.search;
  Image.find({title: new RegExp(text+'+', "i"),visibility:"public"}, function(err, docs) {
    if (err){ res.send(err);}
    else{ res.send(docs);}
  });
});

router.put('/share',function (req, res, next) {
  User.find({user:req.query.username},function (err,user) {
    if (user.length){
      id = mongoose.Types.ObjectId(req.body.image_id);
      Image.findById(id,function (err,  image) {
        console.log("user id " + user[0]._id);
        image.shared_with.push({username:user[0].user,user:user[0]._id});
        image.save(function (err) {
          if (!err) {
            //return console.log("created");
            res.end("1");
          } else {
            //TODO: return page with errors;
            res.end("0");
          }
        });
      });
    }
    else{
      res.end("0");
    }
  });

});
<commit_msg>fileserver<commit_after>var express = require('express'),
  router = express.Router(),
  config = require('../../config/config'),
  mongoose = require('mongoose'),
  multer  = require('multer'),
  User = mongoose.model('User'),
  fs = require('fs'),
  direccion = "",
  dataType = "",
  imagename="",
  variante=1;
  Image = mongoose.model('Image');
var mcache = require('memory-cache');

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
      if (variante==1){
          cb(null, 'server1/mnt/glustervolume');
          direccion = 'server1/mnt/glustervolume/';
          dataType = file.mimetype;
      }
      else {
          cb(null, 'server2/mnt/glustervolume');
          direccion = 'server2/mnt/glustervolume';
          dataType = file.mimetype;
      }
    },
    filename: function (req, file, cb) {
      imagename = Date.now()+ '-' + file.originalname;
      cb(null, imagename);

    }
});
var upload = multer({ storage: storage });

module.exports = function (app) {
  app.use('/Image', router);
};
router.get('/see', function (req, res, next) {
  id = mongoose.Types.ObjectId(req.query.image_id);
  let cacheBody = mcache.get(id)
  if (cacheBody) {
    res.contentType(cacheBody.contentType);
    res.send(fs.readFileSync(cacheBody.location));
  }else{
    Image.findById(id, function (err, doc) {
      if (err) return next(err);
        res.contentType(doc.img.contentType);
        value = doc.img;
        mcache.put(id, value, 10*1000);
        res.send(fs.readFileSync(doc.img.location));
    });
  }
});
router.get('/',function (req, res, next) {
  id = mongoose.Types.ObjectId(req.query.image_id);
  Image.findById(id,function (err, image) {
    if (err){ res.send(err);}
    res.render('updateimageform',{title:image.title, format:image.format, width:image.width, height:image.height, id:image._id,baseurl:config.baseUrl});
  });
});

router.post('/', upload.single('image'), function (req, res, next) {
  if(variante==1){
    variante=0;
  }
  else{
    variante=1;
  }
  var image = new Image({
    title: req.body.title,
    format: req.body.format,
    width: req.body.width,
    height: req.body.height,
    capture_date: req.body.capdate,
    quality: req.body.quality,
    img: {location:direccion + imagename, contentType:dataType},
    user_id : req.body.user_id,
    visibility: req.body.visibility

  });
  image.save(function (err) {
    if (!err) {
      //return console.log("created");
      res.redirect(config.baseUrl+'home');
    } else {
      //TODO: return page with errors
      res.end(err);
    }
  });
});

router.put('/',function (req, res, next) {
  id = mongoose.Types.ObjectId(req.query.image_id);
  Image.findById(id,function (err, image) {
    if (err){ res.send(err);}
    if (req.body.title != "" && req.body.format != "" && req.body.width != "" && req.body.height != "") {
      image.title = req.body.title;
      image.format = req.body.format;
      image.width = req.body.width;
      image.height = req.body.height;
      image.visibility = req.body.visibility;
      image.save(function (err) {
        if (!err) {
          //return console.log("created");
          res.end("1");
        } else {
          //TODO: return page with errors
          res.end("0");
        }
      });
    }
    else {res.end("0");}
  });
});

router.delete('/',function (req, res, next) {
  id=mongoose.Types.ObjectId(req.query.image_id);
    Image.findById(id,function (err, image) {
        fs.unlink(image.img.location, function(err) {
            if (err) {
                return console.error(err);
            }
        });
    });
  Image.remove({_id:id},function (err, image) {
    if (err){
      res.send(err);
      res.send("0")
    }
    res.end("1");
  });
});

router.post('/user_images',function (req, res, next) {
  Image.find({user_id:req.query.user_id},function (err, docs) {
    if (err){ res.send(err);}
    else{ res.send(docs);}
  });

});

router.post('/public_images',function (req, res, next) {
  Image.find({visibility:"public"},function (err, docs) {
    if (err){ res.send(err);}
    else{ res.send(docs);}
  });
});

router.post('/shared_with_me',function (req, res, next) {
  Image.find({"shared_with.username":req.query.user},function (err, docs) {
    if (err){ res.send(err);}
    else{ res.send(docs);}
  });
});

router.post('/search',function (req, res, next) {
    text = req.body.search;
  Image.find({title: new RegExp(text+'+', "i"),visibility:"public"}, function(err, docs) {
    if (err){ res.send(err);}
    else{ res.send(docs);}
  });
});

router.put('/share',function (req, res, next) {
  User.find({user:req.query.username},function (err,user) {
    if (user.length){
      id = mongoose.Types.ObjectId(req.body.image_id);
      Image.findById(id,function (err,  image) {
        console.log("user id " + user[0]._id);
        image.shared_with.push({username:user[0].user,user:user[0]._id});
        image.save(function (err) {
          if (!err) {
            //return console.log("created");
            res.end("1");
          } else {
            //TODO: return page with errors;
            res.end("0");
          }
        });
      });
    }
    else{
      res.end("0");
    }
  });

});
<|endoftext|>


<commit_before>// using for time formatting - http://momentjs.com/
var moment = require('moment');

var selectedItem = Alloy.Models.device;

var deviceCollection = Alloy.Collections.instance("device");
/**
 deviceCollection.fetch({
 beforeSend : deviceCollection.setHeader,
 success : function(collection, response, option) {
 console.log("Collection Response: " + JSON.stringify(collection, null, 2));
 },
 error : function(collection, response, option) {
 console.log(response);
 }
 });
 */

deviceCollection.getAll({
	success : function(collection, response, option) {
		console.log("Collection Response: " + JSON.stringify(collection, null, 2));
	},
	error : function(collection, response, option) {
		console.log(response);
	}
});

function doOnTableViewClick(_event) {

	// use the 'index' property from the event to determine
	// which model from the collection was selected
	var currentItem = deviceCollection.at(_event.index);

	// log for debugging purposes and convert object to
	// string that is readable
	console.log(JSON.stringify(currentItem, null, 2));

	// create the new controller and pass in the
	// model object as an argument 'item'
	var ctrl = Alloy.createController('detail', {
		'item' : currentItem
	});
}

/**
 *
 */
function sampleOfFetchingAModel() {
	var deviceModel = Alloy.Models.instance("device");
	var modelID = "54e0d1d502f817bc0600442a";

	deviceModel.authFetch(modelID, {
		success : function(_r, _c) {
			// log the output
			console.log("deviceModel.fetch: " + JSON.stringify(_r, null, 2));
		},
		error : function(_r2, _c2) {
			// log an error
			console.log("Error- deviceModel.fetch " + _r);
		}
	});
}

/**
 *
 */
function sampleOfSavingAModel() {
	// create a new model and save it
	//1) create a model object
	var deviceModel = Alloy.Models.instance("device");

	// 2) set attributes on the model
	deviceModel.set({
		"first_col" : "Added from Appcelerator",
		"second_col" : "So we begin",
	});

	// 3) save the model using the extended helper function created
	// to encapsulate the kinvey authentication in the model object
	deviceModel.authSave({
		success : function(_r, _c) {
			// log the output
			console.log("deviceModel.save: " + JSON.stringify(_r, null, 2));
		},
		error : function(_r2, _c2) {
			// log an error
			console.log("Error- deviceModel.save " + _r);
		}
	});
}

/**
 *
 */
function sampleOfUpdatingAModel() {
	// create a new model and save it
	//1) get a model object
	var deviceModel = Alloy.Models.instance("device");
	var modelID = "54e0d1d502f817bc0600442a";

	deviceModel.authFetch(modelID, {
		success : function(_r, _c) {

			// 2) set attributes on the model that you
			//    want to update
			deviceModel.set({
				"first_col" : "Added from Home Again"
			});

			// 3) save the model using the extended helper function created
			//    to encapsulate the kinvey authentication in the model object
			//    the rest adapter will know what to do, save or update based
			//    on the existence of the model id
			deviceModel.authSave({
				success : function(_model, _response) {
					// log the output
					console.log("deviceModel.update: " + JSON.stringify(_model, null, 2));

					// this will cause the UI to update to reflect the changes
					var collection = Alloy.Collections.instance("device");
					collection.getAll({});
				},
				error : function(_model, _response) {
					// log an error
					console.log("Error- deviceModel.update " + JSON.stringify(_response, null, 2));
				}
			});
		},
		error : function(_model, _response) {
			// log an error
			console.log("Error- deviceModel.update when fetching " + _model);
		}
	});

}

/**
 *
 * @param {Object} evt
 */
function doOpen(evt) {
	if (OS_ANDROID) {
	}
}

/**
 * used to transform the model for easier output on the UI.
 *
 * this specifically was need to get the last modified date and the
 * creation date.
 *
 * @param {Object} _model
 */
function transform(_model) {
	var transform = _model.toJSON();
	return {
		first_col : transform.first_col,
		second_col : transform.second_col,

		// format the date using moment library
		lastModified : moment(transform._kmd.lmt).format('MMMM Do YYYY, h:mm:ss a'),
	};
}

//
// Need to handle opening the windows based on the platform
// Since on IOS we need the NavigationWindow opened first and
// on android we do not.
if (OS_IOS) {
	Alloy.Globals.navWindow = $.getView();

	Alloy.Globals.navWindow.open();
} else {
	$.getView().open();
}
//
Alloy.Collections.instance("device").on('sync', function(_model) {
	alert('collection has been changed ' + JSON.stringify(_model));
});

sampleOfUpdatingAModel();

<commit_msg>updating comment regarding use of moment.js<commit_after>// using for time formatting - http://momentjs.com/
var moment = require('moment');

var selectedItem = Alloy.Models.device;

var deviceCollection = Alloy.Collections.instance("device");
/**
 deviceCollection.fetch({
 beforeSend : deviceCollection.setHeader,
 success : function(collection, response, option) {
 console.log("Collection Response: " + JSON.stringify(collection, null, 2));
 },
 error : function(collection, response, option) {
 console.log(response);
 }
 });
 */

deviceCollection.getAll({
	success : function(collection, response, option) {
		console.log("Collection Response: " + JSON.stringify(collection, null, 2));
	},
	error : function(collection, response, option) {
		console.log(response);
	}
});

function doOnTableViewClick(_event) {

	// use the 'index' property from the event to determine
	// which model from the collection was selected
	var currentItem = deviceCollection.at(_event.index);

	// log for debugging purposes and convert object to
	// string that is readable
	console.log(JSON.stringify(currentItem, null, 2));

	// create the new controller and pass in the
	// model object as an argument 'item'
	var ctrl = Alloy.createController('detail', {
		'item' : currentItem
	});
}

/**
 *
 */
function sampleOfFetchingAModel() {
	var deviceModel = Alloy.Models.instance("device");
	var modelID = "54e0d1d502f817bc0600442a";

	deviceModel.authFetch(modelID, {
		success : function(_r, _c) {
			// log the output
			console.log("deviceModel.fetch: " + JSON.stringify(_r, null, 2));
		},
		error : function(_r2, _c2) {
			// log an error
			console.log("Error- deviceModel.fetch " + _r);
		}
	});
}

/**
 *
 */
function sampleOfSavingAModel() {
	// create a new model and save it
	//1) create a model object
	var deviceModel = Alloy.Models.instance("device");

	// 2) set attributes on the model
	deviceModel.set({
		"first_col" : "Added from Appcelerator",
		"second_col" : "So we begin",
	});

	// 3) save the model using the extended helper function created
	// to encapsulate the kinvey authentication in the model object
	deviceModel.authSave({
		success : function(_r, _c) {
			// log the output
			console.log("deviceModel.save: " + JSON.stringify(_r, null, 2));
		},
		error : function(_r2, _c2) {
			// log an error
			console.log("Error- deviceModel.save " + _r);
		}
	});
}

/**
 *
 */
function sampleOfUpdatingAModel() {
	// create a new model and save it
	//1) get a model object
	var deviceModel = Alloy.Models.instance("device");
	var modelID = "54e0d1d502f817bc0600442a";

	deviceModel.authFetch(modelID, {
		success : function(_r, _c) {

			// 2) set attributes on the model that you
			//    want to update
			deviceModel.set({
				"first_col" : "Added from Home Again"
			});

			// 3) save the model using the extended helper function created
			//    to encapsulate the kinvey authentication in the model object
			//    the rest adapter will know what to do, save or update based
			//    on the existence of the model id
			deviceModel.authSave({
				success : function(_model, _response) {
					// log the output
					console.log("deviceModel.update: " + JSON.stringify(_model, null, 2));

					// this will cause the UI to update to reflect the changes
					var collection = Alloy.Collections.instance("device");
					collection.getAll({});
				},
				error : function(_model, _response) {
					// log an error
					console.log("Error- deviceModel.update " + JSON.stringify(_response, null, 2));
				}
			});
		},
		error : function(_model, _response) {
			// log an error
			console.log("Error- deviceModel.update when fetching " + _model);
		}
	});

}

/**
 *
 * @param {Object} evt
 */
function doOpen(evt) {
	if (OS_ANDROID) {
	}
}

/**
 * used to transform the model for easier output on the UI.
 *
 * this specifically was need to get the last modified date and the
 * creation date.
 *
 * be sure to require moment.js in the controller
 *
 *    var moment = require('moment');
 *
 * @param {Object} _model
 */
function transform(_model) {
	var transform = _model.toJSON();
	return {
		first_col : transform.first_col,
		second_col : transform.second_col,

		// format the date using moment library
		lastModified : moment(transform._kmd.lmt).format('MMMM Do YYYY, h:mm:ss a'),
	};
}

//
// Need to handle opening the windows based on the platform
// Since on IOS we need the NavigationWindow opened first and
// on android we do not.
if (OS_IOS) {
	Alloy.Globals.navWindow = $.getView();

	Alloy.Globals.navWindow.open();
} else {
	$.getView().open();
}
//
Alloy.Collections.instance("device").on('sync', function(_model) {
	alert('collection has been changed ' + JSON.stringify(_model));
});

sampleOfUpdatingAModel();

<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Controller.extend({

  numberOfLines: 4,   // The amount of lines currently displayed on screen
  textRows: 18,       // Number of Rows the Terminal Window can hold
  commandHistory: [
    {message: "Hello, My name is Johnathan Brunelle."},
    {message: "I am an Electrical Computer Engineering Student in my second"},
    {message: "year at the University of Western Ontario."},
    {message: "Enter 'help' to view the commands."}],

  init: function () {

    this.set('textBuffer', '> ');
  },

  /**
   * Ensures that text does not run off the terminal window
   * @param historyList current text displayed
   */
  checkLines: function (historyList) {

    if (this.get('numberOfLines') > this.get('textRows')) {

      // Shift the queue a certain amount
      let difference = this.get('numberOfLines') - this.get('textRows');

      for (var i = 0; i < difference; i++) {
        this.get('commandHistory').set('commandHistory', historyList.shift());
      }

      this.set('numberOfLines', this.get('textRows'));
    }
  },

  openExternalPage: function (page) {
    var pages = {
      github : 'https://github.com/JhnBrunelle',
      linkedin: 'https://www.linkedin.com/in/johnbrunelleece'
    };
    window.open(pages[page]);
  },
  /**
   * Process the user input, pointing it to correct function
   * and providing a response
   * @param cmnd user command
   */
  registerCommand: function (cmnd) {
    var historyList = this.get("commandHistory");

    // Used for debugging
    switch (cmnd) {
      case "> help":
      case "> ls":
        this.set("numberOfLines", this.get("numberOfLines") + 8);
        this.checkLines(historyList);
        historyList.pushObject({message: cmnd});
        historyList.pushObject({message: "Help Menu"});
        historyList.pushObject({message: "  clear - Clear terminal window"});
        historyList.pushObject({message: "  about - Info about me"});
        historyList.pushObject({message: "  degree - Display Degree Info"});
        historyList.pushObject({message: "  github - Open Github Page"});
        historyList.pushObject({message: "  linkedin - Open Linkedin Page"});
        historyList.pushObject({message: "  contact - Display Contact Info"});
        break;

      case "> clear":
        this.set('commandHistory', []);
        this.set('numberOfLines', 0);
        break;

      case "> stabilitycheck":    // Used for Debugging
        console.log("commandHistory: " + this.get('commandHistory').length);
        console.log("numberOfLines:  " + this.get('numberOfLines'));

        this.set("numberOfLines", this.get("numberOfLines") + 2);
        this.checkLines(historyList);
        historyList.pushObject({message: cmnd});
        historyList.pushObject({message: "Stability Checked! View Console!"});
        break;

      case "> contact":    // Used for Debugging
        console.log("commandHistory: " + this.get('commandHistory').length);
        console.log("numberOfLines:  " + this.get('numberOfLines'));

        this.set("numberOfLines", this.get("numberOfLines") + 3);
        this.checkLines(historyList);
        historyList.pushObject({message: cmnd});
        historyList.pushObject({message: "Phone - (226)700-3655"});
        historyList.pushObject({message: "Email - jhnbrunelle@gmail.com"});
        break;

      case "> github":
        this.set("numberOfLines", this.get("numberOfLines") + 2);
        this.checkLines(historyList);
        historyList.pushObject({message: cmnd});
        this.openExternalPage("github");
        historyList.pushObject({message: "Github opened!"});
        break;

      case "> linkedin":
        this.set("numberOfLines", this.get("numberOfLines") + 2);
        this.checkLines(historyList);
        historyList.pushObject({message: cmnd});
        this.openExternalPage("linkedin");
        historyList.pushObject({message: "Linkedin opened!"});
        break;

      case "> degree":    // States my Degree
        this.set("numberOfLines", this.get("numberOfLines") + 5);
        this.checkLines(historyList);
        historyList.pushObject({message: cmnd});
        historyList.pushObject({message: "University Of Western Ontario"});
        historyList.pushObject({message: "Bachelor of Engineering Science (BESc) in Computer Engineering"});
        historyList.pushObject({message: "With specialty in Electronics"});
        historyList.pushObject({message: "GPA: 3.9, Class of 2019"});
        break;

      default:
        this.set("numberOfLines", this.get("numberOfLines") + 2);
        this.checkLines(historyList);
        historyList.pushObject({message: cmnd});
        historyList.pushObject({message: "jsh: " + cmnd + ": command not found"});
        break;

    }

  },

  actions: {

    /**
     * Handlees input from console command line
     * @param text User Input
     */
    inputLineHandler: function (text) {
      this.registerCommand(text);
      this.set('textBuffer', '> ');
    }
  }
});
<commit_msg>gjygjhhjjh<commit_after>import Ember from 'ember';

export default Ember.Controller.extend({

  numberOfLines: 4,   // The amount of lines currently displayed on screen
  textRows: 18,       // Number of Rows the Terminal Window can hold
  commandHistory: [
    {message: "Hello, My name is Johnathan Brunelle."},
    {message: "I am an Electrical Computer Engineering Student in my second"},
    {message: "year at the University of Western Ontario."},
    {message: "Enter 'help' to view the commands."}],

  init: function () {

    this.set('textBuffer', '> ');
  },

  /**
   * Ensures that text does not run off the terminal window
   * @param historyList current text displayed
   */
  checkLines: function (historyList) {

    if (this.get('numberOfLines') > this.get('textRows')) {

      // Shift the queue a certain amount
      let difference = this.get('numberOfLines') - this.get('textRows');

      for (var i = 0; i < difference; i++) {
        this.get('commandHistory').set('commandHistory', historyList.shift());
      }

      this.set('numberOfLines', this.get('textRows'));
    }
  },

  openExternalPage: function (page) {
    var pages = {
      github : 'https://github.com/JhnBrunelle',
      linkedin: 'https://www.linkedin.com/in/johnbrunelleece'
    };
    window.open(pages[page]);
  },
  /**
   * Process the user input, pointing it to correct function
   * and providing a response
   * @param cmnd user command
   */
  registerCommand: function (cmnd) {
    var historyList = this.get("commandHistory");

    // Used for debugging
    switch (cmnd) {
      case "> help":
      case "> ls":
        this.set("numberOfLines", this.get("numberOfLines") + 8);
        this.checkLines(historyList);
        historyList.pushObject({message: cmnd});
        historyList.pushObject({message: "Help Menu"});
        historyList.pushObject({message: "  clear - Clear terminal window"});
        historyList.pushObject({message: "  about - Info about me"});
        historyList.pushObject({message: "  degree - Display Degree Info"});
        historyList.pushObject({message: "  github - Open Github Page"});
        historyList.pushObject({message: "  linkedin - Open Linkedin Page"});
        historyList.pushObject({message: "  contact - Display Contact Info"});
        break;

      case "> clear":
        this.set('commandHistory', []);
        this.set('numberOfLines', 0);
        break;

      case "> stabilitycheck":    // Used for Debugging
        console.log("commandHistory: " + this.get('commandHistory').length);
        console.log("numberOfLines:  " + this.get('numberOfLines'));

        this.set("numberOfLines", this.get("numberOfLines") + 2);
        this.checkLines(historyList);
        historyList.pushObject({message: cmnd});
        historyList.pushObject({message: "Stability Checked! View Console!"});
        break;

      case "> contact":    // Used for Debugging
        console.log("commandHistory: " + this.get('commandHistory').length);
        console.log("numberOfLines:  " + this.get('numberOfLines'));

        this.set("numberOfLines", this.get("numberOfLines") + 2);
        this.checkLines(historyList);
        historyList.pushObject({message: cmnd});
        historyList.pushObject({message: "Email - jhnbrunelle@gmail.com"});
        break;

      case "> github":
        this.set("numberOfLines", this.get("numberOfLines") + 2);
        this.checkLines(historyList);
        historyList.pushObject({message: cmnd});
        this.openExternalPage("github");
        historyList.pushObject({message: "Github opened!"});
        break;

      case "> linkedin":
        this.set("numberOfLines", this.get("numberOfLines") + 2);
        this.checkLines(historyList);
        historyList.pushObject({message: cmnd});
        this.openExternalPage("linkedin");
        historyList.pushObject({message: "Linkedin opened!"});
        break;

      case "> degree":    // States my Degree
        this.set("numberOfLines", this.get("numberOfLines") + 5);
        this.checkLines(historyList);
        historyList.pushObject({message: cmnd});
        historyList.pushObject({message: "University Of Western Ontario"});
        historyList.pushObject({message: "Bachelor of Engineering Science (BESc) in Computer Engineering"});
        historyList.pushObject({message: "With specialty in Electronics"});
        historyList.pushObject({message: "GPA: 3.9, Class of 2019"});
        break;

      default:
        this.set("numberOfLines", this.get("numberOfLines") + 2);
        this.checkLines(historyList);
        historyList.pushObject({message: cmnd});
        historyList.pushObject({message: "jsh: " + cmnd + ": command not found"});
        break;

    }

  },

  actions: {

    /**
     * Handlees input from console command line
     * @param text User Input
     */
    inputLineHandler: function (text) {
      this.registerCommand(text);
      this.set('textBuffer', '> ');
    }
  }
});
<|endoftext|>