pm2 / cron worker to send reminder

This commit is contained in:
lesion 2019-03-10 01:01:23 +01:00
parent e41de7208c
commit 6ed639d94b
39 changed files with 264 additions and 105 deletions

View file

@ -4,15 +4,17 @@ FROM node:10
WORKDIR /usr/src/app WORKDIR /usr/src/app
COPY package.json . COPY package.json .
COPY pm2.json .
# install backend dependencies # install backend dependencies
RUN yarn RUN yarn --prod
# copy source # copy source
COPY . . COPY app app/
COPY client client/
# install nodemon # install nodemon
RUN yarn global add nodemon RUN yarn global add pm2
WORKDIR /usr/src/app/client WORKDIR /usr/src/app/client
@ -26,4 +28,4 @@ WORKDIR /usr/src/app
EXPOSE 12300 EXPOSE 12300
CMD [ "yarn", "run", "serve" ] CMD [ "pm2-runtime", "start", "pm2.json" ]

View file

@ -4,16 +4,10 @@ const eventController = require('./controller/event')
const exportController = require('./controller/export') const exportController = require('./controller/export')
const userController = require('./controller/user') const userController = require('./controller/user')
// const botController = require('./controller/bot') // const botController = require('./controller/bot')
const path = require('path')
const multer = require('multer') const multer = require('multer')
const crypto = require('crypto')
const storage = require('./storage')({ const storage = require('./storage')({
destination: 'uploads/', destination: 'uploads/'
filename: (req, file, cb) => {
cb(null, crypto.randomBytes(16).toString('hex') + path.extname(file.originalname))
}
}) })
const upload = multer({ storage }) const upload = multer({ storage })
const api = express.Router() const api = express.Router()

View file

