1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
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'
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
|