var bodyParser = require('body-parser') var mongoose = require('mongoose') var path = require('path') mongoose.Promise = require('bluebird') var socketIO = require('socket.io') var exec = require('child_process').exec function AWPrint (options) { if (!(this instanceof AWPrint)) return new AWPrint(options) options = options || {} if (!options.express) throw new Error('Express not provided to AWPrint'); if (!options.config) throw new Error('Configuration not provided to AWPrint'); var express = options.express var router = express.Router() var config = options.config var io; var db, Print db = mongoose.connect(config.mongodbUrl) mongoose.connection.on('error', (err) => { console.error("failed to start mongo!", err) }) var printSchema = new db.Schema({ url: { type: mongoose.Schema.Types.String, required: true, }, printed: { type: mongoose.Schema.Types.Boolean, }, date: { type: mongoose.Schema.Types.Date, }, }) var Print = db.model('Print', printSchema) router.use('/public/', express.static(path.join(__dirname, './public'))) router.get('/', function (req, res) { res.sendFile(path.join(__dirname, 'public/index.html')) }) router.get('/index', function (req, res) { Print.find({}).sort('-date').limit(40).exec(function(err, docs) { res.json(docs) }) }) router.post('/add', bodyParser.json({}), function (req, res) { var data = { url: req.body.url, printed: false, date: Date.now() } res.sendStatus(200) new Print(data).save().then( (job) => { io && io.emit('job', job) }).catch( (err) => { // idk }) }) router.post('/print', bodyParser.json({}), function (req, res) { res.sendStatus(200) Print.findOne({ _id: req.body._id }).then( (job) => { job.printed = true var cmd = 'curl ' + job.url + ' | lpr -P ARMORYHPM553 -o page-top=28 -o page-left=23 -o page-right=23 -o page-bottom=0 -o media=a4' console.log(cmd) exec(cmd, function(error, stdout, stderr) { console.log('ok') }) return job.save() }).catch( (err) => { console.log('error saving?') }) }) this._router = router // defer until the app is mounted setImmediate(function(){ io = socketIO(options.app._server) io.on('connection', function(socket){ // ... }) }) } AWPrint.prototype.middleware = function () { return this._router } module.exports = AWPrint