first commit backend

This commit is contained in:
lesion
2019-02-26 00:02:42 +01:00
commit 887157f2a9
27 changed files with 819 additions and 0 deletions

74
app/controller/bot.js Normal file
View File

@@ -0,0 +1,74 @@
const jwt = require('jsonwebtoken')
const { User, Event, Comment, Tag } = require('../model')
const config = require('../config')
const mail = require('../mail')
const Mastodon = require('mastodon-api')
const Sequelize = require('sequelize')
const Op = Sequelize.Op
const moment = require('moment')
moment.locale('it')
const botController = {
bots: [],
async initialize() {
console.log('initialize bots')
const botUsers = await User.findAll({where: { mastodon_auth: { [Op.ne]: null }}})
console.log(botUsers)
botController.bots = botUsers.map(user => {
console.log('initialize bot ', user.name)
console.log('.. ', user.mastodon_auth)
const { client_id, client_secret, access_token } = user.mastodon_auth
const bot = new Mastodon({ access_token, api_url: `https://${user.instance}/api/v1/` })
console.log(bot)
const listener = bot.stream('streaming/direct')
listener.on('message', botController.message)
listener.on('error', botController.error)
return {email: user.email, bot}
})
console.log(botController.bots)
},
add (user) {
const bot = new Mastodon({ access_token: user.mastodon_auth.access_token, api_url: `https://${user.instance}/api/v1/` })
const listener = bot.stream('streaming/direct')
listener.on('message', botController.message)
listener.on('error', botController.error)
botController.bots.push({ email: user.email, bot})
},
post(user, event) {
const { bot } = botController.bots.filter(b => b.email === user.email)[0]
const status = `${event.title} @ ${event.place.name} ${moment(event.start_datetime).format('ddd, D MMMM HH:mm')} -
${event.description} - ${event.tags.map(t => '#'+t.tag).join(' ')} ${config.baseurl}/event/${event.id}`
return bot.post('/statuses', { status, visibility: 'private' })
},
async message (msg) {
console.log(msg)
console.log(msg.data.accounts)
const replyid = msg.data.in_reply_to_id || msg.data.last_status.in_reply_to_id
if (!replyid) return
const event = await Event.findOne( {where: {activitypub_id: replyid}} )
if (!event) {
// check for comment..
const comment = await Comment.findOne( {where: { }})
}
const comment = await Comment.create({activitypub_id: msg.data.last_status.id, text: msg.data.last_status.content, author: msg.data.accounts[0].username })
event.addComment(comment)
console.log(event)
// const comment = await Comment.findOne( { where: {activitypub_id: msg.data.in_reply_to}} )
// console.log('dentro message ', data)
return
// add comment to specified event
// let comment
//if (!event) {
//const comment = await Comment.findOne({where: {activitypub_id: req.body.id}, include: Event})
//event = comment.event
//}
//const comment = new Comment(req.body)
//event.addComment(comment)
},
error (err) {
console.log('error ', err)
}
}
setTimeout(botController.initialize, 2000)
module.exports = botController

70
app/controller/event.js Normal file
View File

@@ -0,0 +1,70 @@
const jwt = require('jsonwebtoken')
const { User, Event, Comment, Tag, Place } = require('../model')
const config = require('../config')
const mail = require('../mail')
const moment = require('moment')
const Sequelize = require('sequelize')
const eventController = {
async addComment (req, res) {
// comment could be added to an event or to another comment
let event = await Event.findOne({where: {activitypub_id: req.body.id}})
if (!event) {
const comment = await Comment.findOne({where: {activitypub_id: req.body.id}, include: Event})
event = comment.event
}
const comment = new Comment(req.body)
event.addComment(comment)
res.json(comment)
},
// async boost (req, res) {
// const event = await Event.findById(req.body.id)
// req.user.addBoost(event)
// res.status(200)
// },
async getMeta(req, res) {
const places = await Place.findAll()
const tags = await Tag.findAll()
res.json({tags, places})
},
async updateTag (req, res) {
const tag = await Tag.findByPk(req.body.tag)
console.log(tag)
if (tag) {
res.json(await tag.update(req.body))
} else {
res.send(404)
}
},
async get(req, res) {
const id = req.params.event_id
const event = await Event.findByPk(id, { include: [User, Tag, Comment, Place]})
res.json(event)
},
async getAll (req, res) {
const start = moment().year(req.params.year).month(req.params.month).startOf('month').subtract(1, 'week')
const end = moment().year(req.params.year).month(req.params.month).endOf('month').add(1, 'week')
console.log('start', start)
console.log('end', end)
const events = await Event.findAll({
where: {
[Sequelize.Op.and]: [
{ start_datetime: { [Sequelize.Op.gte]: start } },
{ start_datetime: { [Sequelize.Op.lte]: end } }
]
},
order: [['createdAt', 'ASC']],
include: [User, Comment, Tag, Place]
})
res.json(events)
},
}
module.exports = eventController

45
app/controller/export.js Normal file
View File

@@ -0,0 +1,45 @@
const jwt = require('jsonwebtoken')
const { User, Event, Comment, Tag, Place } = require('../model')
const config = require('../config')
const mail = require('../mail')
const moment = require('moment')
const Sequelize = require('sequelize')
const ics = require('ics')
const exportController = {
async getAll (req, res) {
const events = await Event.findAll({
where: {
[Sequelize.Op.and]: [
{ start_datetime: { [Sequelize.Op.gte]: start } },
{ start_datetime: { [Sequelize.Op.lte]: end } }
]
},
order: [['createdAt', 'DESC']],
include: [User, Comment, Tag, Place]
})
res.json(events)
},
async feed (req, res) {
const events = await Event.findAll({include: [Comment, Tag, Place]})
res.type('application/rss+xml; charset=UTF-8')
res.render('feed/rss.pug', {events, config, moment})
},
async ics (req, res) {
const events = await Event.findAll({include: [Comment, Tag, Place]})
console.log(events)
const eventsMap = events.map(e => ({
start: [2019, 2, 2],
end: [2019, 2, 3],
title: e.title,
description: e.description,
location: e.place.name
}))
res.type('text/calendar; charset=UTF-8')
const { error, value } = ics.createEvents(eventsMap)
console.log(value)
res.send(value)
}
}
module.exports = exportController

