summaryrefslogtreecommitdiff
path: root/server.js
blob: 7fd73f05a76f448f37d06b82206f712b47f0b2d7 (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
const express = require('express')
const app = express()

const redis = require('redis')
const client = redis.createClient(process.env.REDIS_URL)

const request = require('request')
const aws = require('aws-sdk')
const s3 = new aws.S3()

function fetchImages() {
  request('http://map.govmap.gov.il/rainradar/radar.json', (error, response, body) => {
    var res = JSON.parse(body)
    for (let size of ['images140', 'images280']) {
      var imgs = res[size]
      Object.keys(imgs).forEach(function (img) {
        const ts = img.split(':')
        const url = 'http://' + imgs[img]
        const key = `fetched:${url}`
        client.get(key, (err, reply) => {
          if (!reply && reply != 'fetching') {
            client.set(key, 'fetching')
            request({ url: url, encoding: null }, (error, response, body) => {
              if (err) {
                console.log(err)
                client.del(key)
              }
              else {
                const d = ts.slice(0, 3).join('')
                const t = ts.slice(3, 5).join('')
                console.log(`Uploading ${url} to bucket`)
                s3.putObject({
                  Bucket: 'imgs.geshem.space',
                  Key: `${d}_${t}.png`,
                  ContentType: response.headers['content-type'],
                  ContentLength: response.headers['content-length'],
                  Body: body
                }, (err, data) => {
                  if (err) {
                    console.log(err)
                    client.del(key)
                  }
                  else {
                    client.set(key, data.ETag.slice(1, -1))
                  }
                })
              }
            })
          }
        })
      })
    }
  })
}

app.set('view engine', 'pug')

app.use('/static', express.static('static'))

app.use('/', function(req, res, next){
  res.on('finish', function(){
    console.log('hello world!')
  })
  next()
});

app.get('/', function (req, res) {
  res.render('index', { prod: process.env.NODE_ENV === 'production' })
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
  fetchImages()
})