summaryrefslogtreecommitdiff
path: root/lib/awprint/index.js
blob: dec43fd3ce6e93d0c4bc275be78fdef40cd6389b (plain)
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
var bodyParser = require('body-parser')
var mongoose = require('mongoose')
var path = require('path')
mongoose.Promise = require('bluebird')
var socketIO = require('socket.io')

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.update({ _id: req.body._id }, { printed: true, }).then( (req) => {
      // send a websocket message?
    }).catch( (err) => {
      // idk
    })
  })

  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