198
app/controller/user.js Normal file
View File

@@ -0,0 +1,198 @@
const jwt = require('jsonwebtoken')
const Mastodon = require('mastodon-api')
const User = require('../models/user')
const { Event, Tag, Place } = require('../models/event')
const config = require('../config')
const mail = require('../mail')
const bot = require('./bot')
const userController = {
async login (req, res) {
// find the user
const user = await User.findOne({where: { email: req.body.email }})
if (!user) {
res.status(404).json({ success: false, message: 'AUTH_FAIL' })
} else if (user) {
if (!user.is_active) {
res.status(403).json({success: false, message: 'NOT)CONFIRMED'})
}
// check if password matches
else if (!await user.comparePassword(req.body.password)) {
res.status(403).json({ success: false, message: 'AUTH_FAIL' })
} else {
// if user is found and password is right
// create a token
const payload = { email: user.email }
var token = jwt.sign(payload, config.secret)
res.json({
success: true,
message: 'Enjoy your token!',
token,
user
})
}
}
},
async setToken (req, res) {
req.user.mastodon_auth = req.body
await req.user.save()
res.json(req.user)
},
async delEvent (req, res) {
//check if event is mine
const event = await Event.findByPk(req.params.id)
if (event && (req.user.is_admin || req.user.id === event.userId))
{
await event.destroy()
res.sendStatus(200)
} else {
res.sendStatus(404)
}
},
async addEvent (req, res, next) {
const body = req.body
const eventDetails = {
title: body.title,
description: body.description,
multidate: body.multidate,
start_datetime: body.start_datetime,
end_datetime: body.end_datetime
}
if (req.file) {
eventDetails.image_path = req.file.path
}
//create place
let place
try {
place = await Place.findOrCreate({where: {name: body.place_name},
defaults: {address: body.place_address }})
.spread((place, created) => place)
} catch(e) {
console.log(e)
}
let event = await Event.create(eventDetails)
await event.setPlace(place)
// create/assign tags
console.log(body.tags)
if (body.tags) {
await Tag.bulkCreate(body.tags.map(t => ({ tag: t})), {ignoreDuplicates: true})
const tags = await Tag.findAll({where: { tag: body.tags }})
await event.addTags(tags)
}
await req.user.addEvent(event)
event = await Event.findByPk(event.id, {include: [User, Tag, Place]})
// check if bot exists
if (req.user.mastodon_auth) {
const post = await bot.post(req.user, event)
}
return res.json(event)
},
async updateEvent (req, res) {
const body = req.body
const event = await Event.findByPk(body.id)
await event.update(body)
let place
try {
place = await Place.findOrCreate({where: {name: body.place_name},
defaults: {address: body.place_address }})
.spread((place, created) => place)
} catch(e) {
console.log('catch', e)
}
await event.setPlace(place)
await event.setTags([])
console.log(body.tags)
if (body.tags) {
await Tag.bulkCreate(body.tags.map(t => ({ tag: t})), {ignoreDuplicates: true})
const tags = await Tag.findAll({where: { tag: body.tags }})
await event.addTags(tags)
}
const newEvent = await Event.findByPk(event.id, {include: [User, Tag, Place]})
// check if bot exists
if (req.user.mastodon_auth) {
const post = await bot.post(req.user, newEvent)
}
return res.json(newEvent)
},
async getMyEvents (req, res) {
const events = await req.user.getEvents()
res.json(events)
},
async getAuthURL (req, res) {
const instance = req.body.instance
const { client_id, client_secret } = await Mastodon.createOAuthApp(`https://${instance}/api/v1/apps`, 'eventi', 'read write', `${config.baseurl}/settings`)
const url = await Mastodon.getAuthorizationUrl(client_id, client_secret, `https://${instance}`, 'read write', `${config.baseurl}/settings`)
console.log(req.user)
req.user.instance = instance
req.user.mastodon_auth = { client_id, client_secret }
await req.user.save()
res.json(url)
},
async code (req, res) {
const code = req.body.code
const { client_id, client_secret } = req.user.mastodon_auth
const instance = req.user.instance
try {
const token = await Mastodon.getAccessToken(client_id, client_secret, code, `https://${instance}`, '${config.baseurl}/settings')
const mastodon_auth = { client_id, client_secret, access_token: token}
req.user.mastodon_auth = mastodon_auth
await req.user.save()
await botController.add(token)
res.json(req.user)
} catch (e) {
res.json(e)
}
},
async current (req, res) {
res.json(req.user)
},
async getAll (req, res) {
const users = await User.findAll({
order: [['createdAt', 'DESC']]
})
res.json(users)
},
async update (req, res) {
const user = await User.findByPk(req.body.id)
if (user) {
await user.update(req.body)
res.json(user)
} else {
res.send(400)
}
},
async register (req, res) {
try {
req.body.is_active = false
const user = await User.create(req.body)
try {
mail.send(user.email, 'register', { user })
} catch (e) {
console.log(e)
return res.status(400).json(e)
}
const payload = { email: user.email }
const token = jwt.sign(payload, config.secret)
res.json({ user, token })
} catch (e) {
res.status(404).json(e)
}
}
}
module.exports = userController