gancio-upstream/server/api/controller/export.js

73 lines
2 KiB
JavaScript
Raw Normal View History

2019-07-03 16:33:03 +02:00
const { event: Event, place: Place, tag: Tag } = require('../models')
2019-04-03 00:25:12 +02:00
const { Op } = require('sequelize')
const moment = require('moment')
2019-09-17 18:16:59 +02:00
const config = require('config')
2019-04-03 00:25:12 +02:00
const ics = require('ics')
const exportController = {
2019-09-11 19:12:24 +02:00
async export (req, res) {
2019-04-03 00:25:12 +02:00
const type = req.params.type
const tags = req.query.tags
const places = req.query.places
2019-07-03 16:33:03 +02:00
2019-06-26 14:44:21 +02:00
const where = {}
const yesterday = moment().subtract('1', 'day').unix()
2019-07-03 16:33:03 +02:00
let where_tags = {}
2019-04-03 00:25:12 +02:00
if (tags) {
2019-07-03 16:33:03 +02:00
where_tags = { where: { tag: tags.split(',') } }
2019-04-03 00:25:12 +02:00
}
2019-07-03 16:33:03 +02:00
2019-04-03 00:25:12 +02:00
if (places) {
2019-06-26 14:44:21 +02:00
where.placeId = places.split(',')
2019-04-03 00:25:12 +02:00
}
2019-09-17 18:16:59 +02:00
2019-04-03 00:25:12 +02:00
const events = await Event.findAll({
2019-05-30 12:12:51 +02:00
order: ['start_datetime'],
2019-06-07 17:02:33 +02:00
where: {
is_visible: true,
2019-05-30 12:12:51 +02:00
start_datetime: { [Op.gte]: yesterday },
2019-06-26 14:44:21 +02:00
...where
2019-05-30 12:12:51 +02:00
},
2019-07-03 16:33:03 +02:00
include: [ { model: Tag, ...where_tags }, { model: Place, attributes: ['name', 'id', 'address'] }]
2019-04-03 00:25:12 +02:00
})
2019-04-03 00:25:12 +02:00
switch (type) {
2019-09-17 18:16:59 +02:00
case 'rss':
2019-04-03 00:25:12 +02:00
case 'feed':
return exportController.feed(res, events.slice(0, 20))
case 'ics':
return exportController.ics(res, events)
case 'json':
return res.json(events)
2019-04-03 00:25:12 +02:00
}
},
2019-09-11 19:12:24 +02:00
feed (res, events) {
2019-04-03 00:25:12 +02:00
res.type('application/rss+xml; charset=UTF-8')
2019-09-17 18:16:59 +02:00
res.render('feed/rss.pug', { events, config, moment })
2019-04-03 00:25:12 +02:00
},
2019-09-11 19:12:24 +02:00
ics (res, events) {
2019-04-03 00:25:12 +02:00
const eventsMap = events.map(e => {
2019-10-02 16:00:51 +02:00
const tmpStart = moment.unix(e.start_datetime).utc(false)
const tmpEnd = moment.unix(e.end_datetime).utc(false)
2019-04-03 00:25:12 +02:00
const start = [tmpStart.year(), tmpStart.month() + 1, tmpStart.date(), tmpStart.hour(), tmpStart.minute()]
const end = [tmpEnd.year(), tmpEnd.month() + 1, tmpEnd.date(), tmpEnd.hour(), tmpEnd.minute()]
return {
start,
end,
title: e.title,
description: e.description,
location: e.place.name + ' ' + e.place.address
}
})
res.type('text/calendar; charset=UTF-8')
const { error, value } = ics.createEvents(eventsMap)
res.send(value)
}
}
module.exports = exportController