This commit is contained in:
lesion
2019-05-30 12:04:14 +02:00
parent 69792b518e
commit 6099d538c0
47 changed files with 1220 additions and 998 deletions

View File

@@ -52,6 +52,24 @@
"prio": 0, "prio": 0,
"references": [], "references": [],
"title": "export lista" "title": "export lista"
},
{
"assignedTo": {
"name": "lesion"
},
"creation_time": "2019-04-30T12:46:42.208Z",
"id": "16",
"references": [],
"title": "riesco a rimuovere bootstrap-vue e usare solo element ?"
},
{
"assignedTo": {
"name": "lesion"
},
"creation_time": "2019-04-28T09:25:50.701Z",
"id": "13",
"references": [],
"title": "test altra visualizzazione"
} }
], ],
"in-progress": [ "in-progress": [
@@ -123,6 +141,42 @@
"title": "risolvere le modali quando il js e' disabilitato", "title": "risolvere le modali quando il js e' disabilitato",
"type": "bug" "type": "bug"
}, },
{
"assignedTo": {
"name": "lesion"
},
"creation_time": "2019-05-27T15:42:35.467Z",
"id": "21",
"references": [],
"title": "all'admin deve mostrare un badge se ci sono pending operation"
},
{
"assignedTo": {
"name": "lesion"
},
"creation_time": "2019-05-27T15:16:22.839Z",
"id": "20",
"references": [],
"title": "check password reset"
},
{
"assignedTo": {
"name": "lesion"
},
"creation_time": "2019-05-27T15:45:39.093Z",
"id": "23",
"references": [],
"title": "colori te prego!"
},
{
"assignedTo": {
"name": "lesion"
},
"creation_time": "2019-05-27T15:45:18.012Z",
"id": "22",
"references": [],
"title": "filtri per luogo!"
},
{ {
"assignedTo": { "assignedTo": {
"name": "lesion" "name": "lesion"
@@ -132,6 +186,24 @@
"references": [], "references": [],
"title": "gestione errori quando non c'e' un evento" "title": "gestione errori quando non c'e' un evento"
}, },
{
"assignedTo": {
"name": "lesion"
},
"creation_time": "2019-05-02T16:15:07.106Z",
"id": "19",
"references": [],
"title": "modifica eventi multigiorno"
},
{
"assignedTo": {
"name": "lesion"
},
"creation_time": "2019-05-02T11:50:28.476Z",
"id": "18",
"references": [],
"title": "notifiche email / iscrizione / evento da confermare"
},
{ {
"assignedTo": { "assignedTo": {
"name": "lesion" "name": "lesion"
@@ -146,19 +218,19 @@
"assignedTo": { "assignedTo": {
"name": "lesion" "name": "lesion"
}, },
"creation_time": "2019-04-27T19:44:33.769Z", "creation_time": "2019-04-30T22:00:29.237Z",
"id": "12", "id": "17",
"references": [], "references": [],
"title": "rifare il calendario o solo il popup" "title": "porcoddio la config arriva anche al client ovviamente, devo separare!"
}, },
{ {
"assignedTo": { "assignedTo": {
"name": "lesion" "name": "lesion"
}, },
"creation_time": "2019-04-28T09:25:50.701Z", "creation_time": "2019-04-27T19:44:33.769Z",
"id": "13", "id": "12",
"references": [], "references": [],
"title": "test altra visualizzazione" "title": "rifare il calendario o solo il popup"
}, },
{ {
"assignedTo": { "assignedTo": {
@@ -187,10 +259,10 @@
"assignedTo": { "assignedTo": {
"name": "lesion" "name": "lesion"
}, },
"creation_time": "2019-04-30T12:46:42.208Z", "creation_time": "2019-05-27T20:42:22.581Z",
"id": "16", "id": "24",
"references": [], "references": [],
"title": "riesco a rimuovere bootstrap-vue e usare solo element ?" "title": "copy to clipboard"
} }
] ]
} }

View File

@@ -1,22 +1,34 @@
# gancio ## gancio
### event manager for radical communities
> My well-made Nuxt.js project > :warning: Gancio is under heavy development,
> if something is not working as expected, it's expected :D
## Build Setup
## Install
``` bash ``` bash
# install dependencies # install dependencies
$ yarn install $ yarn install
# serve with hot reload at localhost:3000
$ yarn run dev
# build for production and launch server # build for production and launch server
$ yarn run build $ yarn build
$ yarn start $ yarn start
# generate static project
$ yarn run generate
``` ```
##### nginx setup
https://nuxtjs.org/faq/nginx-proxy
For detailed explanation on how things work, checkout [Nuxt.js docs](https://nuxtjs.org). For detailed explanation on how things work, checkout [Nuxt.js docs](https://nuxtjs.org).
## Hacking
``` bash
$ yarn dev
```
#### Add a new icon
plugin/vue-awesome.js

55
assets/style.less Normal file
View File

@@ -0,0 +1,55 @@
html, body {
margin: 0px;
background-color: #222C32 !important;
width: 100%;
overflow-x: hidden;
box-sizing: border-box;
font-family: BlinkMacSystemFont,-apple-system,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,Helvetica,Arial,sans-serif !important;
}
* {
box-sizing: border-box;
}
.el-dialog {
margin-top: 0px !important;
border-radius: 0px;
width: 100%;
.el-dialog__body {
word-break: break-word;
}
}
.el-select-dropdown {
max-width: 100%;
left: 0px;
}
.page-enter-active, .page-leave-active {
transition: opacity .2s, transform .3s;
}
.page-enter, .page-leave-active {
transition: opacity .3s, transform .2s;
opacity: 0;
// transform: translateY(30px);
}
pre {
font-family: BlinkMacSystemFont,-apple-system,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,Helvetica,Arial,sans-serif !important;
margin-bottom: 0px;
white-space: pre-line;
font-family: unset;
}
.el-popover {
word-break: normal;
}
@media only screen and (min-width: 768px) {
.el-dialog {
margin-top: 10vh !important;
width: 700px;
border-radius: 3px;
}
}

View File

@@ -1,37 +1,29 @@
<template lang="pug"> <template lang="pug">
v-calendar#calendar.card( #calendar
v-calendar(
title-position='left' title-position='left'
locale='it' locale='it'
is-dark is-dark
show-caps
:attributes='attributes' :attributes='attributes'
:from-page.sync='page' :from-page.sync='page'
is-expanded is-inline) is-expanded
div(slot='popover', slot-scope='{ customData, attributes }') show-clear-margin
p {{attributes}} is-inline
//- router-link(:to="`/event/${customData.id}`") {{customData.start_datetime|hour}} - {{customData.title}} @dayclick='click')
//- div(v-if='customData.days && customData.days[selectedEvent]')
p {{customData.days[customData.selectedEvent].title}}
p {{customData.days[customData.selectedEvent].tags}}
el-button(@click='customData.selectedEvent=customData.selectedEvent+1') {{customData.selectedEvent}}/{{customData.days.length}}
v-icon(name='clock' @click='customData.selectedEvent=customData.selectedEvent+1')
//- @{{customData.place.name}}
</template> </template>
<script> <script>
import { mapState, mapActions } from 'vuex' import { mapState, mapActions, mapGetters } from 'vuex'
import moment from 'dayjs' import moment from 'dayjs'
import { intersection } from 'lodash' import { intersection } from 'lodash'
export default { export default {
name: 'Calendar', name: 'Calendar',
// filters,
data () { data () {
const month = moment().month()+1 const month = moment().month()+1
const year = moment().year() const year = moment().year()
return { return {
page: { month, year}, page: { month, year},
selectedEvent: {},
daysWithEvents: {}
} }
}, },
@@ -42,8 +34,9 @@ export default {
}, },
methods: { methods: {
...mapActions(['updateEvents']), ...mapActions(['updateEvents']),
nextEvent () { click (day) {
const element = document.getElementById(day.day)
if (element) element.scrollIntoView(); //Even IE6 supports this
}, },
eventToAttribute(event) { eventToAttribute(event) {
let e = { let e = {
@@ -52,18 +45,6 @@ export default {
order: event.start_datetime, order: event.start_datetime,
} }
const day = moment(event.start_datetime).date() const day = moment(event.start_datetime).date()
if (!this.daysWithEvents[day]) {
this.daysWithEvents[day] = []
e.popover = {
slot: 'popover',
visibility: 'hover',
isInteractive: true,
hideIndicator: true,
}
e.customData.days = this.daysWithEvents[day]
}
this.daysWithEvents[day].push({title: event.title, when: event.start_datetime, tags: event.tags })
let color = event.tags && event.tags.length && event.tags[0].color ? event.tags[0].color : 'rgba(170,170,250,0.7)' let color = event.tags && event.tags.length && event.tags[0].color ? event.tags[0].color : 'rgba(170,170,250,0.7)'
if (event.past) color = 'rgba(200,200,200,0.5)' if (event.past) color = 'rgba(200,200,200,0.5)'
if (event.multidate) { if (event.multidate) {
@@ -71,7 +52,7 @@ export default {
start: event.start_datetime, end: event.end_datetime start: event.start_datetime, end: event.end_datetime
} }
e.highlight = { backgroundColor: color, e.highlight = { backgroundColor: color,
borderColor: 'transparent', // borderColor: 'transparent',
borderWidth: '4px' } borderWidth: '4px' }
} else { } else {
e.dates = event.start_datetime e.dates = event.start_datetime
@@ -81,17 +62,13 @@ export default {
} }
}, },
computed: { computed: {
filteredEvents () { ...mapGetters(['filteredEvents']),
return this.$store.getters.filteredEvents
},
...mapState(['events', 'filters']),
attributes () { attributes () {
return [ return [
{ key: 'today', dates: new Date(), { key: 'today', dates: new Date(),
highlight: { highlight: {
backgroundColor: '#aaffaa' backgroundColor: '#aaffaa'
}, },
popover: {label: this.$t('common.today')}
}, },
...this.filteredEvents.map(this.eventToAttribute) ...this.filteredEvents.map(this.eventToAttribute)
] ]
@@ -102,11 +79,9 @@ export default {
<style> <style>
#calendar { #calendar {
margin-bottom: 0em; margin: 0 auto;
margin-top: 0.3em; max-width: 500px;
align-self: center;
} }
#calendar a {
color: blue;
}
</style> </style>

View File

@@ -1,65 +1,139 @@
<template lang="pug"> <template lang="pug">
nuxt-link(:to='`/event/${event.id}`') nuxt-link.event(:to='`event/${event.id}`' :class='{ withImg: event.image_path }')
//- @click='$router.push("/event/" + event.id)' //- image
b-card(bg-variant='dark' text-variant='white' :class="{ withImg: event.image_path ? true : false }" img(v-if='showImage && event.image_path' :src='`/media/thumb/${event.image_path}`')
:img-src='imgPath')
strong {{event.title}} .event-info
div <v-icon name='clock'/> {{event.start_datetime|datetime}} .content-info
span <v-icon name='map-marker-alt'/> {{event.place.name}}
br //- title
el-tag.mr-1(:color='tag.color' v-for='tag in event.tags' :key='tag.tag' h2 {{event.title}}
size='small' @click.stop='addSearchTag(tag)') {{tag.tag}}
//- date / place
.date
div {{event|event_when}}
div {{event.place.name}}
//- p(v-if='showDescription') {{event.description}}
//- div(v-if='event.comments && event.comments.length')
//- v-icon(name='comments' color='dark')
//- span {{event.comments.length}} {{$t('common.comments')}}
ul.tags(v-if='showTags && event.tags')
li(v-for='tag in event.tags' :key='tag.tag') {{tag.tag}}
</template> </template>
<script> <script>
import { mapState, mapActions } from 'vuex' import { mapState, mapActions } from 'vuex'
// import api from '@/server/api'
// import filters from '@/filters'
export default { export default {
props: ['event'], props: {
computed: { event: Object,
...mapState(['user']), showTags: {
imgPath() { type: Boolean,
return this.event.image_path && '/media/thumb/' + this.event.image_path default: true
}, },
mine() { showImage: {
return this.event.userId === this.user.id type: Boolean,
default: true
},
showDescription: {
type: Boolean,
default: true
},
selected: {
type: Boolean,
default: false
} }
}, },
// filters: { computed: {
// datetime: this.datetime date () {
// }, return new Date(this.event.start_datetime).getDate()
methods: {
...mapActions(['delEvent', 'addSearchTag']),
async remove() {
// await api.delEvent(this.event.id)
// this.delEvent(this.event.id)
} }
} }
} }
</script> </script>
<style scoped> <style lang='less'>
/* .card::before {
border-top: 4px solid black;
content: ''
} */
.el-card { @media only screen and (min-width: 574px) {
border: none; .event {
height: 100%;
}
}
.event {
padding: 3px;
display: flex;
flex-direction: column;
// height: 100%;
&:hover {
text-decoration: none;
}
img {
width: 100%;
max-height: 200px;
object-fit: cover;
object-position: top;
}
.event-info {
height: 100%;
display: flex;
flex-direction: column;
justify-content: space-between;
background-color: #222;
}
.content-info {
font-size: 12px;
font-size: 0.8em;
padding: 0.8em 1em;
max-height: 200px;
color: rgb(255, 122, 204);
h2 {
color: yellow;
font-size: 16px;
font-size: 1.1rem;
margin: 0px;
}
p {
max-height: 92px;
overflow: hidden;
color: white;
margin: 0px;
}
.date {
font-weight: 800;
font-size: 16px;
font-size: 1rem;
}
}
.tags {
font-size: 12px;
padding: 1px;
margin-bottom: 0;
display:flex;
flex-wrap: wrap;
justify-content: center;
li {
background: #40484D;
display: inline-block;
padding: 2px 10px;
color: rgba(255,255,255,0.7);
margin: 1px;
text-align: center;
flex-grow: 1;
}
}
} }
.el-card img {
width: 100%;
}
.card-columns .card {
margin-top: 0.2em;
margin-bottom: 0em;
}
.card-img {
height: 180px;
object-fit: cover;
}
</style> </style>

View File

@@ -1,108 +1,40 @@
<template lang="pug"> <template lang="pug">
div(v-loading='loading') section
magic-grid(:animate="true" useMin :gap=5 :maxCols=4
:maxColWidth='400' ref='magicgrid') .row.m-0
div.mt-1.item no-ssr
//- Search#search Calendar.col-sm-12.col-lg-8.col-xl-6
no-ssr .p-0.col-sm-6.col-lg-4.col-xl-3(v-for='event in filteredEvents')
Calendar a(:id='event.newDay' v-if='event.newDay')
Event.item.mt-1(v-for='event in events' .d-block.d-sm-none
:key='event.id' el-divider {{event.start_datetime|day}}
:event='event') Event(
:id='event.start_datetime'
:key='event.id'
:event='event'
)
</template> </template>
<script> <script>
import { mapState, mapActions } from 'vuex' import { mapGetters } from 'vuex'
import axios from 'axios'
// import filters from '@/filters.js'
import Event from '@/components/Event' import Event from '@/components/Event'
import Calendar from '@/components/Calendar' import Calendar from '@/components/Calendar'
// import { intersection } from 'lodash' import Search from '@/components/Search'
// import moment from 'dayjs'
// import Search from '@/components/Search'
export default { export default {
name: 'Home', name: 'Home',
data () { data () {
return { loading: true } return { }
}, },
// created () { components: { Calendar, Event, Search },
// const now = new Date() computed: mapGetters(['filteredEvents']),
// const page = { month: now.getMonth() - 1, year: now.getFullYear() }
// this.updateEvents(page)
// },
components: { Event, Calendar }, // , Calendar, Search },
computed: {
...mapState(['events', 'filters']),
filteredEvents() {
return this.events
// return this.$store.getters.filteredEvents
.filter(e => !e.past)
.sort((a, b) => a.start_datetime > b.start_datetime)
}
},
mounted () {
this.loading = false
},
methods: mapActions(['updateEvents']),
watch: {
filteredEvents() {
this.$nextTick(this.$refs.magicgrid.positionItems)
this.loading = false
}
}
} }
</script> </script>
<style> <style lang="less">
#search { section {
display: inline-flex;
}
.item {
width: 100%; width: 100%;
max-width: 400px; max-width: 1500px;
margin-top: 4px; margin: 0 auto;
position: absolute;
cursor: pointer;
} }
.card-columns {
column-count: 1;
column-gap: 0.2em;
}
@media (min-width: 576px) {
.container {
max-width: none;
}
.card-columns {
column-count: 2;
}
}
@media (min-width: 950px) {
.container {
max-width: 1400px;
}
.card-columns {
column-count: 3;
}
}
/* .item {
transition: all .2s;
display: inline-block;
width: 100%;
} */
/* .list-enter, .list-leave-to {
opacity: 0;
transform: translateY(30px);
}
.list-leave-active {
position: absolute;
top: 0px;
width: 0px;
left: 0px;
height: 0px;
z-index: -10;
} */
</style> </style>

View File

@@ -1,34 +1,83 @@
<template lang="pug"> <template lang="pug">
div#gancio-widget div#list
//- el-card.mb-1(no-body header='Eventi') el-divider {{title}}
//- b-list-group#list(flush) el-timeline
p minimal {{minimal}} el-timeline-item(
ul v-for='event in events'
li.flex-column.align-items-start(v-for="event in events" :key='event.id' :key='event.id'
:to='`/event/${event.id}`' target='_parent') :timestamp='event|event_when'
img(v-if='event.image_path' slot="aside" :src="`http://localhost:3000/media/${event.image_path}`" alt="Meia Aside" style='max-height: 60px') placement='top' icon='el-icon-arrow-down' size='large'
strong.mb-1 {{event.title}} )
br
small.float-right {{event.place.name}} div.float-right
//- el-tag.mr-1(v-if='showtags' :color='tag.color || "rgba(64,158,255,.1)"' size='mini' v-for='tag in event.tags' :key='tag.tag') {{tag.tag}} small @{{event.place.name}}
a(:href='"/event/" + event.id' target='_blank') {{event.title}}
hr
</template> </template>
<script> <script>
import axios from 'axios' import { mapGetters } from 'vuex'
const { SHARED_CONF } = require('@/config')
export default { export default {
name: 'List', name: 'List',
data () { data () {
return { return { SHARED_CONF }
events: []
}
}, },
props: { props: {
title: {
type: String,
default: SHARED_CONF.title
},
events: {
type: Array,
default: () => {
return []
}
},
maxEvents: {
type: Number,
default: 0
},
minimal: { minimal: {
type: Boolean, type: Boolean,
default: false default: false
},
showTags: {
type: Boolean,
default: true,
},
showImage: {
type: Boolean,
default: true,
},
showDescription: {
type: Boolean,
default: true
} }
}, },
async mounted () {
this.events = (await axios.get('http://localhost:3000/api/export/json')).data
}
} }
</script> </script>
<style lang='less'>
#list {
max-width: 500px;
.el-timeline {
padding-left: 5px;
hr {
margin-top: 4px;
margin-bottom: 4px;
}
}
.el-timeline-item {
padding-bottom: 1px;
}
.el-timeline-item__timestamp {
margin: 0px;
padding: 0px;
}
}
</style>

View File

@@ -1,51 +1,59 @@
<template lang="pug"> <template lang="pug">
b-navbar(type="dark" variant="dark" toggleable='md') el-menu.d-grid.nav(mode='horizontal' router background-color="#222C32")
b-navbar-toggle(target='nav_collapse')
b-navbar-brand(to='/') <img id='logo' src='gancio_logo.svg'/> el-menu-item(v-if='!$auth.loggedIn' index='/login' :title="$t('common.login')")
b-collapse#nav_collapse(is-nav) v-icon(color='lightgreen' name='user')
b-navbar-nav
b-nav-item(v-if='!$auth.loggedIn' to='/login' v-b-tooltip :title='$t("common.login")') <v-icon color='lightgreen' name='lock' /> el-menu-item(index='/add' :title="$t('common.add_event')")
span.d-md-none {{$t('common.login')}} v-icon(color='lightgreen' name='plus')
b-nav-item(to='/add' v-b-tooltip :title='$t("common.add_event")' ) <v-icon color='lightgreen' name='plus'/>
span.d-md-none {{$t('common.add_event')}} el-menu-item(v-if='$auth.loggedIn' index='/settings' :title="$t('common.settings')")
b-nav-item(v-if='$auth.loggedIn' to='/settings' v-b-tooltip :title='$t("common.settings")') <v-icon color='orange' name='cog'/> v-icon(color='orange' name='cog')
span.d-md-none {{$t('common.settings')}}
b-nav-item(v-if='$auth.user && $auth.user.is_admin' to='/admin' v-b-tooltip :title='$t("common.admin")') <v-icon color='lightblue' name='tools'/> el-menu-item(v-if='$auth.user && $auth.user.is_admin' index='/admin' :title="$t('common.admin')")
span.d-md-none {{$t('common.admin')}} v-icon(color='lightblue' name='tools')
b-nav-item(to='/export' v-b-tooltip :title='$t("common.export")') <v-icon name='file-export' color='yellow'/>
span.d-md-none {{$t('common.export')}} el-menu-item(index='/export' :title="$t('common.share')")
b-nav-item(v-if='$auth.loggedIn' @click='logout' v-b-tooltip :title='$t("common.logout")') <v-icon color='red' name='sign-out-alt'/> v-icon(name='share' color='yellow')
span.d-md-none {{$t('common.logout')}}
b-nav-item el-menu-item(v-if='$auth.loggedIn' @click='logout' :title="$t('common.logout')")
b-navbar-nav.ml-auto v-icon(color='red' name='sign-out-alt')
b-nav-item(to='/about')
span {{$t('common.info')}} <v-icon color='#ff9fc4' name='question-circle'/> el-popover(
placement="bottom"
trigger="click")
Search
el-menu-item(slot='reference')
v-icon(color='lightblue' name='search')
el-menu-item.float-right(index='/about' :title="$t('common.info')")
img#logo(src='/favicon.ico')
</template> </template>
<script> <script>
import {mapState, mapActions} from 'vuex' import { Message } from 'element-ui'
import Search from '@/components/Search'
export default { export default {
name: 'Nav', name: 'Nav',
computed: { components: { Search },
...mapState(['filters']), methods: {
filters_tags: { logout () {
set (value) { Message({
this.setSearchTags(value) message: this.$t('common.logout_ok'),
}, type: 'success'
get () { })
return this.filters.tags this.$auth.logout()
} }
}, }
filters_places: {
set (value) {
this.setSearchPlaces(value)
},
get () {
return this.filters.places
}
},
},
methods: mapActions(['logout']),
} }
</script> </script>
<style>
.el-menu.el-menu--horizontal {
border-bottom: none;
}
</style>

View File

@@ -1,23 +1,64 @@
<template lang="pug"> <template lang="pug">
div div.ml-2.mt-1
el-select.mr-1(v-model='filters_places' multiple filterable collapse-tags el-switch.mb-1(v-if='$auth.loggedIn'
default-first-option :placeholder='$t("Where")') active-text='solo miei'
el-option(v-for='place in places' :value='place.name' inactive-text='tutti'
:label='place.name' :key='place.id') inactive-color='lightgreen'
el-select(v-model='filters_tags' multiple filterable collapse-tags v-model='onlyMine'
default-first-option :placeholder='$t("Tags")') )
el-option(v-for='tag in tags' :key='tag.tag' el-switch.mt-1.mb-1.ml-2.d-block(
:label='tag.tag' :value='tag.tag') inactive-text='futuri'
active-text='anche passati'
inactive-color='lightgreen'
v-model='showPast'
)
el-select.search(v-model='filter' multiple
filterable collapse-tags default-first-option
:placeholder='$t("common.search")')
el-option(v-for='(keyword, id) in keywords' :key='keyword.value'
:label='keyword.label' :value='keyword.value')
</template> </template>
<script> <script>
import {mapState, mapActions} from 'vuex' import {mapState, mapActions} from 'vuex'
export default { export default {
data () {
return {
onlyMine: false,
withPast: true,
}
},
name :'Search', name :'Search',
methods: mapActions(['setSearchPlaces', 'setSearchTags']), methods: mapActions(['setSearchPlaces', 'setSearchTags', 'showPastEvents']),
computed: { computed: {
...mapState(['tags', 'places', 'filters']), ...mapState(['tags', 'places', 'filters', 'show_past_events']),
keywords () {
const tags = this.tags.map( t => ({ value: 't' + t.tag, label: t.tag, count: +t.eventsCount }))
const places = this.places.map( p => ({ value: 'p' + p.id, label: p.name, count: +p.eventsCount }))
return tags.concat(places)
},
showPast : {
set (value) {
this.showPastEvents(value)
},
get () {
return this.show_past_events
}
},
filter: {
set (filters) {
const tags = filters.filter(f => f[0] === 't').map(t => t.slice(1))
this.setSearchTags(tags)
const places = filters.filter(f => f[0] === 'p').map(p => +p.slice(1))
this.setSearchPlaces(places)
},
get () {
return this.filters.tags.map(t => 't' + t).concat(this.filters.places.map(p => 'p' + p))
}
},
filters_tags: { filters_tags: {
set (value) { set (value) {
this.setSearchTags(value) this.setSearchTags(value)
@@ -37,3 +78,5 @@ export default {
} }
} }
</script> </script>
<style lang="less">
</style>

View File

@@ -1,71 +1,6 @@
<template lang='pug'> <template>
#app <nuxt/>
Nav
Home
transition(name="fade" mode="out-in")
nuxt
</template> </template>
<style lang="less">
<script> @import '../assets/style.less';
import Home from '~/components/Home.vue'
import Nav from '~/components/Nav.vue'
export default {
name: 'App',
components: { Nav, Home },
}
</script>
<style>
#logo {
max-height: 40px;
}
.navbar-brand {
padding: 0px;
}
#search,
#search ul {
align-items: baseline;
}
html, body {
scrollbar-face-color: #313543;
scrollbar-track-color: rgba(0, 0, 0, 0.1);
font-family: Lato,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif;
color: #2c3e50;
background: black;
}
::-webkit-scrollbar {
width: 7px;
height: 7px; }
::-webkit-scrollbar-thumb {
background: #313543;
border: 0px none #ffffff;
border-radius: 6px; }
::-webkit-scrollbar-thumb:hover {
background: #353a49; }
::-webkit-scrollbar-thumb:active {
background: #313543; }
::-webkit-scrollbar-track {
border: 0px none #ffffff;
border-radius: 6px;
background: rgba(0, 0, 0, 0.1); }
::-webkit-scrollbar-track:hover {
background: #282c37; }
::-webkit-scrollbar-track:active {
background: #282c37; }
::-webkit-scrollbar-corner {
background: transparent; }
/* .column {
margin-top: 3px;
margin-right: 3px;
margin-bottom: 3px;
width: 350px;
} */
</style> </style>

5
locales/email/en.json Normal file
View File

@@ -0,0 +1,5 @@
{
"registration_email": "registration_email",
"recover_email": "recover_email",
"press here": "press here"
}

5
locales/email/es.json Normal file
View File

@@ -0,0 +1,5 @@
{
"registration_email": "registration_email",
"recover_email": "recover_email",
"press here": "press here"
}

5
locales/email/it.json Normal file
View File

@@ -0,0 +1,5 @@
{
"registration_email": "registration_email",
"recover_email": "recover_email",
"press here": "press here"
}

5
locales/email/zh.json Normal file
View File

@@ -0,0 +1,5 @@
{
"registration_email": "registration_email",
"recover_email": "recover_email",
"press here": "press here"
}

View File

@@ -1,74 +0,0 @@
{
"common": {
"login": "Entra",
"email": "Email",
"password": "Password",
"register": "Registrati",
"send": "Invia",
"description": "Descrizione",
"info": "Info",
"add_event": "Aggiungi evento",
"export": "Esporta",
"settings": "Impostazioni",
"admin": "Amministra",
"logout": "Esci",
"where": "Dove",
"when": "Quando",
"next": "Avanti",
"what": "Cosa",
"address": "Indirizzo",
"media": "Media",
"today": "Oggi",
"users": "Utenti",
"places": "Posti",
"events": "Eventi",
"tags": "Etichette",
"deactivate": "Disattiva",
"activate": "Attiva",
"remove_admin": "Rimuovi Admin",
"name": "Nome",
"save": "Salva",
"confirm": "Conferma",
"tag": "Etichetta",
"color": "Colore",
"associate": "Associa",
"hide": "Nascondi",
"remove": "Elimina",
"edit": "Modifica",
"actions": "Azioni",
"resources": "Risorse",
"add": "Aggiungi"
},
"login": {
"description": "Entrando puoi pubblicare nuovi eventi.",
"not_registered": "Non sei registrata?",
"forgot_password": "Ho dimenticato la password",
"insert_email": "Inserisci la mail",
"check_email": "Controlla la tua casella di posta (anche la cartella spam)",
"error": "Errore nel login"
},
"register": {
"description": "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 carne e sangue, scrivici quindi due righe per farci capire che eventi vorresti pubblicare.",
"complete": "",
"admin_complete": ""
},
"event": {
"anon": "",
"anon_description": "",
"where_description" : "Dov'è il gancio? Se è un luogo fisico, scrivi il suo nome del per esteso (tipo 'Mezcal Squat'), se è una Piazza/Via metti quella (tipo 'Piazza Castello, Torino'). Se trovi già il luogo dell'evento premilo e l'indirizzo verrà autocompletato.",
"address_description": "",
"tag_description": "Puoi inserire un tag (es. concerto, corteo)",
"added": "Avento aggiunto"
},
"admin": {
"event_confirm_description": "Qui puoi confermare gli eventi inseriti da utenti non iscritti",
"tag_description": "Cambia il colore delle etichette",
"place_description": "Modifica l'indirizzo di un posto",
"mastodon_description": "Puoi associare un account mastodon a questa istanza di gancio. Tutti gli eventi verranno pubblicati li'",
"mastodon_instance": "Istanza mastodon"
}
}

View File

@@ -1,4 +1,4 @@
const pkg = require('./package') const { SHARED_CONF } = require('./config')
module.exports = { module.exports = {
mode: 'universal', mode: 'universal',
@@ -7,11 +7,11 @@ module.exports = {
** Headers of the page ** Headers of the page
*/ */
head: { head: {
title: pkg.name, title: SHARED_CONF.title,
meta: [ meta: [
{ charset: 'utf-8' }, { charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' }, { name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: pkg.description } { hid: 'description', name: 'description', content: SHARED_CONF.description }
], ],
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }] link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }]
}, },
@@ -23,27 +23,26 @@ module.exports = {
/* /*
** Customize the progress-bar color ** Customize the progress-bar color
*/ */
loading: { color: '#fff' }, // loading: { color: '#fff' },
/* /*
** Global CSS ** Global CSS
*/ */
css: [ css: [
'element-ui/lib/theme-chalk/index.css',
'bootstrap/dist/css/bootstrap.css', 'bootstrap/dist/css/bootstrap.css',
'bootstrap-vue/dist/bootstrap-vue.css', 'element-ui/lib/theme-chalk/index.css',
'v-calendar/lib/v-calendar.min.css'
], ],
/* /*
** Plugins to load before mounting the App ** Plugins to load before mounting the App
*/ */
plugins: ['@/plugins/element-ui', '@/plugins/filters', plugins: [
'@/plugins/i18n', '@/plugins/bootstrap-vue', '@/plugins/element-ui', // UI library -> https://element.eleme.io/#/en-US/
'@/plugins/vue-awesome', '@/plugins/filters', // text filters, datetime, etc.
{ src: '@/plugins/v-calendar', ssr: false }, '@/plugins/i18n', // localization plugin
{ src: '@/plugins/vuex-persist.js', ssr: false }, '@/plugins/vue-awesome', // icon
'@/plugins/magic-grid'], { src: '@/plugins/v-calendar', ssr: false }, // calendar, TO-REDO
'@/plugins/initialize'
],
/* /*
** Nuxt.js modules ** Nuxt.js modules
@@ -57,18 +56,18 @@ module.exports = {
** Axios module configuration ** Axios module configuration
*/ */
axios: { axios: {
baseURL: '', baseURL: SHARED_CONF.baseurl + '/api',
browserBaseURL: SHARED_CONF.baseurl + '/api',
prefix: '/api', prefix: '/api',
credentials: true // credentials: true
// See https://github.com/nuxt-community/axios-module#options // See https://github.com/nuxt-community/axios-module#options
}, },
auth: { auth: {
strategies: { strategies: {
local: { local: {
endpoints: { endpoints: {
login: { url: '/auth/login', method: 'post', propertyName: 'token' }, login: { url: '/auth/login', method: 'post', propertyName: 'token' },
logout: { url: '/auth/logout', method: 'post' }, logout: false,
user: { url: '/auth/user', method: 'get', propertyName: false } user: { url: '/auth/user', method: 'get', propertyName: false }
}, },
} }
@@ -80,12 +79,14 @@ module.exports = {
** Build configuration ** Build configuration
*/ */
build: { build: {
transpile: [/^element-ui/, /^vue-awesome/, /^vue-magic-grid/, /^vuex-persist/], transpile: [/^element-ui/, /^vue-awesome/],
splitChunks: {
layouts: true
}
/* /*
** You can extend webpack config here ** You can extend webpack config here
*/ */
extend(config, ctx) { // extend(config, ctx) {
// Run ESLint on save // Run ESLint on save
// if (ctx.isDev && ctx.isClient) { // if (ctx.isDev && ctx.isClient) {
// config.module.rules.push({ // config.module.rules.push({
@@ -95,6 +96,6 @@ module.exports = {
// exclude: /(node_modules)/ // exclude: /(node_modules)/
// }) // })
// } // }
} // }
} }
} }

View File

@@ -18,31 +18,33 @@
"axios": "^0.18.0", "axios": "^0.18.0",
"bcrypt": "^3.0.5", "bcrypt": "^3.0.5",
"body-parser": "^1.18.3", "body-parser": "^1.18.3",
"bootstrap-vue": "^2.0.0-rc.16", "bootstrap": "4.3.1",
"cookie-parser": "^1.4.4", "cookie-parser": "^1.4.4",
"cors": "^2.8.5", "cors": "^2.8.5",
"cross-env": "^5.2.0", "cross-env": "^5.2.0",
"dayjs": "^1.8.11", "dayjs": "^1.8.11",
"element-ui": "^2.4.11", "element-ui": "^2.8.2",
"email-templates": "^5.0.4", "email-templates": "^5.0.4",
"express": "^4.16.4", "express": "^4.16.4",
"express-jwt": "^5.3.1", "express-jwt": "^5.3.1",
"ics": "^2.13.2", "ics": "^2.13.2",
"js-cookie": "^2.2.0", "js-cookie": "^2.2.0",
"jsonwebtoken": "^8.5.1", "jsonwebtoken": "^8.5.1",
"less": "^3.9.0",
"less-loader": "^5.0.0",
"mastodon-api": "^1.3.0", "mastodon-api": "^1.3.0",
"morgan": "^1.9.1", "morgan": "^1.9.1",
"multer": "^1.4.1", "multer": "^1.4.1",
"nuxt": "^2.4.0", "nuxt": "^2.4.0",
"pg": "^7.10.0", "pg": "^7.10.0",
"sequelize": "^5.2.1", "sequelize": "^5.2.1",
"sequelize-cli": "^5.4.0",
"sharp": "^0.22.0", "sharp": "^0.22.0",
"sqlite3": "^4.0.6", "sqlite3": "^4.0.6",
"v-calendar": "^0.9.7", "v-calendar": "^1.0.0-beta.10",
"vue-awesome": "^3.5.1", "vue-awesome": "^3.5.1",
"vue-custom-element": "^3.2.6", "vue-custom-element": "^3.2.6",
"vue-i18n": "^8.10.0", "vue-i18n": "^8.10.0",
"vue-magic-grid": "^0.0.4",
"vuex-persist": "^2.0.0" "vuex-persist": "^2.0.0"
}, },
"devDependencies": { "devDependencies": {

View File

@@ -1,6 +1,6 @@
<template lang="pug"> <template lang="pug">
b-modal(hide-footer @hidden='$router.replace("/")' :title='$t("About")' el-dialog(:title='$t("common.info")' visible
:visible='true' size='lg') :before-close='close')
h5 Chi siamo h5 Chi siamo
p. p.
Gancio e' un progetto dell'<a href='https://autistici.org/underscore'>underscore hacklab</a> e uno dei Gancio e' un progetto dell'<a href='https://autistici.org/underscore'>underscore hacklab</a> e uno dei
@@ -18,11 +18,9 @@
blockquote. blockquote.
Se vieni a Torino e dici: "ehi, ci diamo un gancio alle 8?" nessuno si presenterà con i guantoni per fare a mazzate. Se vieni a Torino e dici: "ehi, ci diamo un gancio alle 8?" nessuno si presenterà con i guantoni per fare a mazzate.
Darsi un gancio vuol dire beccarsi alle ore X in un posto Y Darsi un gancio vuol dire beccarsi alle ore X in un posto Y
p li A: a che ora è il gancio in radio per andare al presidio?
small A: a che ora è il gancio in radio per andare al presidio? li B: non so ma domani non posso venire, ho gia' un gancio per caricare il bar.
p br
small B: non so ma domani non posso venire, ho gia' un gancio per caricare il bar.
h5 Contatti h5 Contatti
p. p.
@@ -31,4 +29,19 @@
<a href='https://git.lattuga.net/cisti/gancio'>qui</a>. Aiuti e suggerimenti sono sempre benvenuti, puoi scriverci <a href='https://git.lattuga.net/cisti/gancio'>qui</a>. Aiuti e suggerimenti sono sempre benvenuti, puoi scriverci
su underscore chicciola autistici.org su underscore chicciola autistici.org
</template> </template>
<script>
export default {
data () {
return {
open: true,
}
},
methods: {
close (done) {
this.$router.replace('/')
done()
}
}
}
</script>

View File

@@ -1,8 +1,7 @@
<template lang="pug"> <template lang="pug">
b-modal(ref='modal' @hidden='$router.replace("/")' size='lg' :visible='true' el-dialog(:before-close='close' :visible='open' :title="edit?$t('common.edit_event'):$t('common.add_event')")
:title="edit?$t('common.edit_event'):$t('common.add_event')" hide-footer) el-form(v-loading='loading')
el-form el-tabs.mb-2(v-model='activeTab')
el-tabs.mb-2(v-model='activeTab' v-loading='sending')
//- NOT LOGGED EVENT //- NOT LOGGED EVENT
el-tab-pane(v-if='!$auth.loggedIn') el-tab-pane(v-if='!$auth.loggedIn')
@@ -12,19 +11,28 @@
//- WHERE //- WHERE
el-tab-pane el-tab-pane
span(slot='label') {{$t('common.where')}} <v-icon name='map-marker-alt'/> span(slot='label') <v-icon name='map-marker-alt'/> {{$t('common.where')}}
div {{$t('common.where')}} div {{$t('common.where')}}
el-popover( el-popover(
placement="top-start" placement="top-start"
width="400" width="400"
trigger="hover") trigger="click")
v-icon(slot='reference' color='#ff9fc4' name='question-circle') v-icon(slot='reference' color='#ff9fc4' name='question-circle')
slot slot
p {{$t('event.where_description')}} p(v-html="$t('event.where_description')")
el-select.mb-3(v-model='event.place.name' @change='placeChoosed' filterable allow-create default-first-option)
el-select.mb-3(v-model='event.place.name'
@change='placeChoosed'
filterable allow-create
default-first-option
)
el-option(v-for='place in places_name' :label='place' :value='place' :key='place.id') el-option(v-for='place in places_name' :label='place' :value='place' :key='place.id')
div {{$t("common.address")}} br
el-input.mb-3(ref='address' v-model='event.place.address' :disabled='places_name.indexOf(event.place.name)>-1' @keydown.native.enter='next') br
div {{$t("common.address")}} {{event.place.name}}
el-input.mb-3(ref='address' v-model='event.place.address'
:disabled='places_name.indexOf(event.place.name)>-1'
@keydown.native.enter='next')
el-button.float-right(@click='next' :disabled='!couldProceed') {{$t('common.next')}} el-button.float-right(@click='next' :disabled='!couldProceed') {{$t('common.next')}}
//- WHEN //- WHEN
@@ -32,15 +40,27 @@
span(slot='label') {{$t('common.when')}} <v-icon name='clock'/> span(slot='label') {{$t('common.when')}} <v-icon name='clock'/>
span {{event.multidate ? $t('event.dates_description') : $t('event.date_description')}} span {{event.multidate ? $t('event.dates_description') : $t('event.date_description')}}
el-switch.float-right(v-model='event.multidate' :active-text="$t('event.multidate_description')") el-switch.float-right(v-model='event.multidate' :active-text="$t('event.multidate_description')")
v-date-picker.mb-3(:mode='event.multidate ? "range" : "single"' v-model='date' is-inline
is-expanded :min-date='new Date()' @input='date ? $refs.time_start.focus() : false') v-date-picker.mb-3(
div {{$t('event.time_start_description')}} :mode='event.multidate ? "range" : "single"'
el-time-select.mb-3(ref='time_start' :attributes='attributes'
v-model="time.start" v-model='date'
:picker-options="{ start: '00:00', step: '00:30', end: '24:00'}") is-inline
div {{$t('event.time_end_description')}} is-expanded
el-time-select(v-model='time.end' :min-date='new Date()'
:picker-options="{start: '00:00', step: '00:30', end: '24:00'}") )
el-row
el-col(:span='12')
div {{$t('event.time_start_description')}}
el-time-select.mb-3(ref='time_start'
v-model="time.start"
:picker-options="{ start: '00:00', step: '00:30', end: '24:00'}")
div {{$t('event.time_end_description')}}
el-time-select(v-model='time.end'
:picker-options="{start: '00:00', step: '00:30', end: '24:00'}")
el-col(:span='12')
List(:events='todayEvents' :title='$t("event.same_day")')
el-button.float-right(@click='next' :disabled='!couldProceed') {{$t('common.next')}} el-button.float-right(@click='next' :disabled='!couldProceed') {{$t('common.next')}}
//- WHAT //- WHAT
@@ -61,35 +81,45 @@
el-tab-pane el-tab-pane
span(slot='label') {{$t('common.media')}} <v-icon name='image'/> span(slot='label') {{$t('common.media')}} <v-icon name='image'/>
span {{$t('event.media_description')}} el-upload.text-center(
b-form-file.mb-2(v-model='event.image', :placeholder='$t("common.poster")' accept='image/*') action=''
el-button.float-right(@click='done') {{edit?$t('common.edit'):$t('common.send')}} :limit="1"
:auto-upload='false'
drag
:on-change='uploadedFile'
:multiple='false'
:file-list="fileList"
)
i.el-icon-upload
div.el-upload__text {{$t('event.media_description')}}
el-button.float-right(@click='done' :disabled='!couldProceed') {{edit?$t('common.edit'):$t('common.send')}}
</template> </template>
<script> <script>
// import api from '@/plugins/api' import { mapActions, mapState, mapGetters } from 'vuex'
import { mapActions, mapState } from 'vuex'
import moment from 'dayjs' import moment from 'dayjs'
import Calendar from '@/components/Calendar' import List from '@/components/List'
import { Message } from 'element-ui' import { Message } from 'element-ui'
export default { export default {
components: { Calendar }, name: 'Add',
components: { List },
data() { data() {
return { return {
event: { event: {
place: { name: '', address: '' }, place: { name: '', address: '' },
title: '', description: '', tags: [], title: '', description: '', tags: [],
multidate: false, multidate: false,
image: false
}, },
visible: true, fileList: [],
open: true,
id: null, id: null,
activeTab: "0", activeTab: "0",
date: null, date: null,
time: { start: '20:00', end: null }, time: { start: '20:00', end: null },
edit: false, edit: false,
sending: false, loading: true,
} }
}, },
name: 'newEvent', name: 'newEvent',
@@ -100,11 +130,10 @@ export default {
} }
}, },
async mounted () { async mounted () {
if (this.$route.params.id) { if (this.$route.params.edit) {
this.id = this.$route.params.id this.id = this.$route.params.edit
this.edit = true this.edit = true
const event = await api.getEvent(this.id) const event = await this.$axios.$get('/event/'+ this.id)
// this.event.place = {name: event.place.name, address: event.place.address }
this.event.place.name = event.place.name this.event.place.name = event.place.name
this.event.place.address = event.place.address || '' this.event.place.address = event.place.address || ''
this.event.multidate = event.multidate this.event.multidate = event.multidate
@@ -119,6 +148,7 @@ export default {
} }
} }
this.updateMeta() this.updateMeta()
this.loading = false
}, },
computed: { computed: {
...mapState({ ...mapState({
@@ -126,12 +156,18 @@ export default {
places_name: state => state.places.map(p => p.name ), places_name: state => state.places.map(p => p.name ),
places: state => state.places, places: state => state.places,
user: state => state.user, user: state => state.user,
events: state => state.events
}), }),
todayEvents () {
const date = moment(this.date)
return this.events.filter(e => date.isSame(moment(e.start_datetime), 'day'))
},
...mapGetters(['filteredEvents']),
attributes () {
return this.events.filter(e => !e.past).map(this.eventToAttribute)
},
disableAddress () { disableAddress () {
console.log('dentro disable Address') return this.places_name.find(p => p.name === this.event.place.name)
const ret = this.places_name.find(p => p.name === this.event.place.name)
console.log(ret)
return ret
}, },
couldProceed () { couldProceed () {
const t = this.$auth.loggedIn ? -1 : 0 const t = this.$auth.loggedIn ? -1 : 0
@@ -143,18 +179,45 @@ export default {
this.event.place.address.length>0 this.event.place.address.length>0
case 2+t: case 2+t:
if (this.date && this.time.start) return true if (this.date && this.time.start) return true
break
case 3+t: case 3+t:
return this.event.title.length>0 return this.event.title.length>0
break
case 4+t: case 4+t:
return true return this.event.place.name.length>0 &&
break this.event.place.address.length>0 &&
(this.date && this.time.start) &&
this.event.title.length>0
} }
} }
}, },
methods: { methods: {
...mapActions(['addEvent', 'updateEvent', 'updateMeta']), ...mapActions(['addEvent', 'updateEvent', 'updateMeta']),
close (done) {
this.$router.replace('/')
done()
},
eventToAttribute(event) {
let e = {
key: event.id,
customData: event,
order: event.start_datetime,
}
const day = moment(event.start_datetime).date()
let color = event.tags && event.tags.length && event.tags[0].color ? event.tags[0].color : 'rgba(170,170,250,0.7)'
if (event.past) color = 'rgba(200,200,200,0.5)'
if (event.multidate) {
e.dates = {
start: event.start_datetime, end: event.end_datetime
}
e.highlight = { backgroundColor: color,
// borderColor: 'transparent',
borderWidth: '4px' }
} else {
e.dates = event.start_datetime
e.dot = { backgroundColor: color, borderColor: color, borderWidth: '3px' }
}
return e
},
next () { next () {
this.activeTab = String(Number(this.activeTab)+1) this.activeTab = String(Number(this.activeTab)+1)
if (this.activeTab === "2") { if (this.activeTab === "2") {
@@ -171,6 +234,9 @@ export default {
} }
this.$refs.address.focus() this.$refs.address.focus()
}, },
uploadedFile(file, fileList) {
this.event.image = file
},
async done () { async done () {
let start_datetime, end_datetime let start_datetime, end_datetime
const [ start_hour, start_minute ] = this.time.start.split(':') const [ start_hour, start_minute ] = this.time.start.split(':')
@@ -191,7 +257,7 @@ export default {
const formData = new FormData() const formData = new FormData()
if (this.event.image) { if (this.event.image) {
formData.append('image', this.event.image, this.event.image.name) formData.append('image', this.event.image.raw, this.event.image.name)
} }
formData.append('title', this.event.title) formData.append('title', this.event.title)
formData.append('place_name', this.event.place.name) formData.append('place_name', this.event.place.name)
@@ -205,7 +271,7 @@ export default {
} }
if (this.event.tags) if (this.event.tags)
this.event.tags.forEach(tag => formData.append('tags[]', tag)) this.event.tags.forEach(tag => formData.append('tags[]', tag))
this.sending = true this.loading = true
try { try {
if (this.edit) { if (this.edit) {
await this.updateEvent(formData) await this.updateEvent(formData)
@@ -213,11 +279,11 @@ export default {
await this.addEvent(formData) await this.addEvent(formData)
} }
this.updateMeta() this.updateMeta()
this.sending = false this.loading = false
this.$refs.modal.hide() this.$router.replace('/')
Message({ type: 'success', message: this.$auth.loggedIn ? this.$t('event.added') : this.$t('event.added_anon')}) Message({ type: 'success', message: this.$auth.loggedIn ? this.$t('event.added') : this.$t('event.added_anon')})
} catch (e) { } catch (e) {
this.sending = false this.loading = false
console.error(e) console.error(e)
} }
} }

View File

@@ -1,6 +1,5 @@
<template lang="pug"> <template lang="pug">
b-modal(hide-footer @hidden='$router.replace("/")' :title='$t("common.admin")' el-dialog(:title='$t("common.admin")' width='80%' :visible='open' :before-close='close')
:visible='true' size='lg')
el-tabs(tabPosition='left' v-model='tab') el-tabs(tabPosition='left' v-model='tab')
//- USERS //- USERS
@@ -35,7 +34,7 @@
el-form-item(:label="$t('common.address')") el-form-item(:label="$t('common.address')")
el-input.mr-1(:placeholder='$t("common.address")' v-model='place.address') el-input.mr-1(:placeholder='$t("common.address")' v-model='place.address')
el-button(variant='primary' @click='savePlace') {{$t('common.save')}} el-button(variant='primary' @click='savePlace') {{$t('common.save')}}
el-table(:data='paginatedPlaces' small) el-table(:data='paginatedPlaces' small @current-change="val => place=val")
el-table-column(:label="$t('common.name')") el-table-column(:label="$t('common.name')")
template(slot-scope='data') {{data.row.name}} template(slot-scope='data') {{data.row.name}}
el-table-column(:label="$t('common.address')") el-table-column(:label="$t('common.address')")
@@ -61,26 +60,26 @@
el-pagination(:page-size='perPage' :currentPage.sync='eventPage' :total='events.length') el-pagination(:page-size='perPage' :currentPage.sync='eventPage' :total='events.length')
//- TAGS //- TAGS
el-tab-pane.pt-1 //- el-tab-pane.pt-1
template(slot='label') //- template(slot='label')
v-icon(name='tag') //- v-icon(name='tags')
span {{$t('common.tags')}} //- span {{$t('common.tags')}}
p {{$t('admin.tag_description')}} //- p {{$t('admin.tag_description')}}
el-tag(v-if='tag.tag' :color='tag.color' size='mini') {{tag.tag}} //- el-tag(v-if='tag.tag' :color='tag.color' size='mini') {{tag.tag}}
el-form(:inline='true' label-width='120px') //- el-form(:inline='true' label-width='120px')
el-form-item(:label="$t('common.color')") //- el-form-item(:label="$t('common.color')")
el-color-picker(v-model='tag.color' @change='updateColor') //- el-color-picker(v-model='tag.color' @change='updateColor')
el-table(:data='paginatedTags' striped small hover //- el-table(:data='paginatedTags' striped small hover
highlight-current-row @current-change="tagSelected") //- highlight-current-row @current-change="tagSelected")
el-table-column(:label="$t('common.tag')") //- el-table-column(:label="$t('common.tag')")
template(slot-scope='data') //- template(slot-scope='data')
el-tag(:color='data.row.color' size='mini') {{data.row.tag}} //- el-tag(:color='data.row.color' size='mini') {{data.row.tag}}
el-pagination(:page-size='perPage' :currentPage.sync='tagPage' :total='tags.length') //- el-pagination(:page-size='perPage' :currentPage.sync='tagPage' :total='tags.length')
//- SETTINGS //- SETTINGS
el-tab-pane.pt-1 el-tab-pane.pt-1
template(slot='label') template(slot='label')
v-icon(name='tools') v-icon(name='cog')
span {{$t('common.settings')}} span {{$t('common.settings')}}
el-form(inline @submit.prevent.stop='associatemastodon_instance') el-form(inline @submit.prevent.stop='associatemastodon_instance')
span {{$t('admin.mastodon_description')}} span {{$t('admin.mastodon_description')}}
@@ -91,7 +90,6 @@
</template> </template>
<script> <script>
import { mapState } from 'vuex' import { mapState } from 'vuex'
import api from '@/plugins/api'
import { Message } from 'element-ui' import { Message } from 'element-ui'
export default { export default {
@@ -116,22 +114,18 @@ export default {
mastodon_instance: '', mastodon_instance: '',
settings: {}, settings: {},
tab: "0", tab: "0",
open: true
} }
}, },
async mounted () { async mounted () {
console.log('sono dentro mounted', this.$route)
const code = this.$route.query.code const code = this.$route.query.code
if (code) { if (code) {
this.tab = "4" this.tab = "4"
const instance = await this.$axios.$post('/user/code', {code, is_admin: true}) const instance = await this.$axios.$post('/user/code', {code, is_admin: true})
} }
// // this.users = await api.getUsers()
// // this.events = await api.getUnconfirmedEvents()
// // this.settings = await api.getAdminSettings()
}, },
async asyncData ({ $axios, params, store }) { async asyncData ({ $axios, params, store }) {
console.log(store.state)
try { try {
const users = await $axios.$get('/users') const users = await $axios.$get('/users')
const events = await $axios.$get('/event/unconfirmed') const events = await $axios.$get('/event/unconfirmed')
@@ -158,7 +152,7 @@ export default {
paginatedPlaces () { paginatedPlaces () {
return this.places.slice((this.placePage-1) * this.perPage, return this.places.slice((this.placePage-1) * this.perPage,
this.placePage * this.perPage) this.placePage * this.perPage)
}, },
}, },
methods: { methods: {
placeSelected (items) { placeSelected (items) {
@@ -175,15 +169,15 @@ export default {
this.tag = { color: tag.color, tag: tag.tag } this.tag = { color: tag.color, tag: tag.tag }
}, },
async savePlace () { async savePlace () {
const place = await api.updatePlace(this.place) // const place = await api.updatePlace(this.place)
}, },
async toggle(user) { async toggle(user) {
user.is_active = !user.is_active user.is_active = !user.is_active
const newuser = await api.updateUser(user) // const newuser = await api.updateUser(user)
}, },
async toggleAdmin(user) { async toggleAdmin(user) {
user.is_admin = !user.is_admin user.is_admin = !user.is_admin
const newuser = await api.updateUser(user) // const newuser = await api.updateUser(user)
}, },
async updateColor () { async updateColor () {
// try { // try {
@@ -198,7 +192,7 @@ export default {
async associate () { async associate () {
if (!this.mastodon_instance) return if (!this.mastodon_instance) return
const url = await this.$axios.$post('/user/getauthurl', {instance: this.mastodon_instance, admin: true}) const url = await this.$axios.$post('/settings/getauthurl', {instance: this.mastodon_instance})
setTimeout( () => window.location.href=url, 100); setTimeout( () => window.location.href=url, 100);
}, },
async confirm (id) { async confirm (id) {
@@ -207,13 +201,18 @@ export default {
await this.$axios.$get(`/event/confirm/${id}`) await this.$axios.$get(`/event/confirm/${id}`)
this.loading = false this.loading = false
Message({ Message({
message: this.$t('event_confirmed'), message: this.$t('common.event_confirmed'),
type: 'success' type: 'success'
}) })
this.events = this.events.filter(e => e.id !== id) this.events = this.events.filter(e => e.id !== id)
} catch (e) { } catch (e) {
} }
} },
close (done) {
console.log('oppure qui !')
this.$router.replace('/')
// done()
}
} }
} }
</script> </script>

View File

@@ -1,22 +1,26 @@
<template lang="pug"> <template lang="pug">
div List(:events="events" :title='title')
p porcodio
</template> </template>
<script> <script>
import { mapState } from 'vuex' import { mapState } from 'vuex'
// import List from '../../components/List' import { SHARED_CONF } from '../../config'
import List from '../../components/List'
import moment from 'dayjs' import moment from 'dayjs'
export default { export default {
name: 'diocane',
layout: 'iframe', layout: 'iframe',
// components: { List }, components: { List },
async asyncData ({ $axios, req, res }) { async asyncData ({ $axios, req, res }) {
const title = req.query.title || SHARED_CONF.title
const show_tags = req.query.showtags const show_tags = req.query.showtags
const tags = req.query.tags const tags = req.query.tags
const places = req.query.places const places = req.query.places
const events = await $axios.$get('/export/json') const now = new Date()
return { events, show_tags }
// TODO: filter future events based on tags/places/userid
const events = await $axios.$get(`/event/${now.getMonth()}/${now.getFullYear()}`)
return { show_tags, events, title }
}, },
} }
</script> </script>

View File

@@ -1,54 +1,81 @@
<template lang="pug"> <template lang="pug">
b-modal#eventDetail(ref='eventDetail' hide-body hide-header hide-footer @hidden='$router.replace("/")' size='lg' :visible='true') el-card#eventDetail(
b-card(no-body, :img-src='imgPath' v-loading='loading') visible hide-header
nuxt-link(to='/') no-header :show-close='false'
el-button.close_button(circle icon='el-icon-close' type='success' top='0vh !important'
@click.prevent='$refs.eventDetail.hide()') :appendToBody='true')
b-card-header
h3 {{event.title}}
v-icon(name='clock')
span {{event.start_datetime|datetime}}
br
v-icon(name='map-marker-alt')
span {{event.place.name}} - {{event.place.address}}
br
b-card-body(v-if='event.description || event.tags')
pre(v-html='event.description')
el-tag.mr-1(:color='tag.color' v-for='tag in event.tags'
size='mini' :key='tag.tag') {{tag.tag}}
div(v-if='mine')
hr
el-button(v-if='event.is_visible' plain type='warning' @click.prevents='toggle' icon='el-icon-view') {{$t('common.hide')}}
el-button(v-else plain type='success' @click.prevents='toggle' icon='el-icon-view') {{$t('common.confirm')}}
el-button(plain type='danger' @click.prevent='remove' icon='el-icon-remove') {{$t('common.remove')}}
el-button(plain type='primary' @click='$router.replace("/edit/"+event.id)') <v-icon color='orange' name='edit'/> {{$t('common.edit')}}
b-card-body(v-if='event.activitypub_id') //- close button
strong {{$t('common.resources')}} - nuxt-link.float-right(to='/')
el-button(circle icon='el-icon-close' type='danger' size='small' plain)
//- title, where, when
h5.text-center {{event.title}}
div.nextprev
nuxt-link(v-if='prev' :to='`/event/${prev.id}`')
el-button(icon='el-icon-arrow-left' round size='small' type='success' plain)
nuxt-link.float-right(v-if='next' :to='`/event/${next.id}`')
el-button(icon='el-icon-arrow-right' round size='small' plain type='success')
//- image
img(:src='imgPath' v-if='event.image_path')
.info
div {{event|event_when}}
div {{event.place.name}} - {{event.place.address}}
//- description and tags
div(v-if='event.description || event.tags')
pre(v-html='event.description')
el-tag.mr-1(v-for='tag in event.tags'
size='mini' :key='tag.tag') {{tag.tag}}
//- show hide, confirm, delete, edit buttons when allowed
div(v-if='mine')
hr
el-button(v-if='event.is_visible' size='mini' plain type='warning' @click.prevents='toggle' icon='el-icon-view') {{$t('common.hide')}}
el-button(v-else plain type='success' size='mini' @click.prevents='toggle' icon='el-icon-view') {{$t('common.confirm')}}
el-button(plain type='danger' size='mini' @click.prevent='remove' icon='el-icon-remove') {{$t('common.remove')}}
el-button(plain type='primary' size='mini' @click='$router.replace(`/add/${event.id}`)' icon='el-icon-edit') {{$t('common.edit')}}
//- comments
.card-body(v-if='event.activitypub_id')
strong {{$t('common.related')}} -
a(:href='`https://mastodon.cisti.org/web/statuses/${event.activitypub_id}`') {{$t('common.add')}} a(:href='`https://mastodon.cisti.org/web/statuses/${event.activitypub_id}`') {{$t('common.add')}}
b-card-header(v-for='comment in event.comments' :key='comment.id') .card-header(v-for='comment in event.comments' :key='comment.id')
img.avatar(:src='comment.data.last_status.account.avatar') img.avatar(:src='comment.data.last_status.account.avatar')
strong {{comment.author}} strong {{comment.author}}
a.float-right(:href='comment.data.last_status.url') a.float-right(:href='comment.data.last_status.url')
small {{comment.data.last_status.created_at|datetime}} small {{comment.data.last_status.created_at|datetime}}
div.mt-1(v-html='comment_filter(comment.text)') div.mt-1(v-html='comment_filter(comment.text)')
img(v-for='img in comment.data.last_status.media_attachments' :src='img.preview_url') img(v-for='img in comment.data.last_status.media_attachments' :src='img.preview_url')
//- span {{comment}}
</template> </template>
<script> <script>
import { mapState, mapActions } from 'vuex'; import { mapState, mapActions, mapGetters } from 'vuex'
// import api from '@/plugins/api' import config from '@/config'
//import filters from '@/filters'
export default { export default {
name: 'Event', name: 'Event',
// transition: null,
// Watch for $route.query.page to call Component methods (asyncData, fetch, validate, layout, etc.)
// watchQuery: ['id'],
// Key for <NuxtChild> (transitions)
// key: to => to.fullPath,
// Called to know which transition to apply
// transition(to, from) {
// console.log('dentro transition')
// if (!from) return 'slide-left'
// return +to.params.id < +from.params.id ? 'slide-right' : 'slide-left'
// },
head () { head () {
return { return {
title: this.event.title, title: this.event.title,
meta: [ meta: [
// hid is used as unique identifier. Do not use `vmid` for it as it will not work // hid is used as unique identifier. Do not use `vmid` for it as it will not work
{ hid: 'description', name: 'description', content: this.event.description }, // { hid: 'description', name: 'description', content: this.event.description },
{ hid: 'og-description', name: 'og:description', content: this.event.description }, // { hid: 'og-description', name: 'og:description', content: this.event.description },
{ hid: 'og-title', property: 'og:title', content: this.event.title }, { hid: 'og-title', property: 'og:title', content: this.event.title },
{ hid: 'og-url', property: 'og:url', content: `event/${this.event.id}` }, { hid: 'og-url', property: 'og:url', content: `event/${this.event.id}` },
{ property: 'og:type', content: 'event'}, { property: 'og:type', content: 'event'},
@@ -57,33 +84,43 @@ export default {
} }
}, },
computed: { computed: {
...mapState([]), ...mapGetters(['filteredEvents']),
next () {
let found = false
return this.filteredEvents.find(e => {
if (found) return e
if (e.id === this.event.id) found = true
})
},
prev () {
let prev = false
this.filteredEvents.find(e => {
if (e.id === this.event.id) return true
prev = e
})
return prev
},
imgPath () { imgPath () {
return this.event.image_path && '/media/' + this.event.image_path return this.event.image_path && '/media/' + this.event.image_path
}, },
mine () { mine () {
if (!this.$auth.user) return false
return this.event.userId === this.$auth.user.id || this.$auth.user.is_admin return this.event.userId === this.$auth.user.id || this.$auth.user.is_admin
}, },
}, },
data () {
return {
event: { comments: [], place: {}, title: ''},
id: null,
loading: true,
}
},
async asyncData ( { $axios, params }) { async asyncData ( { $axios, params }) {
const event = await $axios.$get(`/event/${params.id}`) const event = await $axios.$get(`/event/${params.id}`)
return { event, id: params.id, loading: false } return { event, id: params.id}
}, },
methods: { methods: {
...mapActions(['delEvent']), ...mapActions(['delEvent']),
keydown (e) {
console.error(e)
},
comment_filter (value) { comment_filter (value) {
console.log('dentro comment_filter')
return value.replace(/<a.*href="([^">]+).*>(?:.(?!\<\/a\>))*.<\/a>/, (orig, url) => { return value.replace(/<a.*href="([^">]+).*>(?:.(?!\<\/a\>))*.<\/a>/, (orig, url) => {
// get extension // get extension
const ext = url.slice(-4) const ext = url.slice(-4)
console.log('dentro il replace ', ext)
if (['.mp3', '.ogg'].indexOf(ext)>-1) { if (['.mp3', '.ogg'].indexOf(ext)>-1) {
return `<audio controls><source src='${url}'></audio>` return `<audio controls><source src='${url}'></audio>`
} else { } else {
@@ -92,9 +129,13 @@ export default {
}) })
}, },
async remove () { async remove () {
await api.delEvent(this.event.id) try {
this.delEvent(this.event.id) await this.$axios.delete(`/user/event/${this.id}`)
this.$refs.eventDetail.hide() this.delEvent(Number(this.id))
this.$router.back()
} catch (e) {
console.error(e)
}
}, },
async toggle () { async toggle () {
try { try {
@@ -106,49 +147,60 @@ export default {
this.event.is_visible = true this.event.is_visible = true
} }
} catch (e) { } catch (e) {
console.error(e)
} }
} }
} }
} }
</script> </script>
<style> <style lang='less'>
#eventDetail .avatar { #eventDetail {
height: 40px; max-width: 1000px;
border-radius: 5px; border-radius: 0px;
margin: 0 auto;
pre {
color: #404246;
font-size: 1em;
font-family: BlinkMacSystemFont,-apple-system,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,Helvetica,Arial,sans-serif !important;
}
h5 {
font-size: 1.4em;
min-height: 40px;
}
.info {
margin: 10px;
font-size: 1.3em;
font-weight: 600;
text-align: center;
}
img {
width: 100%;
max-height: 89vh;
object-fit: contain;
}
.avatar {
width: auto;
height: 40px;
border-radius: 5px;
}
.nextprev {
font-size: 10px;
margin-bottom: 5px;
}
} }
#eventDetail .image { @media only screen and (max-width: 768px) {
max-height: 200px; #eventDetail {
font-size: 12px;
}
} }
/* #eventDetail {
display: block !important;
opacity: 1;
} */
#eventDetail .modal-body {
padding: 0px;
width: 100%;
}
#eventDetail .close_button:hover {
background-color: rgba(200, 100, 100, 0.4);
}
#eventDetail .card {
border: 0px;
}
#eventDetail .close_button {
background-color: rgba(100, 100, 100, 0.3);
color: red;
font-size: 20px;
border: 1px dashed rgba(20,20,20,0.3);
position: absolute;
top: 10px;
right: 10px;
}
</style> </style>

View File

@@ -1,13 +1,12 @@
<template lang="pug"> <template lang="pug">
b-modal(ref='modal' @hidden='$router.replace("/")' el-dialog(:title='$t("common.export")' visible :before-close='close')
:title='$t("common.export")' :visible='true' size='lg' hide-footer)
p {{$t('export.intro')}} p {{$t('export.intro')}}
li(v-if='filters.tags.length') {{$t('common.tags')}}: li(v-if='filters.tags.length') {{$t('common.tags')}}:
el-tag.ml-1(color='#409EFF' size='mini' v-for='tag in filters.tags' :key='tag.tag') {{tag}} el-tag.ml-1(size='mini' v-for='tag in filters.tags' :key='tag.tag') {{tag}}
li(v-if='filters.places.length') {{$t('common.places')}}: li(v-if='filters.places.length') {{$t('common.places')}}:
el-tag.ml-1(color='#409EFF' size='mini' v-for='place in filters.places' :key='place.id') {{place}} el-tag.ml-1(size='mini' v-for='place in filters.places' :key='place.id') {{place}}
el-tabs.mt-2(tabPosition='left' v-model='type') el-tabs.mt-2(v-model='type')
el-tab-pane.pt-1(label='email' name='email') el-tab-pane.pt-1(label='email' name='email')
p(v-html='$t(`export.email_description`)') p(v-html='$t(`export.email_description`)')
@@ -15,57 +14,50 @@
//- el-switch(v-model='notification.notify_on_add' :active-text="$t('notify_on_insert')") //- el-switch(v-model='notification.notify_on_add' :active-text="$t('notify_on_insert')")
//- br //- br
//- el-switch.mt-2(v-model='notification.send_notification' :active-text="$t('send_notification')") //- el-switch.mt-2(v-model='notification.send_notification' :active-text="$t('send_notification')")
el-input.mt-2(v-model='notification.email' :placeholder="$t('common.insert_your_address')" ref='email') el-input.mt-2(v-model='notification.email' :placeholder="$t('export.insert_your_address')" ref='email')
el-button.mt-2.float-right(native-type= 'submit' type='success' @click='add_notification') {{$t('Send')}} el-button.mt-2.float-right(native-type= 'submit' type='success' @click='add_notification') {{$t('common.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_description`)') span(v-html='$t(`export.feed_description`)')
el-input(v-model='link') el-input(v-model='link')
el-button(slot='append' plain type="primary" icon='el-icon-document' v-clipboard:copy="link") {{$t("common.copy")}} el-button(slot='append' plain type="primary" icon='el-icon-document' ) {{$t("common.copy")}}
el-tab-pane.pt-1(label='ics/ical' name='ics') el-tab-pane.pt-1(label='ics/ical' name='ics')
p(v-html='$t(`export.ical_description`)') p(v-html='$t(`export.ical_description`)')
el-input(v-model='link') el-input(v-model='link')
el-button(slot='append' plain type="primary" icon='el-icon-document' v-clipboard:copy="link") {{$t("common.opy")}} el-button(slot='append' plain type="primary" icon='el-icon-document') {{$t("common.copy")}}
el-tab-pane.pt-1(label='list' name='list') el-tab-pane.pt-1(label='list' name='list')
p(v-html='$t(`export.list_description`)') p(v-html='$t(`export.list_description`)')
//- el-form-item(:label="$t('export.show_tags')")
el-switch(v-model='list.show_tags') el-row
el-col.mr-2(:span='11')
iframe(:src='`http://localhost:3000/embed/list?tags=cia&showtags=${list.show_tags?"true":""}`' height='300') el-input(v-model='list.title') Title
//- el-card.mb-1(no-body header='Eventi') el-col.float-right(:span='12')
//- b-list-group#list(flush) List(
//- b-list-group-item.flex-column.align-items-start(v-for="event in filteredEvents" :key='event.id' :title='list.title'
//- :to='`/event/${event.id}`') :events='filteredEvents'
//- //- b-media )
//- img(v-if='event.image_path' slot="aside" :src="imgPath(event)" alt="Meia Aside" style='max-height: 60px') el-input.mb-1(type='textarea' v-model='listScript' readonly )
//- small.float-right {{event.start_datetime|datetime}} el-button.float-right(plain type="primary" icon='el-icon-document') {{$t('common.copy')}}
//- strong.mb-1 {{event.title}}
//- br
//- small.float-right {{event.place.name}}
//- 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-button.float-right(plain type="primary" icon='el-icon-document' v-clipboard:copy="script") Copy
el-tab-pane.pt-1(label='calendar' name='calendar') //- el-tab-pane.pt-1(label='calendar' name='calendar')
p(v-html='$t(`export.calendar_description`)') //- p(v-html='$t(`export.calendar_description`)')
//- no-ssr //- //- no-ssr
Calendar.mb-1 //- Calendar.mb-1
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') Copy
</template> </template>
<script> <script>
import { mapState } from 'vuex' import { mapState, mapGetters } from 'vuex'
import path from 'path' import path from 'path'
// import filters from '../filters'
import Calendar from '@/components/Calendar' import Calendar from '@/components/Calendar'
import List from '@/components/List' import List from '@/components/List'
import {intersection} from 'lodash' import {intersection} from 'lodash'
// import api from '@/api'
import { Message } from 'element-ui' import { Message } from 'element-ui'
const { SHARED_CONF } = require('@/config')
export default { export default {
name: 'Export', name: 'Export',
@@ -73,33 +65,40 @@ export default {
data () { data () {
return { return {
type: 'email', type: 'email',
link: '',
export_list: true,
script: `<iframe>Ti piacerebbe</iframe>`,
notification: { email: '' }, notification: { email: '' },
list: { show_tags: true }, list: { title: SHARED_CONF.title },
} }
}, },
// filters, // filters,
mounted () {
this.link = this.loadLink()
},
watch: {
type (value) {
this.link = this.loadLink()
}
},
methods: { methods: {
async add_notification () { async add_notification () {
if (!this.notification.email){ if (!this.notification.email){
Message({message:'Inserisci una mail', type: 'error'}) Message({message:'Inserisci una mail', type: 'error'})
return this.$refs.email.focus() return this.$refs.email.focus()
} }
await api.addNotification({ ...this.notification, filters: this.filters}) // await api.addNotification({ ...this.notification, filters: this.filters})
this.$refs.modal.hide() // this.$refs.modal.hide()
Message({message: this.$t('email_notification_activated'), type: 'success'}) Message({message: this.$t('email_notification_activated'), type: 'success'})
}, },
loadLink () { imgPath (event) {
return event.image_path && event.image_path
},
close (done) {
this.$router.replace('/')
done()
}
},
computed: {
...mapState(['filters', 'events']),
...mapGetters(['filteredEvents']),
listScript () {
const params = []
if (this.list.title) {
params.push(`title=${this.list.title}`)
}
return `<iframe src="${SHARED_CONF.baseurl}/embed/list?${params.join('&')}"></iframe>`
},
link () {
const tags = this.filters.tags.join(',') const tags = this.filters.tags.join(',')
const places = this.filters.places.join(',') const places = this.filters.places.join(',')
let query = '' let query = ''
@@ -113,17 +112,8 @@ export default {
} }
} }
return `${process.env.VUE_APP_API}/api/export/${this.type}${query}` return `${SHARED_CONF.baseurl}/api/export/${this.type}${query}`
}, },
imgPath (event) {
return event.image_path && event.image_path
},
},
computed: {
...mapState(['filters', 'events']),
filteredEvents () {
return this.$store.getters.filteredEvents.filter(e => !e.past)
},
showLink () { showLink () {
return (['feed', 'ics'].indexOf(this.type)>-1) return (['feed', 'ics'].indexOf(this.type)>-1)
}, },

View File

@@ -1,2 +1,15 @@
<template lang="pug"> <template lang="pug">
#home
Nav
Home
</template> </template>
<script>
import Home from '~/components/Home.vue'
import Nav from '~/components/Nav.vue'
export default {
name: 'Index',
components: { Nav, Home },
}
</script>

View File

@@ -1,15 +1,21 @@
<template lang='pug'> <template lang='pug'>
b-modal(@shown="$refs.email.focus()" :title='$t("common.login")' hide-footer
@hidden='$router.replace("/")' :visible='true' ref='modal') el-dialog(:title='$t("common.login")' :before-close='close' visible)
el-form(v-loading='loading') el-form(v-loading='loading')
p(v-html="$t('login.description')") p(v-html="$t('login.description')")
el-input.mb-2(v-model='email' type='email' :placeholder='$t("common.email")' autocomplete='email' ref='email') el-input.mb-2(v-model='email' type='email' :placeholder='$t("common.email")' autocomplete='email' ref='email')
v-icon(name='user' slot='prepend') i.el-icon-user(slot='prepend')
el-input.mb-1(v-model='password' @keyup.enter.native="submit" type='password' :placeholder='$t("common.password")') el-input.mb-1(v-model='password' @keyup.enter.native="submit" type='password' :placeholder='$t("common.password")')
v-icon(name="lock" slot='prepend') i.el-icon-lock(slot='prepend')
el-button.mr-1(plain type="success" @click='submit') {{$t('common.login')}}
router-link(to='/register') el-button.mr-1(plain type="success" :disabled='!email || !password' @click='submit') {{$t('common.login')}}
nuxt-link(to='/register')
el-button.mt-1(plain type="primary") {{$t('login.not_registered')}} el-button.mt-1(plain type="primary") {{$t('login.not_registered')}}
a.float-right(href='#' @click='forgot') {{$t('login.forgot_password')}} a.float-right(href='#' @click='forgot') {{$t('login.forgot_password')}}
</template> </template>
@@ -17,18 +23,22 @@
const Cookie = process.client ? require('js-cookie') : undefined const Cookie = process.client ? require('js-cookie') : undefined
import { mapActions } from 'vuex' import { mapActions } from 'vuex'
import { Message } from 'element-ui' import { Message } from 'element-ui'
// import api from '@/plugins/api' import get from 'lodash/get'
export default { export default {
name: 'Login', name: 'Login',
data () { data () {
return { return {
open: true,
password: '', password: '',
email: '', email: '',
loading: false loading: false
} }
}, },
methods: { methods: {
close () {
this.$router.replace('/')
},
...mapActions(['login']), ...mapActions(['login']),
async forgot () { async forgot () {
if (!this.email) { if (!this.email) {
@@ -37,7 +47,7 @@ export default {
return return
} }
this.loading = true this.loading = true
// await api.forgotPassword(this.email) await this.$axios.$post('/user/recover', { email: this.email })
this.loading = false this.loading = false
Message({ message: this.$t('login.check_email'), type: 'success' }) Message({ message: this.$t('login.check_email'), type: 'success' })
}, },
@@ -49,12 +59,12 @@ export default {
this.loading = false this.loading = false
Message({ message: this.$t('login.ok'), type: 'success' }) Message({ message: this.$t('login.ok'), type: 'success' })
} catch (e) { } catch (e) {
Message({ message: this.$t('login.error') + e, type: 'error' }) e = get(e, 'response.data.message', e)
Message({ message: this.$t('login.error') + this.$t(e), type: 'error' })
this.loading = false this.loading = false
return return
} }
this.email = this.password = '' this.email = this.password = ''
this.$refs.modal.hide()
} }
} }
} }

View File

@@ -1,9 +1,8 @@
<template lang='pug'> <template lang='pug'>
b-modal(hide-footer @hidden='$router.replace("/")' ref='modal' el-dialog(:title="$t('common.register')" visible :before-close='() => $router.replace("/")' @open='$refs.email.focus()')
:title="$t('common.register')" :visible='true' @shown='$refs.email.focus()')
el-form el-form
p(v-html="$t('register.description')") p(v-html="$t('register.description')")
el-input.mb-2(ref='email' v-model='user.email' type='email' el-input.mb-2(ref='email' v-model='user.email' type='email' required
:placeholder='$t("common.email")' autocomplete='email') :placeholder='$t("common.email")' autocomplete='email')
span(slot='prepend') @ span(slot='prepend') @
@@ -13,11 +12,10 @@
el-input.mb-2(v-model='user.description' type="textarea" rows='3' :placeholder="$t('common.description')") el-input.mb-2(v-model='user.description' type="textarea" rows='3' :placeholder="$t('common.description')")
v-icon(name='envelope-open-text') v-icon(name='envelope-open-text')
el-button.float-right(plain type="success" icon='el-icon-arrow-right' @click='register') {{$t('common.send')}} el-button(plain type="success" icon='el-icon-arrow-right' :disabled='!user.password || !user.email || !user.description' @click='register') {{$t('common.send')}}
</template> </template>
<script> <script>
import api from '@/plugins/api'
import { mapActions } from 'vuex' import { mapActions } from 'vuex'
import { Message } from 'element-ui' import { Message } from 'element-ui'
@@ -28,23 +26,29 @@ export default {
error: {}, error: {},
user: { } user: { }
} }
},
computed: {
}, },
methods: { methods: {
...mapActions(['login']), ...mapActions(['login']),
async register () { async register () {
try { try {
const user = await this.$axios.$post('/user', this.user) const user = await this.$axios.$post('/user', this.user)
this.$refs.modal.hide()
Message({ Message({
message: this.$t(`register.${user.is_admin && 'admin_'}complete`), message: this.$t(`register.${user.is_admin && 'admin_'}complete`),
type: 'success' type: 'success'
}) })
this.$router.replace("/")
} catch (e) { } catch (e) {
console.log('DENTRO CATCH!!!', e)
const error = e && e.response && e.response.data && e.response.data.errors[0].message || e
console.error(error)
console.error(e)
Message({ Message({
message: this.$t('register.error') + e, message: this.$t('register.error') + error,
type: 'error' type: 'error'
}) })
console.error(e)
} }
} }
} }

View File

@@ -1,58 +1,40 @@
<template lang="pug"> <template lang="pug">
b-modal(:title="$t('common.settings')" hide-footer @hidden='$router.replace("/")' :visible='true') el-dialog(:title="$t('common.settings')" :before-close='close' visible)
h5 {{user.name}} //- el-form
el-input(v-model="mastodon_instance" @enter.native='associate') //- el-form-item {{$t('settings.change_password')}}
span(slot='prepend') {{$t('settings.mastodon_instance')}} el-divider {{$t('settings.change_password')}}
el-button(v-if='!user.mastodon_auth' slot='append' @click='associate' type='success') {{$t('settings.associate')}} el-input(v-model='password' type='password')
el-button(v-else slot='append' @click='deassociate' variant='success') {{$t('settings.unassociate')}} el-button(slot='append' @click='change' type='success') {{$t('common.send')}}
el-input.mt-2(v-model='password' type='password')
span(slot='prepend') {{$t('settings.change_password')}}
el-button(slot='append' @click='change' type='success') {{$t('settings.change')}}
</template> </template>
<script> <script>
import { mapState, mapActions } from 'vuex' import { mapState, mapActions } from 'vuex'
export default { export default {
props: ['code'],
data () { data () {
return { return {
mastodon_instance: '',
password: '', password: '',
user: {}
} }
}, },
computed: mapState(['oauth', 'user']), // computed: mapState(['user']),
async asyncData ({ $axios, params }) { // async asyncData ({ $axios, params }) {
// const code = this.$route.query.code // const user = await $axios.$get('/auth/user')
// if (code) { // user.mastodon_auth = ''
// const res = await api.setCode({code}) // return { user }
// } // },
const user = await $axios.$get('/auth/user')
user.mastodon_auth = ''
return { user } //, mastodon_instance: user.mastodon_auth.instance }
// this.user = user
// this.mastodon_instance = user.mastodon_auth.instance
},
methods: { methods: {
async change () { async change () {
if (!this.password) return if (!this.password) return
const user = this.user const user = this.user
user.password = this.password user.password = this.password
try { try {
await api.updateUser(user) // this.$axios.
} catch (e) { // await api.updateUser(user)
console.log(e) } catch (e) {
} console.log(e)
}, }
async deassociate () { },
const user = this.user close (done) {
user.mastodon_auth = '' this.$router.back()
this.mastodon_instance = '' done()
await api.updateUser(user)
},
async associate () {
if (!this.mastodon_instance) return
const url = await this.$axios.$post('/user/getauthurl', {instance: this.mastodon_instance})
setTimeout( () => window.location.href=url, 100);
} }
} }
} }

View File

@@ -1,80 +0,0 @@
// import axios from 'axios'
// import { getters } from '@/store'
// const api = axios.create({
// baseURL: process.env.NODE_ENV === 'development' ? 'http://localhost:3000/api' : '/api',
// withCredentials: true,
// responseType: 'json',
// headers: {
// // 'Access-Control-Allow-Origin': '*',
// // 'Access-Control-Allow-Credentials': 'true',
// // 'Accept': 'application/json',
// 'Content-Type': 'application/json'
// }
// })
// export default function ({ $axios }) {
// function get(path) {
// return $axios.$get(path, { headers: { 'Authorization': 'Bearer ' + getters.token } })
// }
// function post(path, data) {
// return $axios.$post(path, data)
// }
// function post(path, data) {
// return api.post(path, data) // , { headers: { 'Authorization': getters.token } })
// .then(res => res.data)
// .catch((e) => {
// console.error(e)
// if (e.response.status === 403) {
// // store.commit('logout') // TOFIX
// return false
// }
// throw e.response && e.response.data &&
// e.response.data.errors && e.response.data.errors[0].message
// })
// }
// function put(path, data) {
// return api.put(path, data, { headers: { 'Authorization': getters.token } })
// .then(ret => ret.data)
// }
// function del(path) {
// return api.delete(path, { headers: { 'Authorization': getters.token } }).then(ret => ret.data)
// }
// return {
// login: (email, password) => post('/login', { email, password }),
// register: user => post('/user', user)
// // password recovery
// forgotPassword: email => post('/user/recover', { email }),
// checkRecoverCode: recover_code => post('/user/check_recover_code', { recover_code }),
// recoverPassword: (recover_code, password) => post('/user/recover_password', { recover_code, password }),
// getAllEvents: (month, year) => get(`/event/${year}/${month}`),
// getUnconfirmedEvents: () => get('/event/unconfirmed'),
// confirmEvent: id => get(`/event/confirm/${id}`),
// unconfirmEvent: id => get(`/event/unconfirm/${id}`),
// addNotification: notification => post('/event/notification', notification),
// delNotification: code => del(`/event/notification/${code}`),
// addEvent: event => post('/user/event', event),
// updateEvent: event => put('/user/event', event),
// updatePlace: place => put('/place', place),
// delEvent: eventId => del(`/user/event/${eventId}`),
// getEvent: eventId => get(`/event/${eventId}`),
// getMeta: () => get('/event/meta'),
// getUser: () => get('/user'),
// getUsers: () => get('/users'),
// updateTag: tag => put('/tag', tag),
// updateUser: user => put('/user', user),
// getAuthURL: mastodonInstance => post('/user/getauthurl', mastodonInstance),
// setCode: code => post('/user/code', code),
// getAdminSettings: () => get('/settings')
// // setAdminSetting: (key, value) => post('/settings', { key, value })
// }
// }

View File

@@ -1,6 +0,0 @@
import Vue from 'vue'
import BootstrapVue from 'bootstrap-vue'
export default () => {
Vue.use(BootstrapVue)
}

View File

@@ -1,8 +1,8 @@
import Vue from 'vue' import Vue from 'vue'
import { Button, Select, Tag, Option, Table, FormItem, Card, import { Button, Select, Tag, Option, Table, FormItem, Card, Row, Col, Upload, Checkbox,
Form, Tabs, TabPane, Switch, Input, Loading, TimeSelect, Form, Tabs, TabPane, Switch, Input, Loading, TimeSelect, Badge, ButtonGroup, Divider,
TableColumn, ColorPicker, Pagination, Popover, Tooltip, TableColumn, ColorPicker, Pagination, Popover, Tooltip, Dialog, Calendar, Carousel, CarouselItem,
Container, Footer , Timeline, TimelineItem} from 'element-ui' Container, Footer , Timeline, TimelineItem, Menu, MenuItem } from 'element-ui'
import localeEn from 'element-ui/lib/locale/lang/en' import localeEn from 'element-ui/lib/locale/lang/en'
import localeIt from 'element-ui/lib/locale/lang/it' import localeIt from 'element-ui/lib/locale/lang/it'
import locale from 'element-ui/lib/locale' import locale from 'element-ui/lib/locale'
@@ -10,6 +10,19 @@ locale.use(localeIt)
export default () => { export default () => {
Vue.use(Button) Vue.use(Button)
Vue.use(Divider)
Vue.use(Checkbox)
Vue.use(Upload)
Vue.use(ButtonGroup)
Vue.use(Calendar)
Vue.use(Row)
Vue.use(Col)
Vue.use(Carousel)
Vue.use(CarouselItem)
Vue.use(Badge)
Vue.use(Dialog)
Vue.use(Menu)
Vue.use(MenuItem)
Vue.use(Container) Vue.use(Container)
Vue.use(Timeline) Vue.use(Timeline)
Vue.use(TimelineItem) Vue.use(TimelineItem)

View File

@@ -3,6 +3,21 @@ import moment from 'dayjs'
import 'dayjs/locale/it' import 'dayjs/locale/it'
moment.locale('it') moment.locale('it')
Vue.filter('datetime', value => moment(value).format('ddd, D MMMM HH:mm')) export default (a) => {
Vue.filter('short_datetime', value => moment(value).format('D/MM HH:mm'))
Vue.filter('hour', value => moment(value).format('HH:mm')) Vue.filter('datetime', value => moment(value).format('ddd, D MMMM HH:mm'))
Vue.filter('short_datetime', value => moment(value).format('D/MM HH:mm'))
Vue.filter('hour', value => moment(value).format('HH:mm'))
Vue.filter('day', value => moment(value).format('ddd, D MMM'))
Vue.filter('month', value => moment(value).format('MMM'))
Vue.filter('event_when', event => {
if (event.multidate) {
return moment(event.start_datetime).format('dddd, D MMMM HH:mm') + ' - ' + moment(event.end_datetime).format('ddd, D MMMM')
} else {
if (event.end_datetime && event.end_datetime !== event.start_datetime)
return moment(event.start_datetime).format('dddd, D MMMM HH:mm') + '-' + moment(event.end_datetime).format('HH:mm')
else
return moment(event.start_datetime).format('dddd, D MMMM HH:mm')
}
})
}

View File

@@ -1,5 +1,6 @@
import Vue from 'vue' import Vue from 'vue'
import VueI18n from 'vue-i18n' import VueI18n from 'vue-i18n'
import it from '@/locales/it.js'
Vue.use(VueI18n) Vue.use(VueI18n)
@@ -10,7 +11,7 @@ export default ({ app, store }) => {
locale: store.state.locale, locale: store.state.locale,
fallbackLocale: 'it', fallbackLocale: 'it',
messages: { messages: {
'it': require('~/locales/it.json') it
// 'fr': require('~/locales/fr.json') // 'fr': require('~/locales/fr.json')
} }
}) })

View File

@@ -1,6 +0,0 @@
import Vue from 'vue'
import MagicGrid from 'vue-magic-grid'
export default () => {
Vue.use(MagicGrid)
}

View File

@@ -1,6 +1,5 @@
import Vue from 'vue' import Vue from 'vue'
import VCalendar from 'v-calendar' import VCalendar from 'v-calendar'
// import 'v-calendar/lib/v-calendar.min.css'
export default () => { export default () => {
Vue.use(VCalendar, { Vue.use(VCalendar, {

View File

@@ -17,6 +17,14 @@ import 'vue-awesome/icons/edit'
import 'vue-awesome/icons/envelope-open-text' import 'vue-awesome/icons/envelope-open-text'
import 'vue-awesome/icons/user-secret' import 'vue-awesome/icons/user-secret'
import 'vue-awesome/icons/question-circle' import 'vue-awesome/icons/question-circle'
import 'vue-awesome/icons/share'
import 'vue-awesome/icons/comment'
import 'vue-awesome/icons/comments'
import 'vue-awesome/icons/tags'
import 'vue-awesome/icons/chevron-right'
import 'vue-awesome/icons/chevron-left'
import 'vue-awesome/icons/search'
import Icon from 'vue-awesome/components/Icon' import Icon from 'vue-awesome/components/Icon'
export default () => { export default () => {

View File

@@ -4,7 +4,7 @@ const User = require('./models/user')
const Auth = { const Auth = {
async fillUser(req, res, next) { async fillUser(req, res, next) {
if (!req.user) return next(new Error('ERROR! No user')) if (!req.user) return next()
req.user = await User.findOne({ req.user = await User.findOne({
where: { id: { [Op.eq]: req.user.id }, is_active: true } where: { id: { [Op.eq]: req.user.id }, is_active: true }
}) })

View File

@@ -1,5 +1,5 @@
const { User, Event, Comment, Tag } = require('../model') const { User, Event, Comment, Tag } = require('../model')
const config = require('../../../config') const { SHARED_CONF } = require('../../../config')
const Mastodon = require('mastodon-api') const Mastodon = require('mastodon-api')
// const Sequelize = require('sequelize') // const Sequelize = require('sequelize')
// const Op = Sequelize.Op // const Op = Sequelize.Op
@@ -13,7 +13,7 @@ const botController = {
bot: null, bot: null,
async initialize () { async initialize () {
const settings = await settingsController.settings() const settings = await settingsController.settings()
if (!settings.mastodon_auth) return if (!settings.mastodon_auth || !settings.mastodon_auth.access_token) return
const mastodon_auth = settings.mastodon_auth const mastodon_auth = settings.mastodon_auth
botController.bot = new Mastodon({ botController.bot = new Mastodon({
access_token: mastodon_auth.access_token, access_token: mastodon_auth.access_token,
@@ -46,7 +46,7 @@ const botController = {
const { access_token, instance } = mastodon_auth const { access_token, instance } = mastodon_auth
const bot = new Mastodon({ access_token, api_url: `https://${instance}/api/v1/` }) const bot = new Mastodon({ access_token, api_url: `https://${instance}/api/v1/` })
const status = `${event.title} @ ${event.place.name} ${moment(event.start_datetime).format('ddd, D MMMM HH:mm')} - const status = `${event.title} @ ${event.place.name} ${moment(event.start_datetime).format('ddd, D MMMM HH:mm')} -
${event.description.length > 200 ? event.description.substr(0, 200) + '...' : event.description} - ${event.tags.map(t => '#' + t.tag).join(' ')} ${config.baseurl}/event/${event.id}` ${event.description.length > 200 ? event.description.substr(0, 200) + '...' : event.description} - ${event.tags.map(t => '#' + t.tag).join(' ')} ${SHARED_CONF.baseurl}/event/${event.id}`
let media let media
if (event.image_path) { if (event.image_path) {

View File

@@ -3,6 +3,7 @@ const moment = require('moment')
const { Op } = require('sequelize') const { Op } = require('sequelize')
const lodash = require('lodash') const lodash = require('lodash')
const { User, Event, Comment, Tag, Place, Notification } = require('../model') const { User, Event, Comment, Tag, Place, Notification } = require('../model')
const Sequelize = require('sequelize')
const eventController = { const eventController = {
@@ -19,8 +20,26 @@ const eventController = {
}, },
async getMeta(req, res) { async getMeta(req, res) {
const places = await Place.findAll() const places = await Place.findAll({
const tags = await Tag.findAll() group: ['place.id'],
order: [[Sequelize.fn("COUNT", Sequelize.col('events.id')), 'DESC']],
attributes: {
include: [[Sequelize.fn("COUNT", Sequelize.col('events.id')), 'eventsCount']],
exclude: ['createdAt', 'updatedAt']
},
include: { model: Event, attributes: [] }
})
const tags = await Tag.findAll({
group: ['tag'],
order: [[Sequelize.fn("COUNT", Sequelize.col('events.id')), 'DESC']],
includeIgnoreAttributes:false,
attributes: {
include: [[Sequelize.fn("COUNT", Sequelize.col('events.id')), 'eventsCount']],
exclude: ['createdAt', 'updatedAt']
},
include: { model: Event, attributes: [] }})
res.json({ tags, places }) res.json({ tags, places })
}, },
@@ -67,7 +86,14 @@ const eventController = {
async get(req, res) { async get(req, res) {
const id = req.params.event_id const id = req.params.event_id
const event = await Event.findByPk(id, { include: [User, Tag, Comment, Place] }) const event = await Event.findByPk(id, { include:
[
Tag,
Comment,
{ model: Place, attributes: ['name', 'address'] }
] ,
order: [ [Comment, 'id', 'DESC'] ]
})
res.json(event) res.json(event)
}, },

View File

@@ -1,4 +1,6 @@
const { Settings } = require('../model') const { Settings } = require('../model')
const { SHARED_CONF } = require('../../../config')
const Mastodon = require('mastodon-api')
const settingsController = { const settingsController = {
async setAdminSetting (key, value) { async setAdminSetting (key, value) {
@@ -14,6 +16,42 @@ const settingsController = {
res.json(settings) res.json(settings)
}, },
async getAuthURL(req, res) {
const instance = req.body.instance
const callback = `${SHARED_CONF.baseurl}/api/settings/oauth`
const { client_id, client_secret } = await Mastodon.createOAuthApp(`https://${instance}/api/v1/apps`,
SHARED_CONF.title, 'read write', callback)
const url = await Mastodon.getAuthorizationUrl(client_id, client_secret,
`https://${instance}`, 'read write', callback)
await settingsController.setAdminSetting('mastodon_auth', { client_id, client_secret, instance })
res.json(url)
},
async code(req, res) {
const code = req.query.code
let client_id, client_secret, instance
const callback = `${SHARED_CONF.baseurl}/api/settings/oauth`
console.error('sono dentro CODEEEEEEEEEE', code)
const settings = await settingsController.settings()
console.log(settings);
({ client_id, client_secret, instance } = settings.mastodon_auth)
try {
const token = await Mastodon.getAccessToken(client_id, client_secret, code,
`https://${instance}`, callback)
const mastodon_auth = { client_id, client_secret, access_token: token, instance }
console.error(mastodon_auth)
await settingsController.setAdminSetting('mastodon_auth', mastodon_auth)
res.redirect('/admin')
} catch (e) {
res.json(e)
}
},
async settings () { async settings () {
const settings = await Settings.findAll() const settings = await Settings.findAll()
const map = {} const map = {}

View File

@@ -2,14 +2,12 @@ const fs = require('fs')
const path = require('path') const path = require('path')
const crypto = require('crypto') const crypto = require('crypto')
const jwt = require('jsonwebtoken') const jwt = require('jsonwebtoken')
const Mastodon = require('mastodon-api')
const { Op } = require('sequelize') const { Op } = require('sequelize')
const jsonwebtoken = require('jsonwebtoken') const jsonwebtoken = require('jsonwebtoken')
const User = require('../models/user') const User = require('../models/user')
const config = require('../../../config') const { SECRET_CONF, SHARED_CONF } = require('../../../config')
const mail = require('../mail') const mail = require('../mail')
const { Event, Tag, Place } = require('../models/event') const { Event, Tag, Place } = require('../models/event')
const settingsController = require('./settings')
const eventController = require('./event') const eventController = require('./event')
const userController = { const userController = {
@@ -17,13 +15,13 @@ const userController = {
// find the user // find the user
const user = await User.findOne({ where: { email: { [Op.eq]: req.body && req.body.email } } }) const user = await User.findOne({ where: { email: { [Op.eq]: req.body && req.body.email } } })
if (!user) { if (!user) {
res.status(404).json({ success: false, message: 'AUTH_FAIL' }) res.status(403).json({ success: false, message: 'auth.fail' })
} else if (user) { } else if (user) {
if (!user.is_active) { if (!user.is_active) {
res.status(403).json({ success: false, message: 'NOT_CONFIRMED' }) res.status(403).json({ success: false, message: 'auth.not_confirmed' })
// check if password matches // check if password matches
} else if (!await user.comparePassword(req.body.password)) { } else if (!await user.comparePassword(req.body.password)) {
res.status(403).json({ success: false, message: 'AUTH_FAIL' }) res.status(403).json({ success: false, message: 'auth.fail' })
} else { } else {
// if user is found and password is right // if user is found and password is right
// create a token // create a token
@@ -33,7 +31,7 @@ const userController = {
email: user.email, email: user.email,
scope: [user.is_admin ? 'admin' : 'user'] scope: [user.is_admin ? 'admin' : 'user']
}, },
config.secret SECRET_CONF.secret
) )
res.json({token: accessToken}) res.json({token: accessToken})
@@ -58,8 +56,12 @@ const userController = {
if (event.image_path) { if (event.image_path) {
const old_path = path.resolve(__dirname, '..', '..', 'uploads', event.image_path) const old_path = path.resolve(__dirname, '..', '..', 'uploads', event.image_path)
const old_thumb_path = path.resolve(__dirname, '..', '..', 'uploads', 'thumb', event.image_path) const old_thumb_path = path.resolve(__dirname, '..', '..', 'uploads', 'thumb', event.image_path)
await fs.unlink(old_path) try {
await fs.unlink(old_thumb_path) await fs.unlink(old_path)
await fs.unlink(old_thumb_path)
} catch (e) {
console.error(e)
}
} }
await event.destroy() await event.destroy()
res.sendStatus(200) res.sendStatus(200)
@@ -160,61 +162,14 @@ const userController = {
return res.json(newEvent) return res.json(newEvent)
}, },
async getAuthURL(req, res) {
const instance = req.body.instance
const is_admin = req.body.admin && req.user.is_admin
const callback = `${config.baseurl}/${is_admin ? 'admin/oauth' : 'settings'}`
const { client_id, client_secret } = await Mastodon.createOAuthApp(`https://${instance}/api/v1/apps`,
config.title, 'read write', callback)
const url = await Mastodon.getAuthorizationUrl(client_id, client_secret,
`https://${instance}`, 'read write', callback)
if (is_admin) {
await settingsController.setAdminSetting('mastodon_auth', { client_id, client_secret, instance })
} else {
req.user.mastodon_auth = { client_id, client_secret, instance }
await req.user.save()
}
res.json(url)
},
async code(req, res) {
const { code, is_admin } = req.body
let client_id, client_secret, instance
const callback = `${config.baseurl}/${is_admin ? 'admin/oauth' : 'settings'}`
if (is_admin) {
const settings = await settingsController.settings();
({ client_id, client_secret, instance } = settings.mastodon_auth)
} else {
({ client_id, client_secret, instance } = req.user.mastodon_auth)
}
try {
const token = await Mastodon.getAccessToken(client_id, client_secret, code,
`https://${instance}`, callback)
const mastodon_auth = { client_id, client_secret, access_token: token, instance }
if (is_admin) {
await settingsController.setAdminSetting('mastodon_auth', mastodon_auth)
res.json(instance)
} else {
req.user.mastodon_auth = mastodon_auth
await req.user.save()
// await bot.add(req.user, token)
res.json(req.user)
}
} catch (e) {
res.json(e)
}
},
async forgotPassword(req, res) { async forgotPassword(req, res) {
const email = req.body.email const email = req.body.email
const user = await User.findOne({ where: { email: { [Op.eq]: email } } }) const user = await User.findOne({ where: { email: { [Op.eq]: email } } })
if (!user) return res.sendStatus(200) if (!user) return res.sendStatus(200)
user.recover_code = crypto.randomBytes(16).toString('hex') user.recover_code = crypto.randomBytes(16).toString('hex')
mail.send(user.email, 'recover', { user, config }) mail.send(user.email, 'recover', { user, config: SHARED_CONF })
await user.save() await user.save()
res.sendStatus(200) res.sendStatus(200)
}, },
@@ -229,13 +184,17 @@ const userController = {
async updatePasswordWithRecoverCode(req, res) { async updatePasswordWithRecoverCode(req, res) {
const recover_code = req.body.recover_code const recover_code = req.body.recover_code
if (!recover_code) return res.sendStatus(400)
const password = req.body.password const password = req.body.password
if (!recover_code || !password) return res.sendStatus(400)
const user = await User.findOne({ where: { recover_code: { [Op.eq]: recover_code } } }) const user = await User.findOne({ where: { recover_code: { [Op.eq]: recover_code } } })
if (!user) return res.sendStatus(400) if (!user) return res.sendStatus(400)
user.password = password user.password = password
await user.save() try {
res.sendStatus(200) await user.save()
res.sendStatus(200)
} catch(e) {
res.sendStatus(400)
}
}, },
async current(req, res) { async current(req, res) {
@@ -253,7 +212,7 @@ const userController = {
const user = await User.findByPk(req.body.id) const user = await User.findByPk(req.body.id)
if (user) { if (user) {
if (!user.is_active && req.body.is_active) { if (!user.is_active && req.body.is_active) {
await mail.send(user.email, 'confirm', { user, config }) await mail.send(user.email, 'confirm', { user, config: SHARED_CONF })
} }
await user.update(req.body) await user.update(req.body)
res.json(user) res.json(user)
@@ -263,25 +222,29 @@ const userController = {
}, },
async register(req, res) { async register(req, res) {
console.error('register !!', req)
const n_users = await User.count() const n_users = await User.count()
try { try {
// the first registered user will be an active admin
if (n_users === 0) { if (n_users === 0) {
// the first registered user will be an active admin
req.body.is_active = req.body.is_admin = true req.body.is_active = req.body.is_admin = true
} else { } else {
req.body.is_active = false req.body.is_active = false
} }
const user = await User.create(req.body) const user = await User.create(req.body)
try { try {
mail.send([user.email, config.admin], 'register', { user, config }) mail.send([user.email, SECRET_CONF.admin], 'register', { user, config: SHARED_CONF })
} catch (e) { } catch (e) {
console.error(e)
return res.status(400).json(e) return res.status(400).json(e)
} }
const payload = { email: user.email } const payload = { email: user.email }
const token = jwt.sign(payload, config.secret) const token = jwt.sign(payload, SECRET_CONF.secret)
res.json({ user, token }) res.json({ user, token })
} catch (e) { } catch (e) {
console.error(e)
res.status(404).json(e) res.status(404).json(e)
} }
} }

View File

@@ -1,5 +1,6 @@
const Sequelize = require('sequelize') const Sequelize = require('sequelize')
const conf = require('../../config.js') const { SECRET_CONF } = require('../../config.js')
const db = new Sequelize(conf.db)
db.sync() const db = new Sequelize(SECRET_CONF.db)
// db.sync()
module.exports = db module.exports = db

View File

@@ -5,10 +5,23 @@ 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 settingsController = require('./controller/settings') const settingsController = require('./controller/settings')
const config = require('../../config') const { SECRET_CONF } = require('../../config')
const cookieParser = require('cookie-parser')
const botController = require('./controller/bot') const expressJwt = require('express-jwt')
const jwt = require('express-jwt')({secret: config.secret}) const jwt = expressJwt({
secret: SECRET_CONF.secret,
credentialsRequired: false,
getToken: req => {
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
return req.headers.authorization.split(' ')[1];
} else if (req.cookies && req.cookies['auth._token.local']) {
const tmp = req.cookies['auth._token.local'].split(' ');
return tmp[1]
}
return null
}
})
const storage = require('./storage')({ const storage = require('./storage')({
destination: 'uploads/' destination: 'uploads/'
@@ -16,7 +29,7 @@ const storage = require('./storage')({
const upload = multer({ storage }) const upload = multer({ storage })
const api = express.Router() const api = express.Router()
api.use(cookieParser())
// AUTH // AUTH
api.post('/auth/login', userController.login) api.post('/auth/login', userController.login)
api.post('/auth/logout', userController.logout) api.post('/auth/logout', userController.logout)
@@ -81,7 +94,7 @@ api.get('/export/:type', exportController.export)
api.get('/event/:month/:year', eventController.getAll) api.get('/event/:month/:year', eventController.getAll)
// mastodon oauth auth // mastodon oauth auth
api.post('/user/getauthurl', jwt, isAuth, userController.getAuthURL) api.post('/settings/getauthurl', jwt, isAuth, isAdmin, settingsController.getAuthURL)
api.post('/user/code', jwt, isAuth, userController.code) api.get('/settings/oauth', jwt, isAuth, isAdmin, settingsController.code)
module.exports = api module.exports = api

View File

@@ -1,40 +1,40 @@
const Email = require('email-templates') const Email = require('email-templates')
const path = require('path') const path = require('path')
const config = require('../../config') const { SECRET_CONF, SHARED_CONF } = require('../../config')
const moment = require('moment') const moment = require('moment')
moment.locale(config.locale) moment.locale(SHARED_CONF.locale)
const mail = { const mail = {
send (addresses, template, locals) { send (addresses, template, locals) {
const email = new Email({ const email = new Email({
views: { root: path.join(__dirname, 'emails') }, 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: {
from: `${config.title} <${config.smtp.auth.user}>` from: `${SHARED_CONF.title} <${SECRET_CONF.smtp.auth.user}>`
}, },
send: true, send: true,
i18n: { i18n: {
locales: ['en', 'es', 'it'], directory: path.join(__dirname, '..', '..', 'locales', 'email'),
defaultLocale: config.locale defaultLocale: SHARED_CONF.locale
}, },
transport: config.smtp transport: SECRET_CONF.smtp
}) })
return email.send({ return email.send({
template, template,
message: { message: {
to: addresses, to: addresses,
bcc: config.admin bcc: SECRET_CONF.admin
}, },
locals: { locals: {
...locals, ...locals,
locale: config.locale, locale: SHARED_CONF.locale,
config, config: SHARED_CONF,
datetime: datetime => moment(datetime).format('ddd, D MMMM HH:mm') datetime: datetime => moment(datetime).format('ddd, D MMMM HH:mm')
} }
}) })

View File

@@ -10,19 +10,23 @@ const Event = db.define('event', {
end_datetime: { type: Sequelize.DATE, index: true }, end_datetime: { type: Sequelize.DATE, index: true },
image_path: Sequelize.STRING, image_path: Sequelize.STRING,
is_visible: Sequelize.BOOLEAN, is_visible: Sequelize.BOOLEAN,
activitypub_id: { type: Sequelize.STRING, index: true }, activitypub_id: { type: Sequelize.BIGINT, index: true },
// activitypub_ids: { type: Sequelize.ARRAY, index} activitypub_ids: {
type: Sequelize.ARRAY(Sequelize.BIGINT),
index: true,
defaultValue: []
}
}) })
const Tag = db.define('tag', { const Tag = db.define('tag', {
tag: { type: Sequelize.STRING, index: true, unique: true, primaryKey: true }, tag: { type: Sequelize.STRING, index: true, unique: true, },
color: { type: Sequelize.STRING } color: { type: Sequelize.STRING }
}) })
const Comment = db.define('comment', { const Comment = db.define('comment', {
activitypub_id: { type: Sequelize.STRING, index: true }, activitypub_id: { type: Sequelize.BIGINT, index: true },
data: Sequelize.JSON, data: Sequelize.JSON,
url: Sequelize.STRING, // url: Sequelize.STRING,
author: Sequelize.STRING, author: Sequelize.STRING,
text: Sequelize.STRING text: Sequelize.STRING
}) })

View File

@@ -28,8 +28,8 @@ DiskStorage.prototype._handleFile = function _handleFile(req, file, cb) {
const thumbPath = path.join(destination, 'thumb', filename) const thumbPath = path.join(destination, 'thumb', filename)
const outStream = fs.createWriteStream(finalPath) const outStream = fs.createWriteStream(finalPath)
const thumbStream = fs.createWriteStream(thumbPath) const thumbStream = fs.createWriteStream(thumbPath)
const resizer = sharp().resize(800).jpeg({ quality: 80 }) const resizer = sharp().resize(800).jpeg({ quality: 90 })
const thumbnailer = sharp().resize(400).jpeg({ quality: 60 }) const thumbnailer = sharp().resize(400).jpeg({ quality: 90 })
file.stream.pipe(thumbnailer).pipe(thumbStream) file.stream.pipe(thumbnailer).pipe(thumbStream)
thumbStream.on('error', e => console.log('thumbStream error ', e)) thumbStream.on('error', e => console.log('thumbStream error ', e))

View File

@@ -1,7 +1,7 @@
// const mail = require('./mail') // const mail = require('./mail')
const bot = require('./api/controller/bot') const bot = require('./api/controller/bot')
const settingsController = require('./api/controller/settings') const settingsController = require('./api/controller/settings')
const config = require('./api/config.js') // const config = require('./api/config.js')
const { Event, Notification, EventNotification, const { Event, Notification, EventNotification,
User, Place, Tag } = require('./api/model') User, Place, Tag } = require('./api/model')
@@ -25,15 +25,6 @@ async function sendNotification (notification, event, eventNotification) {
}) })
promises.push(b) promises.push(b)
} }
// user publish
if (event.user && event.user.mastodon_auth && event.user.mastodon_auth.access_token) {
const b = bot.post(event.user.mastodon_auth, event).then(ret => {
event.activitypub_id = ret.id
return event.save()
})
promises.push(b)
}
break
} }
return Promise.all(promises) return Promise.all(promises)
} }

View File

@@ -1,6 +1,7 @@
import moment from 'dayjs' import moment from 'dayjs'
import { intersection } from 'lodash' import intersection from 'lodash/intersection'
import Vue from 'vue' import map from 'lodash/map'
export const state = () => ({ export const state = () => ({
events: [], events: [],
@@ -13,51 +14,61 @@ export const state = () => ({
filters: { filters: {
tags: [], tags: [],
places: [] places: []
} },
show_past_events: false,
}) })
export const getters = { export const getters = {
token: state => state.token, token: state => state.token,
// filter current + future events only // filter current + future events only
// plus, filter matches search tag/place // plus, filter matches search tag/place
filteredEvents: (state) => { filteredEvents: (state) => {
const events = state.events.map((e) => {
const end_datetime = e.end_datetime || moment(e.start_datetime).add('3', 'hour') let events = state.events
const past = (moment().diff(end_datetime, 'minutes') > 0)
e.past = past // TOFIX: use lodash
if (state.filters.tags.length || state.filters.places.length){
events = events.filter((e) => {
if (state.filters.tags.length) {
const m = intersection(e.tags.map(t => t.tag), state.filters.tags)
if (m.length > 0) return true
}
if (state.filters.places.length) {
if (state.filters.places.find(p => p === e.place.id)) {
return true
}
}
return 0
})
}
if (!state.show_past_events) {
events = events.filter( e => !e.past )
}
let lastDay = null
events = map(events, e => {
const currentDay = moment(e.start_datetime).date()
console.log(currentDay)
e.newDay = (!lastDay || lastDay!==currentDay) && currentDay
lastDay = currentDay
return e return e
}) })
if (!state.filters.tags.length && !state.filters.places.length) {
return events return events
}
return events.filter((e) => {
if (state.filters.tags.length) {
const m = intersection(e.tags.map(t => t.tag), state.filters.tags)
if (m.length > 0) return true
}
if (state.filters.places.length) {
if (state.filters.places.find(p => p === e.place.name)) {
return true
}
}
return 0
})
} }
} }
export const mutations = { export const mutations = {
logout(state) {
state.logged = false
state.token = ''
state.user = {}
},
login(state, user) {
state.logged = true
state.user = user.user
state.token = user.token
},
setEvents(state, events) { setEvents(state, events) {
state.events = events // set a `past` flag
state.events = events.map((e) => {
const end_datetime = e.end_datetime || moment(e.start_datetime).add('3', 'hour')
const past = (moment().diff(end_datetime, 'minutes') > 0)
e.past = !!past
return e
})
}, },
addEvent(state, event) { addEvent(state, event) {
state.events.push(event) state.events.push(event)
@@ -69,7 +80,9 @@ export const mutations = {
}) })
}, },
delEvent(state, eventId) { delEvent(state, eventId) {
state.events = state.events.filter(ev => ev.id !== eventId) state.events = state.events.filter(ev => {
return ev.id !== eventId
})
}, },
update(state, { tags, places }) { update(state, { tags, places }) {
state.tags = tags state.tags = tags
@@ -93,21 +106,13 @@ export const mutations = {
}, },
setSearchPlaces(state, places) { setSearchPlaces(state, places) {
state.filters.places = places state.filters.places = places
},
showPastEvents (state, show) {
state.show_past_events = show
} }
} }
export const actions = { export const actions = {
// called on server request
// get current month's event
async nuxtServerInit({ commit }, { req }) {
// set user if logged! TODO
const now = new Date()
// const events = await api.getAllEvents(now.getMonth() - 1, now.getFullYear())
const events = await this.$axios.$get(`/event/${now.getMonth()}/${now.getFullYear()}`)
commit('setEvents', events)
const { tags, places } = await this.$axios.$get('/event/meta')
commit('update', { tags, places })
},
async updateEvents({ commit }, page) { async updateEvents({ commit }, page) {
const events = await this.$axios.$get(`/event/${page.month-1}/${page.year}`) const events = await this.$axios.$get(`/event/${page.month-1}/${page.year}`)
commit('setEvents', events) commit('setEvents', events)
@@ -139,8 +144,8 @@ export const actions = {
}, },
setSearchPlaces({ commit }, places) { setSearchPlaces({ commit }, places) {
commit('setSearchPlaces', places) commit('setSearchPlaces', places)
},
showPastEvents({ commit }, show) {
commit('showPastEvents', show)
} }
} }
// export const getters = {
// filteredEvents: state => state.events
// }