@ -1,26 +1,24 @@
const jwt = require('jsonwebtoken') const jwt = require('jsonwebtoken')
const config = require('./config') const config = require('./config')
const User = require('./models/user') const User = require('./models/user')
const { Op } = require('sequelize')
const Auth = { const Auth = {
async fillUser (req, res, next) { async fillUser (req, res, next) {
const token = req.body.token || req.params.token || req.headers['x-access-token'] const token = req.body.token || req.params.token || req.headers['x-access-token']
console.log('[AUTH] ', token) if (!token) return next()
if (!token) next()
jwt.verify(token, config.secret, async (err, decoded) => { jwt.verify(token, config.secret, async (err, decoded) => {
if (err) next() if (err) return next()
req.user = await User.findOne({ where: { email: decoded.email, is_active: true } }) req.user = await User.findOne({ where: { email: { [Op.eq]: decoded.email }, is_active: true } })
next() next()
}) })
}, },
async isAuth (req, res, next) { async isAuth (req, res, next) {
const token = req.body.token || req.params.token || req.headers['x-access-token'] const token = req.body.token || req.params.token || req.headers['x-access-token']
console.log('[AUTH] ', token)
if (!token) return res.status(403).send({ message: 'Token not found' }) if (!token) return res.status(403).send({ message: 'Token not found' })
jwt.verify(token, config.secret, async (err, decoded) => { jwt.verify(token, config.secret, async (err, decoded) => {
if (err) return res.status(403).send({ message: 'Failed to authenticate token ' + err }) if (err) return res.status(403).send({ message: 'Failed to authenticate token ' + err })
console.log('DECODED TOKEN', decoded) req.user = await User.findOne({ where: { email: { [Op.eq]: decoded.email }, is_active: true } })
req.user = await User.findOne({ where: { email: decoded.email, is_active: true } })
if (!req.user) return res.status(403).send({ message: 'Failed to authenticate token ' + err }) if (!req.user) return res.status(403).send({ message: 'Failed to authenticate token ' + err })
next() next()
}) })

View file

@ -20,9 +20,9 @@ if (process.env.NODE_ENV === 'production') {
} }
module.exports = { module.exports = {
locale: 'en', locale: 'it',
title: process.env.TITLE || 'Put here your site name', title: process.env.TITLE || 'GANCIO',
description: process.env.DESCRIPTION || 'A calendar for radical communities', description: process.env.DESCRIPTION || 'A calendar for radical communities',
baseurl: process.env.BASE_URL || 'http://localhost:8080', baseurl: process.env.BASE_URL || 'http://localhost:8080',

View file

@ -1,14 +1,14 @@
const { User, Event, Comment, Tag, Place, MailReminder } = require('../model') const { User, Event, Comment, Tag, Place, Reminder } = require('../model')
const moment = require('moment') const moment = require('moment')
const Sequelize = require('sequelize') const { Op } = require('sequelize')
const lodash = require('lodash')
const eventController = { const eventController = {
async addComment (req, res) { async addComment (req, res) {
// comment could be added to an event or to another comment // comment could be added to an event or to another comment
let event = await Event.findOne({ where: { activitypub_id: req.body.id } }) let event = await Event.findOne({ where: { activitypub_id: { [Op.eq]: req.body.id } } })
if (!event) { if (!event) {
const comment = await Comment.findOne({ where: { activitypub_id: req.body.id }, include: Event }) const comment = await Comment.findOne({ where: { activitypub_id: { [Op.eq]: req.body.id } }, include: Event })
event = comment.event event = comment.event
} }
const comment = new Comment(req.body) const comment = new Comment(req.body)
@ -23,6 +23,26 @@ const eventController = {
res.json({ tags, places }) res.json({ tags, places })
}, },
async getReminders (event) {
function match (event, filters) {
// matches if no filter specified
if (!filters.tags.length && !filters.places.length) return true
if (filters.tags.length) {
const m = lodash.intersection(event.tags.map(t => t.tag), filters.tags)
if (m.length > 0) return true
}
if (filters.places.length) {
if (filters.places.find(p => p === event.place.name)) {
return true
}
}
}
const reminders = await Reminder.findAll()
// get reminder that matches with selected event
return reminders.filter(reminder => match(event, reminder.filters))
},
async updateTag (req, res) { async updateTag (req, res) {
const tag = await Tag.findByPk(req.body.tag) const tag = await Tag.findByPk(req.body.tag)
console.log(tag) console.log(tag)
@ -68,8 +88,12 @@ const eventController = {
}, },
async addReminder (req, res) { async addReminder (req, res) {
await MailReminder.create(req.body.reminder) try {
res.json(200) await Reminder.create(req.body)
res.sendStatus(200)
} catch (e) {
res.sendStatus(404)
}
}, },
async getAll (req, res) { async getAll (req, res) {
const start = moment().year(req.params.year).month(req.params.month).startOf('month').subtract(1, 'week') const start = moment().year(req.params.year).month(req.params.month).startOf('month').subtract(1, 'week')
@ -77,9 +101,9 @@ const eventController = {
const events = await Event.findAll({ const events = await Event.findAll({
where: { where: {
is_visible: true, is_visible: true,
[Sequelize.Op.and]: [ [Op.and]: [
{ start_datetime: { [Sequelize.Op.gte]: start } }, { start_datetime: { [Op.gte]: start } },
{ start_datetime: { [Sequelize.Op.lte]: end } } { start_datetime: { [Op.lte]: end } }
] ]
}, },
order: [['start_datetime', 'ASC']], order: [['start_datetime', 'ASC']],

View file

@ -1,5 +1,5 @@
const { Event, Comment, Tag, Place } = require('../model') const { Event, Comment, Tag, Place } = require('../model')
const Sequelize = require('sequelize') const { Op } = require('sequelize')
const config = require('../config') const config = require('../config')
const moment = require('moment') const moment = require('moment')
const ics = require('ics') const ics = require('ics')
@ -21,7 +21,7 @@ const exportController = {
} }
const events = await Event.findAll({ const events = await Event.findAll({
order: [['start_datetime', 'ASC']], order: [['start_datetime', 'ASC']],
where: { start_datetime: { [Sequelize.Op.gte]: yesterday } }, where: { start_datetime: { [Op.gte]: yesterday } },
include: [Comment, { include: [Comment, {
model: Tag, model: Tag,
where: whereTag where: whereTag

View file

@ -3,14 +3,16 @@ const Mastodon = require('mastodon-api')
const User = require('../models/user') const User = require('../models/user')
const { Event, Tag, Place } = require('../models/event') const { Event, Tag, Place } = require('../models/event')
const eventController = require('./event')
const config = require('../config') const config = require('../config')
const mail = require('../mail') const mail = require('../mail')
const bot = require('./bot') const bot = require('./bot')
const { Op } = require('sequelize')
const userController = { const userController = {
async login (req, res) { async login (req, res) {
// find the user // find the user
const user = await User.findOne({ where: { email: req.body.email } }) const user = await User.findOne({ where: { email: { [Op.eq]: req.body.email } } })
if (!user) { if (!user) {
res.status(404).json({ success: false, message: 'AUTH_FAIL' }) res.status(404).json({ success: false, message: 'AUTH_FAIL' })
} else if (user) { } else if (user) {
@ -82,6 +84,7 @@ const userController = {
} catch (e) { } catch (e) {
console.log(e) console.log(e)
} }
let event = await Event.create(eventDetails) let event = await Event.create(eventDetails)
await event.setPlace(place) await event.setPlace(place)
@ -89,7 +92,7 @@ const userController = {
console.log(body.tags) console.log(body.tags)
if (body.tags) { if (body.tags) {
await Tag.bulkCreate(body.tags.map(t => ({ tag: t })), { ignoreDuplicates: true }) await Tag.bulkCreate(body.tags.map(t => ({ tag: t })), { ignoreDuplicates: true })
const tags = await Tag.findAll({ where: { tag: body.tags } }) const tags = await Tag.findAll({ where: { tag: { [Op.in]: body.tags } } })
await event.addTags(tags) await event.addTags(tags)
} }
if (req.user) await req.user.addEvent(event) if (req.user) await req.user.addEvent(event)
@ -102,7 +105,9 @@ const userController = {
event.save() event.save()
} }
mail.send(config.admin, 'event', { event }) // insert reminder
const reminders = await eventController.getReminders(event)
await event.setReminders(reminders)
return res.json(event) return res.json(event)
}, },
@ -121,7 +126,7 @@ const userController = {
await event.update(body) await event.update(body)
let place let place
try { try {
place = await Place.findOrCreate({ where: { name: body.place_name }, place = await Place.findOrCreate({ where: { name: { [Op.eq]: body.place_name } },
defaults: { address: body.place_address } }) defaults: { address: body.place_address } })
.spread((place, created) => place) .spread((place, created) => place)
} catch (e) { } catch (e) {
@ -132,7 +137,7 @@ const userController = {
console.log(body.tags) console.log(body.tags)
if (body.tags) { if (body.tags) {
await Tag.bulkCreate(body.tags.map(t => ({ tag: t })), { ignoreDuplicates: true }) await Tag.bulkCreate(body.tags.map(t => ({ tag: t })), { ignoreDuplicates: true })
const tags = await Tag.findAll({ where: { tag: body.tags } }) const tags = await Tag.findAll({ where: { tag: { [Op.eq]: body.tags } } })
await event.addTags(tags) await event.addTags(tags)
} }
const newEvent = await Event.findByPk(event.id, { include: [User, Tag, Place] }) const newEvent = await Event.findByPk(event.id, { include: [User, Tag, Place] })

27
app/cron.js Normal file
View file

@ -0,0 +1,27 @@
const mail = require('./mail')
const { Event, Reminder, EventReminder, User, Place, Tag } = require('./model')
async function loop () {
console.log('nel loop')
// get all event reminder in queue
const eventReminders = await EventReminder.findAll()
const promises = eventReminders.map(async e => {
const event = await Event.findByPk(e.eventId, { include: [User, Place, Tag] })
console.log('EVENT ')
console.log(event)
if (!event.place) return
const reminder = await Reminder.findByPk(e.reminderId)
try {
await mail.send(reminder.email, 'event', { event })
} catch (e) {
console.log('DENTRO CATCH!', e)
return false
}
return e.destroy()
})
return Promise.all(promises)
}
setInterval(loop, 20000)
loop()

10
app/emails/event/html.pug Normal file
View file

@ -0,0 +1,10 @@
h3 #{event.title}
p Dove: #{event.place.name} - #{event.place.address}
p Quando: #{datetime(event.start_datetime)}
br
<img style="width: 100%" src="#{config.apiurl}/#{event.image_path}" />
p #{event.description}
<a href="#{config.baseurl}/event/#{event.id}">#{config.baseurl}/event/#{event.id}</a>
hr
<a href="#{config.baseurl}">#{config.title} - #{config.description}</a>

View file

@ -0,0 +1 @@
= `[${config.title}] ${event.title} @${event.place.name} ${datetime(event.start_datetime)}`

View file

@ -1,16 +1,19 @@
const Email = require('email-templates') const Email = require('email-templates')
const path = require('path') const path = require('path')
const config = require('./config') const config = require('./config')
const moment = require('moment')
moment.locale('it')
const mail = { const mail = {
send (addresses, template, locals) { send (addresses, template, locals) {
locals.locale = config.locale locals.locale = config.locale
const email = new Email({ const email = new Email({
views: { root: path.join(__dirname, 'emails') },
juice: true, juice: true,
juiceResources: { juiceResources: {
preserveImportant: true, preserveImportant: true,
webResources: { webResources: {
relativeTo: path.join(__dirname, '..', 'emails') relativeTo: path.join(__dirname, 'emails')
} }
}, },
message: { message: {
@ -26,7 +29,7 @@ const mail = {
to: addresses, to: addresses,
bcc: config.admin bcc: config.admin
}, },
locals locals: { ...locals, config, datetime: datetime => moment(datetime).format('ddd, D MMMM HH:mm') }
}) })
} }
} }

View file

@ -1,4 +1,4 @@
const User = require('./models/user') const User = require('./models/user')
const { Event, Comment, Tag, Place, MailReminder } = require('./models/event') const { Event, Comment, Tag, Place, Reminder, EventReminder } = require('./models/event')
module.exports = { User, Event, Comment, Tag, Place, MailReminder } module.exports = { User, Event, Comment, Tag, Place, Reminder, EventReminder }

View file

@ -24,10 +24,10 @@ const Comment = db.define('comment', {
text: Sequelize.STRING text: Sequelize.STRING
}) })
const MailReminder = db.define('reminder', { const Reminder = db.define('reminder', {
filters: Sequelize.JSON, filters: Sequelize.JSON,
mail: Sequelize.STRING, email: Sequelize.STRING,
send_on_add: Sequelize.BOOLEAN, notify_on_add: Sequelize.BOOLEAN,
send_reminder: Sequelize.BOOLEAN send_reminder: Sequelize.BOOLEAN
}) })
@ -42,10 +42,14 @@ Event.hasMany(Comment)
Event.belongsToMany(Tag, { through: 'tagEvent' }) Event.belongsToMany(Tag, { through: 'tagEvent' })
Tag.belongsToMany(Event, { through: 'tagEvent' }) Tag.belongsToMany(Event, { through: 'tagEvent' })
const EventReminder = db.define('EventReminder')
Event.belongsToMany(Reminder, { through: EventReminder })
Reminder.belongsToMany(Event, { through: EventReminder })
Event.belongsTo(User) Event.belongsTo(User)
Event.belongsTo(Place) Event.belongsTo(Place)
User.hasMany(Event) User.hasMany(Event)
Place.hasMany(Event) Place.hasMany(Event)
module.exports = { Event, Comment, Tag, Place, MailReminder } module.exports = { Event, Comment, Tag, Place, Reminder, EventReminder }

View file

@ -1,21 +1,22 @@
const express = require('express') const express = require('express')
const app = express() const app = express()
const bodyParser = require('body-parser') const bodyParser = require('body-parser')
const api = require('./app/api') const api = require('./api')
const cors = require('cors') const cors = require('cors')
const path = require('path') const path = require('path')
const port = process.env.PORT || 9000 const port = process.env.PORT || 9000
app.set('views', path.join(__dirname, 'views'))
app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json()) app.use(bodyParser.json())
app.use(cors()) app.use(cors())
app.use('/static', express.static(path.join(__dirname, 'uploads'))) app.use('/static', express.static(path.join(__dirname, 'uploads')))
app.use('/uploads', express.static('uploads')) app.use('/uploads', express.static('uploads'))
app.use('/api', api) app.use('/api', api)
app.use('/', express.static(path.join(__dirname, 'client', 'dist'))) app.use('/', express.static(path.join(__dirname, '..', 'client', 'dist')))
app.use('/css', express.static(path.join(__dirname, 'client', 'dist', 'css'))) app.use('/css', express.static(path.join(__dirname, '..', 'client', 'dist', 'css')))
app.use('/js', express.static(path.join(__dirname, 'client', 'dist', 'js'))) app.use('/js', express.static(path.join(__dirname, '..', 'client', 'dist', 'js')))
app.use('*', express.static(path.join(__dirname, 'client', 'dist', 'index.html'))) app.use('*', express.static(path.join(__dirname, '..', 'client', 'dist', 'index.html')))
app.listen(port) app.listen(port)
console.log('Magic happens at http://localhost:' + port) console.log('Magic happens at http://localhost:' + port)

56
app/storage.js Normal file
View file

@ -0,0 +1,56 @@
const fs = require('fs')
const os = require('os')
const path = require('path')
const crypto = require('crypto')
const mkdirp = require('mkdirp')
const sharp = require('sharp')
function getDestination (req, file, cb) {
cb(null, os.tmpdir())
}
function DiskStorage (opts) {
if (typeof opts.destination === 'string') {
mkdirp.sync(opts.destination)
this.getDestination = function ($0, $1, cb) { cb(null, opts.destination) }
} else {
this.getDestination = (opts.destination || getDestination)
}
}
DiskStorage.prototype._handleFile = function _handleFile (req, file, cb) {
var that = this
that.getDestination(req, file, function (err, destination) {
if (err) return cb(err)
const filename = crypto.randomBytes(16).toString('hex') + '.webp'
const finalPath = path.join(destination, filename)
const outStream = fs.createWriteStream(finalPath)
const resizer = sharp().resize(800).webp()
file.stream.pipe(resizer).pipe(outStream)
outStream.on('error', cb)
outStream.on('finish', function () {
cb(null, {
destination,
filename,
path: finalPath,
size: outStream.bytesWritten
})
})
})
}
DiskStorage.prototype._removeFile = function _removeFile (req, file, cb) {
var path = file.path
delete file.destination
delete file.filename
delete file.path
fs.unlink(path, cb)
}
module.exports = function (opts) {
return new DiskStorage(opts)
}

View file

@ -1,3 +1,3 @@
module.exports = { module.exports = {
"extends": "standard" 'extends': 'standard'
}; }

View file

@ -37,7 +37,7 @@
v-icon(name='calendar') v-icon(name='calendar')
span.ml-1 {{$t('Events')}} span.ml-1 {{$t('Events')}}
p {{$t('event_confirm_explanation')}} p {{$t('event_confirm_explanation')}}
el-table(:data='paginatedEvents' small primary-key='id') el-table(:data='paginatedEvents' small primary-key='id' v-loading='loading')
el-table-column(:label='$t("Name")') el-table-column(:label='$t("Name")')
template(slot-scope='data') {{data.row.title}} template(slot-scope='data') {{data.row.title}}
el-table-column(:label='$t("Where")') el-table-column(:label='$t("Where")')
@ -76,6 +76,7 @@
<script> <script>
import { mapState } from 'vuex' import { mapState } from 'vuex'
import api from '@/api' import api from '@/api'
import { Message } from 'element-ui'
export default { export default {
name: 'Admin', name: 'Admin',
@ -94,6 +95,7 @@ export default {
place: {name: '', address: '' }, place: {name: '', address: '' },
tag: {name: '', color: ''}, tag: {name: '', color: ''},
events: [], events: [],
loading: false
} }
}, },
async mounted () { async mounted () {
@ -147,8 +149,10 @@ export default {
async confirm (id) { async confirm (id) {
console.log('dentro confirm', id) console.log('dentro confirm', id)
try { try {
this.loading = true
await api.confirmEvent(id) await api.confirmEvent(id)
this.$message({ this.loading = false
Message({
message: this.$t('event_confirmed'), message: this.$t('event_confirmed'),
type: 'success' type: 'success'
}) })

View file

@ -1,5 +1,7 @@
<template lang="pug"> <template lang="pug">
v-calendar#calendar.card( v-calendar#calendar.card(
show-caps
:popover-expanded='true'
:attributes='attributes' :attributes='attributes'
:from-page.sync='page' :from-page.sync='page'
is-expanded is-inline) is-expanded is-inline)
@ -22,8 +24,8 @@ export default {
page: { month, year}, page: { month, year},
} }
}, },
mounted () { async mounted () {
this.updateEvents(this.page) await this.updateEvents(this.page)
}, },
watch: { watch: {
page () { page () {

View file

@ -1,5 +1,5 @@
<template lang="pug"> <template lang="pug">
b-card(bg-variant='dark' text-variant='white' b-card(bg-variant='dark' text-variant='white' :class="{ withImg: event.image_path ? true : false }"
@click='$router.push("/event/" + event.id)' @click='$router.push("/event/" + event.id)'
:img-src='imgPath') :img-src='imgPath')
strong {{event.title}} strong {{event.title}}
@ -58,7 +58,8 @@ export default {
} }
.card-img { .card-img {
max-height: 180px; height: 180px;
object-fit: cover; object-fit: cover;
} }

View file

@ -74,7 +74,7 @@ export default {
async remove () { async remove () {
await api.delEvent(this.event.id) await api.delEvent(this.event.id)
this.delEvent(this.event.id) this.delEvent(this.event.id)
this.$refs.modal.hide() this.$refs.eventDetail.hide()
} }
} }
} }

View file

@ -12,11 +12,11 @@
el-tab-pane.pt-1(label='email' name='email') el-tab-pane.pt-1(label='email' name='email')
p(v-html='$t(`export_email_explanation`)') p(v-html='$t(`export_email_explanation`)')
b-form b-form
el-switch(v-model='reminder.send_on_insert' :active-text="$t('notify_on_insert')") el-switch(v-model='reminder.notify_on_add' :active-text="$t('notify_on_insert')")
br br
el-switch.mt-2(v-model='reminder.send_reminder' :active-text="$t('send_reminder')") //- el-switch.mt-2(v-model='reminder.send_reminder' :active-text="$t('send_reminder')")
el-input.mt-2(v-model='reminder.mail' :placeholder="$t('Insert your address')") el-input.mt-2(v-model='reminder.email' :placeholder="$t('Insert your address')")
el-button.mt-2.float-right(type='success' @click='activate_email') {{$t('Send')}} el-button.mt-2.float-right(type='success' @click='add_reminder') {{$t('Send')}}
el-tab-pane.pt-1(label='feed rss' name='feed') el-tab-pane.pt-1(label='feed rss' name='feed')
span(v-html='$t(`export_feed_explanation`)') span(v-html='$t(`export_feed_explanation`)')
@ -30,7 +30,7 @@
el-tab-pane.pt-1(label='list' name='list') el-tab-pane.pt-1(label='list' name='list')
p(v-html='$t(`export_list_explanation`)') p(v-html='$t(`export_list_explanation`)')
b-card.mb-1(no-body header='Eventi') el-card.mb-1(no-body header='Eventi')
b-list-group#list(flush) b-list-group#list(flush)
b-list-group-item.flex-column.align-items-start(v-for="event in filteredEvents" :key='event.id' b-list-group-item.flex-column.align-items-start(v-for="event in filteredEvents" :key='event.id'
:to='`/event/${event.id}`') :to='`/event/${event.id}`')
@ -40,7 +40,7 @@
strong.mb-1 {{event.title}} strong.mb-1 {{event.title}}
br br
small.float-right {{event.place.name}} small.float-right {{event.place.name}}
el-tag.mr-1(:color='tag.color' size='mini' v-for='tag in event.tags' :key='tag.tag') {{tag.tag}} el-tag.mr-1(:color='tag.color || "grey"' size='mini' v-for='tag in event.tags' :key='tag.tag') {{tag.tag}}
el-input.mb-1(type='textarea' v-model='script') el-input.mb-1(type='textarea' v-model='script')
el-button.float-right(plain type="primary" icon='el-icon-document' v-clipboard:copy="script") Copy el-button.float-right(plain type="primary" icon='el-icon-document' v-clipboard:copy="script") Copy
@ -58,6 +58,7 @@ import path from 'path'
import filters from '../filters' import filters from '../filters'
import Calendar from '@/components/Calendar' import Calendar from '@/components/Calendar'
import {intersection} from 'lodash' import {intersection} from 'lodash'
import api from '@/api'
export default { export default {
name: 'Export', name: 'Export',
@ -66,7 +67,7 @@ export default {
return { return {
type: 'email', type: 'email',
link: '', link: '',
reminder: { send_on_insert: true, send_reminder: false }, reminder: { notify_on_add: true, send_reminder: false },
export_list: true, export_list: true,
script: `<iframe>Ti piacerebbe</iframe>`, script: `<iframe>Ti piacerebbe</iframe>`,
} }
@ -81,7 +82,8 @@ export default {
} }
}, },
methods: { methods: {
activate_email () { async add_reminder () {
await api.emailReminder({ ...this.reminder, filters: this.filters})
this.$refs.modal.hide() this.$refs.modal.hide()
}, },
loadLink () { loadLink () {

View file

@ -1,9 +1,10 @@
<template lang="pug"> <template lang="pug">
magic-grid(animate :gap=5 :maxCols=4 :maxColWidth='300') magic-grid(:animate="false" useMin :gap=5 :maxCols=4
:maxColWidth='400' ref='magicgrid')
div.mt-1.item div.mt-1.item
Search#search Search#search
Calendar Calendar
Event.item(v-for='event in filteredEvents' Event.item.mt-1(v-for='event in filteredEvents'
:key='event.id' :key='event.id'
:event='event') :event='event')
</template> </template>
@ -20,10 +21,17 @@ import Search from '@/components/Search'
export default { export default {
name: 'Home', name: 'Home',
components: { Event, Calendar, Search }, components: { Event, Calendar, Search },
watch: {
filteredEvents () {
this.$nextTick( this.$refs.magicgrid.positionItems)
}
},
computed: { computed: {
...mapState(['events', 'filters']), ...mapState(['events', 'filters']),
filteredEvents () { filteredEvents () {
return this.$store.getters.filteredEvents.filter(e => !e.past) return this.$store.getters.filteredEvents
.filter(e => !e.past)
.sort((a, b) => { a.start_datetime > b.start_datetime})
} }
} }
} }
@ -35,8 +43,11 @@ export default {
} }
.item { .item {
/* min-width: 350px; */
width: 100%; width: 100%;
max-width: 400px;
margin-top: 4px;
position: absolute;
cursor: pointer;
} }
.card-columns { .card-columns {

View file

@ -1,8 +1,8 @@
<template lang='pug'> <template lang='pug'>
b-modal(@show="$refs.email.focus()" :title='$t("Login")' hide-footer b-modal(@shown="$refs.email.focus()" :title='$t("Login")' hide-footer
@hidden='$router.replace("/")' :visible='true') @hidden='$router.replace("/")' :visible='true')
el-form el-form
span {{$t('login_explanation')}} p {{$t('login_explanation')}}
el-input.mb-2(v-model='email' type='email' :placeholder='$t("Email")' autocomplete='email' ref='email') el-input.mb-2(v-model='email' type='email' :placeholder='$t("Email")' autocomplete='email' ref='email')
v-icon(name='user' slot='prepend') v-icon(name='user' slot='prepend')
el-input.mb-2(v-model='password' type='password' :placeholder='$t("Password")') el-input.mb-2(v-model='password' type='password' :placeholder='$t("Password")')

View file

@ -1,33 +1,27 @@
<template lang='pug'> <template lang='pug'>
b-modal(hide-footer b-modal(hide-footer @hidden='$router.replace("/")'
@hidden='$router.replace("/")' :title="$t('Register')" :visible='true' @shown='$refs.email.focus()') :title="$t('Register')" :visible='true' @shown='$refs.email.focus()')
b-form el-form
p.text-muted(v-html="$t('register_explanation')") p(v-html="$t('register_explanation')")
b-input-group.mb-1 el-input.mb-2(ref='email' v-model='user.email' type='email'
b-input-group-prepend :placeholder='$t("Email")' autocomplete='email')
b-input-group-text @ span(slot='prepend') @
b-form-input(ref='email' v-model='user.email' type="text" class="form-control" placeholder="Email" autocomplete="email" )
b-input-group.mb-1 el-input.mb-2(v-model='user.password' type="password" placeholder="Password")
b-input-group-prepend v-icon(name='lock' slot='prepend')
b-input-group-text
v-icon(name='lock')
b-form-input(v-model='user.password' type="password" class="form-control" placeholder="Password")
b-input-group.mb-1 el-input.mb-2(v-model='user.description' type="textarea" rows='3' :placeholder="$t('Description')")
b-input-group-prepend v-icon(name='envelope-open-text')
b-input-group-text
v-icon(name='envelope-open-text')
b-form-textarea(v-model='user.description' type="text" rows='3' class="form-control" :placeholder="$t('Description')")
el-button.float-right(plain type="success" icon='el-icon-arrow-right' @click='register') {{$t('Send')}}
b-button.float-right(variant="success" @click='register') {{$t('Send')}}
</template> </template>
<script> <script>
import api from '@/api' import api from '@/api'
import { mapActions } from 'vuex'; import { mapActions } from 'vuex';
import { Message } from 'element-ui'
export default { export default {
name: 'Register', name: 'Register',
data () { data () {
@ -42,7 +36,7 @@ export default {
try { try {
const user = await api.register(this.user) const user = await api.register(this.user)
this.$router.go(-1) this.$router.go(-1)
this.$message({ Message({
message: this.$t('registration_complete'), message: this.$t('registration_complete'),
type: 'success' type: 'success'
}) })

View file

@ -2,7 +2,7 @@
b-modal(ref='modal' @hidden='$router.replace("/")' size='md' :visible='true' b-modal(ref='modal' @hidden='$router.replace("/")' size='md' :visible='true'
:title="edit?$t('Edit event'):$t('New event')" hide-footer) :title="edit?$t('Edit event'):$t('New event')" hide-footer)
b-container b-container
el-tabs.mb-2(v-model='activeTab' v-loading='sending') el-tabs.mb-2(v-model='activeTab' v-loading='sending' @tab-click.native='changeTab')
el-tab-pane el-tab-pane
span(slot='label') {{$t('Where')}} <v-icon name='map-marker-alt'/> span(slot='label') {{$t('Where')}} <v-icon name='map-marker-alt'/>
@ -34,7 +34,7 @@
el-tab-pane el-tab-pane
span(slot='label') {{$t('What')}} <v-icon name='file-alt'/> span(slot='label') {{$t('What')}} <v-icon name='file-alt'/>
span {{$t('what_explanation')}} span {{$t('what_explanation')}}
el-input.mb-3(v-model='event.title') el-input.mb-3(v-model='event.title' ref='title')
span {{$t('description_explanation')}} span {{$t('description_explanation')}}
el-input.mb-3(v-model='event.description' type='textarea' :rows='3') el-input.mb-3(v-model='event.description' type='textarea' :rows='3')
span {{$t('tag_explanation')}} span {{$t('tag_explanation')}}
@ -44,7 +44,7 @@
el-option(v-for='tag in tags' :key='tag.tag' el-option(v-for='tag in tags' :key='tag.tag'
:label='tag' :value='tag') :label='tag' :value='tag')
el-button.float-right(@click='next' :disabled='!couldProceed') {{$t('Next')}} el-button.float-right(@click.native='next' :disabled='!couldProceed') {{$t('Next')}}
el-tab-pane el-tab-pane
span(slot='label') {{$t('Media')}} <v-icon name='image'/> span(slot='label') {{$t('Media')}} <v-icon name='image'/>
@ -132,14 +132,19 @@ export default {
}, },
methods: { methods: {
...mapActions(['addEvent', 'updateEvent', 'updateMeta']), ...mapActions(['addEvent', 'updateEvent', 'updateMeta']),
changeTab (tab) {
if (this.activeTab === "2") this.$refs.title.focus()
},
next () { next () {
this.activeTab = String(Number(this.activeTab)+1) this.activeTab = String(Number(this.activeTab)+1)
if (this.activeTab === "2") {
this.$refs.title.focus()
}
}, },
prev () { prev () {
this.activeTab = String(Number(this.activeTab-1)) this.activeTab = String(Number(this.activeTab-1))
}, },
placeChoosed () { placeChoosed () {
console.log('dentro placeChoosed')
const place = this.places.find( p => p.name === this.event.place.name ) const place = this.places.find( p => p.name === this.event.place.name )
if (place && place.address) { if (place && place.address) {
this.event.place.address = place.address this.event.place.address = place.address
@ -186,6 +191,7 @@ export default {
await this.updateEvent(formData) await this.updateEvent(formData)
} else { } else {
await this.addEvent(formData) await this.addEvent(formData)
// this.$router.push('/')
} }
this.updateMeta() this.updateMeta()
this.sending = false this.sending = false

View file

@ -77,7 +77,7 @@ const it = {
'Insert your address': 'Inserisci il tuo indirizzo', 'Insert your address': 'Inserisci il tuo indirizzo',
registration_complete: 'Controlla la tua posta (anche la cartella spam)', registration_complete: 'Controlla la tua posta (anche la cartella spam)',
registration_email: `Ciao, la tua registrazione sarà confermata nei prossimi giorni. Riceverai una conferma non temere.`, registration_email: `Ciao, la tua registrazione sarà confermata nei prossimi giorni. Riceverai una conferma non temere.`,
register_explanation: `I movimenti hanno bisogno di organizzarsi e autofinanziarsi. <br/>Questo è un dono per voi, non possiamo più vedervi usare le piattaforme del capitalismo. Solo eventi non commerciali e ovviamente antifascisti, antisessisti, antirazzisti. register_explanation: `I movimenti hanno bisogno di organizzarsi e autofinanziarsi. <br/>Questo è un dono per voi, usatelo solo per eventi non commerciali e ovviamente antifascisti, antisessisti, antirazzisti.
<br/>Prima di poter pubblicare <strong>dobbiamo approvare l'account</strong>, considera che <strong>dietro questo sito ci sono delle persone</strong> di <br/>Prima di poter pubblicare <strong>dobbiamo approvare l'account</strong>, considera che <strong>dietro questo sito ci sono delle persone</strong> di
carne e sangue, scrivici quindi due righe per farci capire che eventi vorresti pubblicare.`, carne e sangue, scrivici quindi due righe per farci capire che eventi vorresti pubblicare.`,
'Not registered?': `Non sei registrata?`, 'Not registered?': `Non sei registrata?`,

View file

@ -4,6 +4,7 @@ import BootstrapVue from 'bootstrap-vue'
import VCalendar from 'v-calendar' import VCalendar from 'v-calendar'
import 'vue-awesome/icons/lock' import 'vue-awesome/icons/lock'
import 'vue-awesome/icons/user'
import 'vue-awesome/icons/plus' import 'vue-awesome/icons/plus'
import 'vue-awesome/icons/cog' import 'vue-awesome/icons/cog'
import 'vue-awesome/icons/tools' import 'vue-awesome/icons/tools'
@ -17,6 +18,7 @@ import 'vue-awesome/icons/tag'
import 'vue-awesome/icons/users' import 'vue-awesome/icons/users'
import 'vue-awesome/icons/calendar' import 'vue-awesome/icons/calendar'
import 'vue-awesome/icons/edit' import 'vue-awesome/icons/edit'
import 'vue-awesome/icons/envelope-open-text'
import Icon from 'vue-awesome/components/Icon' import Icon from 'vue-awesome/components/Icon'
@ -26,7 +28,7 @@ import 'v-calendar/lib/v-calendar.min.css'
import 'bootstrap/dist/css/bootstrap.css' import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css' import 'bootstrap-vue/dist/bootstrap-vue.css'
import { Button, Select, Tag, Option, Table, FormItem, import { Button, Select, Tag, Option, Table, FormItem, Card,
Form, Tabs, TabPane, Switch, Input, Loading, TimeSelect, Form, Tabs, TabPane, Switch, Input, Loading, TimeSelect,
TableColumn, ColorPicker, Pagination } from 'element-ui' TableColumn, ColorPicker, Pagination } from 'element-ui'
import ElementLocale from 'element-ui/lib/locale' import ElementLocale from 'element-ui/lib/locale'
@ -47,6 +49,7 @@ import itLocale from '@/locale/it'
import enLocale from '@/locale/en' import enLocale from '@/locale/en'
Vue.use(Button) Vue.use(Button)
Vue.use(Card)
Vue.use(Select) Vue.use(Select)
Vue.use(Tag) Vue.use(Tag)
Vue.use(Input) Vue.use(Input)

View file

@ -48,8 +48,7 @@ export default new Vuex.Store({
// //
filters: { filters: {
tags: [], tags: [],
places: [], places: []
hidePast: false
} }
}, },
mutations: { mutations: {

View file

@ -17,7 +17,7 @@ services:
ports: ports:
- '12300:12300' - '12300:12300'
volumes: volumes:
- ./uploads:/usr/src/app/uploads - ./app/uploads:/usr/src/app/app/uploads
env_file: .env env_file: .env
environment: environment:

View file

@ -3,7 +3,7 @@
"main": "server.js", "main": "server.js",
"scripts": { "scripts": {
"serve": "NODE_ENV=production nodemon server.js", "serve": "NODE_ENV=production nodemon server.js",
"dev": "NODE_ENV=development nodemon server.js" "dev": "NODE_ENV=development nodemon app/server.js"
}, },
"dependencies": { "dependencies": {
"bcrypt": "^3.0.2", "bcrypt": "^3.0.2",

12
pm2.json Normal file
View file

@ -0,0 +1,12 @@
{
"apps": [
{
"name": "GANCIO",
"script": "./app/server.js"
},
{
"name": "WORKER",
"script": "./app/cron.js"
}
]
}