mille storie

commenti da mastodon, widget con custom widget test...
This commit is contained in:
lesion 2019-04-29 00:27:29 +02:00
parent 3b80dd5f73
commit ac5ef6e324
34 changed files with 573 additions and 275 deletions

View file

@ -1,6 +1,39 @@
{ {
"done": [], "done": [
"in-progress": [], {
"assignedTo": {
"name": "lesion"
},
"category": "feature",
"creation_time": "2019-04-23T19:50:00.973Z",
"description": {
"content": "- export page ok\n- usare un'altra api per retrieve di eventi (perche' devo mostrarli tutti, non solo quelli del mese corrente)\n- non devo fare il load degli eventi nel nuxtServerInit (o dentro il layout normale oppure nelle pagine, tipo nella home)",
"mime": "text/markdown"
},
"details": {
"content": "- export page ok\n- usare un'altra api per retrieve di eventi (perche' devo mostrarli tutti, non solo quelli del mese corrente)\n- non devo fare il load degli eventi nel nuxtServerInit (o dentro il layout normale oppure nelle pagine, tipo nella home)\n",
"mime": "text/markdown"
},
"id": "7",
"prio": 1,
"references": [],
"title": "export page",
"type": "bug"
}
],
"in-progress": [
{
"assignedTo": {
"name": "lesion"
},
"category": "feature",
"creation_time": "2019-04-23T19:46:46.332Z",
"id": "3",
"prio": 0,
"references": [],
"title": "export lista"
}
],
"testing": [ "testing": [
{ {
"assignedTo": { "assignedTo": {
@ -15,18 +48,6 @@
} }
], ],
"todo": [ "todo": [
{
"assignedTo": {
"name": "lesion"
},
"category": "feature",
"creation_time": "2019-04-23T19:50:00.973Z",
"id": "7",
"prio": 1,
"references": [],
"title": "export page",
"type": "bug"
},
{ {
"assignedTo": { "assignedTo": {
"name": "lesion" "name": "lesion"
@ -99,21 +120,19 @@
"name": "lesion" "name": "lesion"
}, },
"category": "feature", "category": "feature",
"creation_time": "2019-04-23T19:46:46.332Z", "creation_time": "2019-04-23T19:44:56.705Z",
"id": "3", "id": "1",
"prio": 0,
"references": [], "references": [],
"title": "export lista" "title": "popup sul calendario"
}, },
{ {
"assignedTo": { "assignedTo": {
"name": "lesion" "name": "lesion"
}, },
"category": "feature", "creation_time": "2019-04-27T19:44:33.769Z",
"creation_time": "2019-04-23T19:44:56.705Z", "id": "12",
"id": "1",
"references": [], "references": [],
"title": "popup sul calendario" "title": "rifare il calendario o solo il popup"
}, },
{ {
"assignedTo": { "assignedTo": {
@ -137,6 +156,15 @@
"references": [], "references": [],
"title": "documentare sorgenti", "title": "documentare sorgenti",
"type": "bug" "type": "bug"
},
{
"assignedTo": {
"name": "lesion"
},
"creation_time": "2019-04-28T09:25:50.701Z",
"id": "13",
"references": [],
"title": "test altra visualizzazione"
} }
] ]
} }

View file

@ -1,15 +1,24 @@
<template lang="pug"> <template lang="pug">
v-calendar#calendar.card( v-calendar#calendar.card(
title-position='left'
locale='it'
is-dark
show-caps show-caps
:attributes='attributes' :attributes='attributes'
:from-page.sync='page' :from-page.sync='page'
is-expanded is-inline) is-expanded is-inline)
//- div(slot='popover', slot-scope='{ customData }') div(slot='popover', slot-scope='{ customData, attributes }')
//- router-link(:to="`/event/${customData.id}`") {{customData.start_datetime|hour}} - {{customData.title}} @{{customData.place.name}} p {{attributes}}
//- router-link(:to="`/event/${customData.id}`") {{customData.start_datetime|hour}} - {{customData.title}}
//- 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 } from 'vuex'
// import filters from '@/filters'
import moment from 'dayjs' import moment from 'dayjs'
import { intersection } from 'lodash' import { intersection } from 'lodash'
@ -21,12 +30,11 @@ export default {
const year = moment().year() const year = moment().year()
return { return {
page: { month, year}, page: { month, year},
selectedEvent: {},
daysWithEvents: {}
} }
}, },
// async mounted () {
// await this.updateEvents(this.page)
// },
watch: { watch: {
page () { page () {
this.updateEvents(this.page) this.updateEvents(this.page)
@ -34,17 +42,28 @@ export default {
}, },
methods: { methods: {
...mapActions(['updateEvents']), ...mapActions(['updateEvents']),
nextEvent () {
},
eventToAttribute(event) { eventToAttribute(event) {
let e = { let e = {
key: event.id, key: event.id,
customData: event, customData: event,
order: event.start_datetime, order: event.start_datetime,
// popover: {
// slot: 'popover',
// visibility: 'hover'
// }
} }
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) {
@ -65,14 +84,14 @@ export default {
filteredEvents () { filteredEvents () {
return this.$store.getters.filteredEvents return this.$store.getters.filteredEvents
}, },
...mapState(['events', 'filters', 'user', 'logged']), ...mapState(['events', 'filters']),
attributes () { attributes () {
return [ return [
{ key: 'todaly', dates: new Date(), { key: 'today', dates: new Date(),
highlight: { highlight: {
backgroundColor: '#aaffaa' backgroundColor: '#aaffaa'
}, },
// popover: {label: this.$t('Today')} popover: {label: this.$t('common.today')}
}, },
...this.filteredEvents.map(this.eventToAttribute) ...this.filteredEvents.map(this.eventToAttribute)
] ]

View file

@ -5,9 +5,9 @@
:img-src='imgPath') :img-src='imgPath')
strong {{event.title}} strong {{event.title}}
div <v-icon name='clock'/> {{event.start_datetime|datetime}} div <v-icon name='clock'/> {{event.start_datetime|datetime}}
//- span <v-icon name='map-marker-alt'/> {{event.place.name}} span <v-icon name='map-marker-alt'/> {{event.place.name}}
br br
el-tag.mr-1(:color='tag.color || "grey"' v-for='tag in event.tags' :key='tag.tag' el-tag.mr-1(:color='tag.color' v-for='tag in event.tags' :key='tag.tag'
size='small' @click.stop='addSearchTag(tag)') {{tag.tag}} size='small' @click.stop='addSearchTag(tag)') {{tag.tag}}
</template> </template>
<script> <script>
@ -20,7 +20,7 @@ export default {
computed: { computed: {
...mapState(['user']), ...mapState(['user']),
imgPath() { imgPath() {
return this.event.image_path && '/uploads/thumb/' + this.event.image_path return this.event.image_path && '/media/thumb/' + this.event.image_path
}, },
mine() { mine() {
return this.event.userId === this.user.id return this.event.userId === this.user.id

View file

@ -1,18 +1,18 @@
<template lang="pug"> <template lang="pug">
div div(v-loading='loading')
magic-grid(:animate="false" useMin :gap=5 :maxCols=4 magic-grid(:animate="true" useMin :gap=5 :maxCols=4
:maxColWidth='400' ref='magicgrid') :maxColWidth='400' ref='magicgrid')
div.mt-1.item div.mt-1.item
//- Search#search //- Search#search
no-ssr no-ssr
Calendar Calendar
Event.item.mt-1(v-for='event in events' Event.item.mt-1(v-for='event in events'
:key='event.id' :key='event.id'
:event='event') :event='event')
</template> </template>
<script> <script>
import { mapState } from 'vuex' import { mapState, mapActions } from 'vuex'
import axios from 'axios' import axios from 'axios'
// import filters from '@/filters.js' // import filters from '@/filters.js'
import Event from '@/components/Event' import Event from '@/components/Event'
@ -23,10 +23,13 @@ import Calendar from '@/components/Calendar'
export default { export default {
name: 'Home', name: 'Home',
// async asyncData ({req}) { data () {
// console.log('dentro asyncData') return { loading: true }
// const { data } = await axios.get('http://localhost:3000/api/event/2019/2') },
// return { events: data } // created () {
// const now = new Date()
// const page = { month: now.getMonth() - 1, year: now.getFullYear() }
// this.updateEvents(page)
// }, // },
components: { Event, Calendar }, // , Calendar, Search }, components: { Event, Calendar }, // , Calendar, Search },
computed: { computed: {
@ -38,9 +41,14 @@ export default {
.sort((a, b) => a.start_datetime > b.start_datetime) .sort((a, b) => a.start_datetime > b.start_datetime)
} }
}, },
mounted () {
this.loading = false
},
methods: mapActions(['updateEvents']),
watch: { watch: {
filteredEvents() { filteredEvents() {
this.$nextTick(this.$refs.magicgrid.positionItems) this.$nextTick(this.$refs.magicgrid.positionItems)
this.loading = false
} }
} }
} }

34
components/List.vue Normal file
View file

@ -0,0 +1,34 @@
<template lang="pug">
div#gancio-widget
//- el-card.mb-1(no-body header='Eventi')
//- b-list-group#list(flush)
p minimal {{minimal}}
ul
li.flex-column.align-items-start(v-for="event in events" :key='event.id'
:to='`/event/${event.id}`' target='_parent')
img(v-if='event.image_path' slot="aside" :src="`http://localhost:3000/media/${event.image_path}`" alt="Meia Aside" style='max-height: 60px')
strong.mb-1 {{event.title}}
br
small.float-right {{event.place.name}}
//- 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}}
</template>
<script>
import axios from 'axios'
export default {
name: 'List',
data () {
return {
events: []
}
},
props: {
minimal: {
type: Boolean,
default: false
}
},
async mounted () {
this.events = (await axios.get('http://localhost:3000/api/export/json')).data
}
}
</script>

View file

@ -10,12 +10,13 @@
span.d-md-none {{$t('common.add_event')}} span.d-md-none {{$t('common.add_event')}}
b-nav-item(v-if='$auth.loggedIn' to='/settings' v-b-tooltip :title='$t("common.settings")') <v-icon color='orange' name='cog'/> b-nav-item(v-if='$auth.loggedIn' to='/settings' v-b-tooltip :title='$t("common.settings")') <v-icon color='orange' name='cog'/>
span.d-md-none {{$t('common.settings')}} span.d-md-none {{$t('common.settings')}}
b-nav-item(v-if='$auth.hasScope(`admin`)' to='/admin' v-b-tooltip :title='$t("common.admin")') <v-icon color='lightblue' name='tools'/> b-nav-item(v-if='$auth.user.is_admin' to='/admin' v-b-tooltip :title='$t("common.admin")') <v-icon color='lightblue' name='tools'/>
span.d-md-none {{$t('common.admin')}} span.d-md-none {{$t('common.admin')}}
b-nav-item(to='/export' v-b-tooltip :title='$t("common.export")') <v-icon name='file-export' color='yellow'/> 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')}} span.d-md-none {{$t('common.export')}}
b-nav-item(v-if='auth.loggedIn' @click='logout' v-b-tooltip :title='$t("common.logout")') <v-icon color='red' name='sign-out-alt'/> b-nav-item(v-if='$auth.loggedIn' @click='logout' v-b-tooltip :title='$t("common.logout")') <v-icon color='red' name='sign-out-alt'/>
span.d-md-none {{$t('common.logout')}} span.d-md-none {{$t('common.logout')}}
b-nav-item
b-navbar-nav.ml-auto b-navbar-nav.ml-auto
b-nav-item(to='/about') b-nav-item(to='/about')
span {{$t('common.info')}} <v-icon color='#ff9fc4' name='question-circle'/> span {{$t('common.info')}} <v-icon color='#ff9fc4' name='question-circle'/>
@ -26,7 +27,7 @@ import {mapState, mapActions} from 'vuex'
export default { export default {
name: 'Nav', name: 'Nav',
computed: { computed: {
...mapState(['filters', 'auth']), ...mapState(['filters']),
filters_tags: { filters_tags: {
set (value) { set (value) {
this.setSearchTags(value) this.setSearchTags(value)

3
layouts/iframe.vue Normal file
View file

@ -0,0 +1,3 @@
<template lang="pug">
nuxt
</template>

View file

@ -17,7 +17,25 @@
"next": "Avanti", "next": "Avanti",
"what": "Cosa", "what": "Cosa",
"address": "Indirizzo", "address": "Indirizzo",
"media": "Media" "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"
}, },
"login": { "login": {
@ -41,6 +59,14 @@
"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.", "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": "", "address_description": "",
"tag_description": "Puoi inserire un tag (es. concerto, corteo)" "tag_description": "Puoi inserire un tag (es. concerto, corteo)"
},
"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

@ -41,8 +41,8 @@ module.exports = {
plugins: ['@/plugins/element-ui', '@/plugins/filters', plugins: ['@/plugins/element-ui', '@/plugins/filters',
'@/plugins/i18n', '@/plugins/bootstrap-vue', '@/plugins/i18n', '@/plugins/bootstrap-vue',
'@/plugins/vue-awesome', '@/plugins/vue-awesome',
'@/plugins/v-calendar', { src: '@/plugins/v-calendar', ssr: false },
{ src: '@/plugins/vuex-persist', ssr: false }, { src: '@/plugins/vuex-persist.js', ssr: false },
'@/plugins/magic-grid'], '@/plugins/magic-grid'],
/* /*
@ -68,7 +68,7 @@ module.exports = {
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: { url: '/auth/logout', method: 'post' },
user: { url: '/auth/user', method: 'get', propertyName: 'user' } user: { url: '/auth/user', method: 'get', propertyName: false }
}, },
// tokenRequired: true, // tokenRequired: true,
// tokenType: 'bearer', // tokenType: 'bearer',

View file

@ -40,6 +40,7 @@
"sqlite3": "^4.0.6", "sqlite3": "^4.0.6",
"v-calendar": "^0.9.7", "v-calendar": "^0.9.7",
"vue-awesome": "^3.5.1", "vue-awesome": "^3.5.1",
"vue-custom-element": "^3.2.6",
"vue-i18n": "^8.10.0", "vue-i18n": "^8.10.0",
"vue-magic-grid": "^0.0.4", "vue-magic-grid": "^0.0.4",
"vuex-persist": "^2.0.0" "vuex-persist": "^2.0.0"
@ -61,6 +62,7 @@
"eslint-plugin-vue": "^5.2.2", "eslint-plugin-vue": "^5.2.2",
"nodemon": "^1.18.9", "nodemon": "^1.18.9",
"prettier": "^1.16.4", "prettier": "^1.16.4",
"pug-plain-loader": "^1.0.0" "pug-plain-loader": "^1.0.0",
"webpack-cli": "^3.3.1"
} }
} }

View file

@ -5,7 +5,7 @@
el-tabs.mb-2(v-model='activeTab' v-loading='sending') el-tabs.mb-2(v-model='activeTab' v-loading='sending')
//- NOT LOGGED EVENT //- NOT LOGGED EVENT
el-tab-pane(v-if='!logged') el-tab-pane(v-if='!$auth.loggedIn')
span(slot='label') {{$t('event.anon')}} <v-icon name='user-secret'/> span(slot='label') {{$t('event.anon')}} <v-icon name='user-secret'/>
p(v-html="$t('event.anon_description')") p(v-html="$t('event.anon_description')")
el-button.float-right(@click='next' :disabled='!couldProceed') {{$t('common.next')}} el-button.float-right(@click='next' :disabled='!couldProceed') {{$t('common.next')}}
@ -13,7 +13,14 @@
//- WHERE //- WHERE
el-tab-pane el-tab-pane
span(slot='label') {{$t('common.where')}} <v-icon name='map-marker-alt'/> span(slot='label') {{$t('common.where')}} <v-icon name='map-marker-alt'/>
div {{$t('common.where')}} div {{$t('common.where')}}
el-popover(
placement="top-start"
width="400"
trigger="hover")
v-icon(slot='reference' color='#ff9fc4' name='question-circle')
slot
p {{$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")}} div {{$t("common.address")}}
@ -119,7 +126,6 @@ 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,
logged: state => state.logged
}), }),
disableAddress () { disableAddress () {
console.log('dentro disable Address') console.log('dentro disable Address')
@ -128,7 +134,7 @@ export default {
return ret return ret
}, },
couldProceed () { couldProceed () {
const t = this.logged ? -1 : 0 const t = this.$auth.loggedIn ? -1 : 0
switch(Number(this.activeTab)) { switch(Number(this.activeTab)) {
case 0+t: case 0+t:
return true return true
@ -209,7 +215,7 @@ export default {
this.updateMeta() this.updateMeta()
this.sending = false this.sending = false
this.$refs.modal.hide() this.$refs.modal.hide()
Message({ type: 'success', message: this.logged ? 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.sending = false
console.error(e) console.error(e)

View file

@ -1,5 +1,5 @@
<template lang="pug"> <template lang="pug">
b-modal(hide-footer @hidden='$router.replace("/")' :title='$t("Admin")' b-modal(hide-footer @hidden='$router.replace("/")' :title='$t("common.admin")'
:visible='true' size='lg') :visible='true' size='lg')
el-tabs(tabPosition='left' v-model='tab') el-tabs(tabPosition='left' v-model='tab')
@ -7,55 +7,56 @@
el-tab-pane.pt-1 el-tab-pane.pt-1
template(slot='label') template(slot='label')
v-icon(name='users') v-icon(name='users')
span.ml-1 {{$t('Users')}} span.ml-1 {{$t('common.users')}}
el-table(:data='paginatedUsers' small) el-table(:data='paginatedUsers' small)
el-table-column(label='Email') el-table-column(label='Email')
template(slot-scope='data') template(slot-scope='data')
el-popover(trigger='hover' :content='data.row.description' width='400') el-popover(trigger='hover' :content='data.row.description' width='400')
span(slot='reference') {{data.row.email}} span(slot='reference') {{data.row.email}}
el-table-column(label='Azioni') el-table-column(:label="$t('common.actions')")
template(slot-scope='data') template(slot-scope='data')
el-button.mr-1(size='mini' el-button.mr-1(size='mini'
:type='data.row.is_active?"warning":"success"' :type='data.row.is_active?"warning":"success"'
@click='toggle(data.row)') {{data.row.is_active?$t('Deactivate'):$t('Activate')}} @click='toggle(data.row)') {{data.row.is_active?$t('common.deactivate'):$t('common.activate')}}
el-button(size='mini' el-button(size='mini'
:type='data.row.is_admin?"danger":"warning"' :type='data.row.is_admin?"danger":"warning"'
@click='toggleAdmin(data.row)') {{data.row.is_admin?$t('Remove Admin'):$t('Admin')}} @click='toggleAdmin(data.row)') {{data.row.is_admin?$t('common.remove_admin'):$t('common.admin')}}
el-pagination(:page-size='perPage' :currentPage.sync='userPage' :total='users.length') el-pagination(:page-size='perPage' :currentPage.sync='userPage' :total='users.length')
//- PLACES //- PLACES
el-tab-pane.pt-1 el-tab-pane.pt-1
template(slot='label') template(slot='label')
v-icon(name='map-marker-alt') v-icon(name='map-marker-alt')
span.ml-1 {{$t('Places')}} span.ml-1 {{$t('common.places')}}
p {{$t('admin_place_explanation')}} p {{$t('admin.place_description')}}
el-form.mb-2(:inline='true' label-width='120px') el-form.mb-2(:inline='true' label-width='120px')
el-form-item(:label="$t('Name')") el-form-item(:label="$t('common.name')")
el-input.mr-1(:placeholder='$t("Name")' v-model='place.name') el-input.mr-1(:placeholder='$t("common.name")' v-model='place.name')
el-form-item(:label="$t('Address')") el-form-item(:label="$t('common.address')")
el-input.mr-1(:placeholder='$t("Address")' v-model='place.address') el-input.mr-1(:placeholder='$t("common.address")' v-model='place.address')
el-button(variant='primary' @click='savePlace') {{$t('Save')}} el-button(variant='primary' @click='savePlace') {{$t('common.save')}}
b-table(selectable :items='places' :fields='placeFields' striped hover el-table(:data='paginatedPlaces' small)
small selectedVariant='success' primary-key='id' el-table-column(:label="$t('common.name')")
select-mode="single" @row-selected='placeSelected' template(slot-scope='data') {{data.row.name}}
:per-page='perPage' :current-page='placePage') el-table-column(:label="$t('common.address')")
template(slot-scope='data') {{data.row.address}}
el-pagination(:page-size='perPage' :currentPage.sync='placePage' :total='places.length') el-pagination(:page-size='perPage' :currentPage.sync='placePage' :total='places.length')
//- EVENTS //- EVENTS
el-tab-pane.pt-1 el-tab-pane.pt-1
template(slot='label') template(slot='label')
v-icon(name='calendar') v-icon(name='calendar')
span.ml-1 {{$t('Events')}} span.ml-1 {{$t('common.events')}}
p {{$t('event_confirm_explanation')}} p {{$t('admin.event_confirm_description')}}
el-table(:data='paginatedEvents' small primary-key='id' v-loading='loading') el-table(:data='paginatedEvents' small primary-key='id' v-loading='loading')
el-table-column(:label='$t("Name")') el-table-column(:label='$t("common.name")')
template(slot-scope='data') {{data.row.title}} template(slot-scope='data') {{data.row.title}}
el-table-column(:label='$t("Where")') el-table-column(:label='$t("common.where")')
template(slot-scope='data') {{data.row.place.name}} template(slot-scope='data') {{data.row.place.name}}
el-table-column(:label='$t("Confirm")') el-table-column(:label='$t("common.confirm")')
template(slot-scope='data') template(slot-scope='data')
el-button(type='primary' @click='confirm(data.row.id)' size='mini') {{$t('Confirm')}} el-button(type='primary' @click='confirm(data.row.id)' size='mini') {{$t('common.confirm')}}
el-button(type='success' @click='preview(data.row.id)' size='mini') {{$t('Preview')}} el-button(type='success' @click='preview(data.row.id)' size='mini') {{$t('common.preview')}}
el-pagination(:page-size='perPage' :currentPage.sync='eventPage' :total='events.length') el-pagination(:page-size='perPage' :currentPage.sync='eventPage' :total='events.length')
@ -63,29 +64,29 @@
el-tab-pane.pt-1 el-tab-pane.pt-1
template(slot='label') template(slot='label')
v-icon(name='tag') v-icon(name='tag')
span {{$t('Tags')}} span {{$t('common.tags')}}
p {{$t('admin_tag_explanation')}} p {{$t('admin.tag_description')}}
el-tag(v-if='tag.tag' :color='tag.color || "grey"' 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('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='Tag') el-table-column(:label="$t('common.tag')")
template(slot-scope='data') template(slot-scope='data')
el-tag(:color='data.row.color || "grey"' 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='tools')
span {{$t('Settings')}} span {{$t('common.settings')}}
el-form(inline) el-form(inline @submit.prevent.stop='associatemastodon_instance')
span {{$t('admin_mastodon_explanation')}} span {{$t('admin.mastodon_description')}}
el-input(v-model="mastodon_instance") el-input(v-model="mastodon_instance")
span(slot='prepend') {{$t('Mastodon instance')}} span(slot='prepend') {{$t('admin.mastodon_instance')}}
el-button(slot='append' @click='associate' variant='success' type='success') {{$t('Associate')}} el-button(slot='append' @click='associate' :disabled='!mastodon_instance.length') {{$t('common.associate')}}
</template> </template>
<script> <script>
@ -117,21 +118,28 @@ export default {
tab: "0", tab: "0",
} }
}, },
// async mounted () { async mounted () {
// const code = this.$route.query.code console.log('sono dentro mounted', this.$route)
// if (code) { const code = this.$route.query.code
// this.tab = "4"
// const instance = await api.setCode({code, is_admin: true}) if (code) {
// } this.tab = "4"
const instance = await this.$axios.$post('/user/code', {code, is_admin: true})
}
// // this.users = await api.getUsers() // // this.users = await api.getUsers()
// // this.events = await api.getUnconfirmedEvents() // // this.events = await api.getUnconfirmedEvents()
// // this.settings = await api.getAdminSettings() // // this.settings = await api.getAdminSettings()
// this.mastodon_instance = this.settings.mastodon_auth && this.settings.mastodon_auth.instance },
// },
async asyncData ({ $axios, params, store }) { async asyncData ({ $axios, params, store }) {
console.log(store.state) console.log(store.state)
const users = await $axios.$get('/users') try {
return { users } const users = await $axios.$get('/users')
const events = await $axios.$get('/event/unconfirmed')
const settings = await $axios.$get('/settings')
return { users, events, settings, mastodon_instance: settings.mastodon_auth && settings.mastodon_auth.instance}
} catch ( e ) {
console.error(e)
}
}, },
computed: { computed: {
...mapState(['tags', 'places']), ...mapState(['tags', 'places']),
@ -146,7 +154,11 @@ export default {
paginatedUsers () { paginatedUsers () {
return this.users.slice((this.userPage-1) * this.perPage, return this.users.slice((this.userPage-1) * this.perPage,
this.userPage * this.perPage) this.userPage * this.perPage)
} },
paginatedPlaces () {
return this.places.slice((this.placePage-1) * this.perPage,
this.placePage * this.perPage)
},
}, },
methods: { methods: {
placeSelected (items) { placeSelected (items) {
@ -160,7 +172,7 @@ export default {
this.place.id = item.id this.place.id = item.id
}, },
tagSelected (tag) { tagSelected (tag) {
this.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)
@ -174,20 +186,25 @@ export default {
const newuser = await api.updateUser(user) const newuser = await api.updateUser(user)
}, },
async updateColor () { async updateColor () {
const newTag = await api.updateTag(this.tag) // try {
// const newTag = await this.$axios.$put('/tag', this.tag)
// } catch (e) {
// console.log(e)
// }
}, },
preview (id) { preview (id) {
this.$router.push(`/event/${id}`) this.$router.push(`/event/${id}`)
}, },
async associate () { async associate () {
if (!this.mastodon_instance) return if (!this.mastodon_instance) return
const url = await api.getAuthURL({instance: this.mastodon_instance, admin: true})
const url = await this.$axios.$post('/user/getauthurl', {instance: this.mastodon_instance, admin: true})
setTimeout( () => window.location.href=url, 100); setTimeout( () => window.location.href=url, 100);
}, },
async confirm (id) { async confirm (id) {
try { try {
this.loading = true this.loading = true
await api.confirmEvent(id) await this.$axios.$get(`/event/confirm/${id}`)
this.loading = false this.loading = false
Message({ Message({
message: this.$t('event_confirmed'), message: this.$t('event_confirmed'),

22
pages/embed/list.vue Normal file
View file

@ -0,0 +1,22 @@
<template lang="pug">
div
p porcodio
</template>
<script>
import { mapState } from 'vuex'
// import List from '../../components/List'
import moment from 'dayjs'
export default {
name: 'diocane',
layout: 'iframe',
// components: { List },
async asyncData ({ $axios, req, res }) {
const show_tags = req.query.showtags
const tags = req.query.tags
const places = req.query.places
const events = await $axios.$get('/export/json')
return { events, show_tags }
},
}
</script>

View file

@ -3,26 +3,26 @@
b-card(no-body, :img-src='imgPath' v-loading='loading') b-card(no-body, :img-src='imgPath' v-loading='loading')
nuxt-link(to='/') nuxt-link(to='/')
el-button.close_button(circle icon='el-icon-close' type='success' el-button.close_button(circle icon='el-icon-close' type='success'
@click='$refs.eventDetail.hide()') @click.prevent='$refs.eventDetail.hide()')
b-card-header b-card-header
h3 {{event.title}} h3 {{event.title}}
v-icon(name='clock') v-icon(name='clock')
span {{event.start_datetime|datetime}} span {{event.start_datetime|datetime}}
br br
v-icon(name='map-marker-alt') v-icon(name='map-marker-alt')
//- span {{event.place.name}} - {{event.place.address}} span {{event.place.name}} - {{event.place.address}}
br br
b-card-body(v-if='event.description || event.tags') b-card-body(v-if='event.description || event.tags')
pre(v-html='event.description') pre(v-html='event.description')
br br
el-tag.mr-1(:color='tag.color || "grey"' v-for='tag in event.tags' el-tag.mr-1(:color='tag.color' v-for='tag in event.tags'
size='mini' :key='tag.tag') {{tag.tag}} size='mini' :key='tag.tag') {{tag.tag}}
.ml-auto(v-if='mine') div(v-if='mine')
hr hr
el-button(v-if='event.is_visible' plain type='warning' @click.prevents='toggle' icon='el-icon-view') {{$t('Unconfirm')}} 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('Confirm')}} 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('Remove')}} 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('Edit')}} el-button(plain type='primary' @click='$router.replace("/edit/"+event.id)') <v-icon color='orange' name='edit'/> {{$t('common.edit')}}
//- COMMENTS ... //- COMMENTS ...
//- b-navbar(type="dark" variant="dark" toggleable='lg') //- b-navbar(type="dark" variant="dark" toggleable='lg')
@ -34,10 +34,17 @@
//- span.mr-3 {{event.comments.length}} <v-icon name='comments'/> //- span.mr-3 {{event.comments.length}} <v-icon name='comments'/>
//- a(href='#', @click='remove') //- a(href='#', @click='remove')
v-icon(color='orange' name='times') v-icon(color='orange' name='times')
//- b-card-footer(v-for='comment in event.comments') //- el-footer(v-for='comment in event.comments')
strong {{comment.author}} strong {{comment.author}}
div(v-html='comment.text') div(v-html='comment.text')
//- el-timeline
//- el-timeline-item(v-for='comment in event.comments')
//- p(v-html='comment.text')
//- a.el-timeline-item__timestamp(href='') {{comment.createdAt}}
strong {{$t('common.comments')}}
div.text.item(v-for='comment in event.comments')
span(v-html='comment.text')
</template> </template>
<script> <script>
import { mapState, mapActions } from 'vuex'; import { mapState, mapActions } from 'vuex';
@ -46,13 +53,27 @@ import { mapState, mapActions } from 'vuex';
export default { export default {
name: 'Event', name: 'Event',
head () {
return {
title: this.event.title,
meta: [
// 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: 'og-description', name: 'og:description', content: this.event.description },
{ hid: 'og-title', property: 'og:title', content: this.event.title },
{ hid: 'og-url', property: 'og:url', content: `event/${this.event.id}` },
{ property: 'og:type', content: 'event'},
{ property: 'og:image', content: this.imgPath }
]
}
},
computed: { computed: {
...mapState(['user']), ...mapState([]),
imgPath () { imgPath () {
return this.event.image_path && process.env.VUE_APP_API + '/uploads/' + this.event.image_path return this.event.image_path && '/media/' + this.event.image_path
}, },
mine () { mine () {
return this.event.userId === this.user.id || this.user.is_admin return this.event.userId === this.$auth.user.id || this.$auth.user.is_admin
} }
}, },
data () { data () {
@ -90,11 +111,9 @@ export default {
try { try {
if (this.event.is_visible) { if (this.event.is_visible) {
await this.$axios.$get(`/event/unconfirm/${this.id}`) await this.$axios.$get(`/event/unconfirm/${this.id}`)
// await api.unconfirmEvent(this.id)
this.event.is_visible = false this.event.is_visible = false
} else { } else {
await this.$axios.$get(`/event/confirm/${this.id}`) await this.$axios.$get(`/event/confirm/${this.id}`)
// await api.confirmEvent(this.id)
this.event.is_visible = true this.event.is_visible = true
} }
} catch (e) { } catch (e) {

View file

@ -1,53 +1,58 @@
<template lang="pug"> <template lang="pug">
b-modal(ref='modal' @hidden='$router.replace("/")' b-modal(ref='modal' @hidden='$router.replace("/")'
:title='$t("Export")' :visible='true' size='lg' hide-footer) :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('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(color='#409EFF' size='mini' v-for='tag in filters.tags' :key='tag.tag') {{tag}}
li(v-if='filters.places.length') {{$t('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(color='#409EFF' 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(tabPosition='left' 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_explanation`)') p(v-html='$t(`export.email_description`)')
el-form(@submit.native.prevent) el-form(@submit.native.prevent)
//- 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('Insert your address')" ref='email') el-input.mt-2(v-model='notification.email' :placeholder="$t('common.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('Send')}}
el-tab-pane.pt-1(label='feed rss' name='feed') el-tab-pane.pt-1(label='feed rss' name='feed')
span(v-html='$t(`export_feed_explanation`)') span(v-html='$t(`export.feed_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("Copy")}} el-button(slot='append' plain type="primary" icon='el-icon-document' v-clipboard:copy="link") {{$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_explanation`)') 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("Copy")}} el-button(slot='append' plain type="primary" icon='el-icon-document' v-clipboard:copy="link") {{$t("common.opy")}}
el-tab-pane.pt-1(label='list' name='list') el-tab-pane.pt-1(label='list' name='list')
p(v-html='$t(`export_list_explanation`)') p(v-html='$t(`export.list_description`)')
el-card.mb-1(no-body header='Eventi') //- el-form-item(:label="$t('export.show_tags')")
b-list-group#list(flush) el-switch(v-model='list.show_tags')
b-list-group-item.flex-column.align-items-start(v-for="event in filteredEvents" :key='event.id'
:to='`/event/${event.id}`') iframe(:src='`http://localhost:3000/embed/list?tags=cia&showtags=${list.show_tags?"true":""}`' height='300')
//- b-media //- el-card.mb-1(no-body header='Eventi')
img(v-if='event.image_path' slot="aside" :src="imgPath(event)" alt="Meia Aside" style='max-height: 60px') //- b-list-group#list(flush)
small.float-right {{event.start_datetime|datetime}} //- b-list-group-item.flex-column.align-items-start(v-for="event in filteredEvents" :key='event.id'
strong.mb-1 {{event.title}} //- :to='`/event/${event.id}`')
br //- //- b-media
small.float-right {{event.place.name}} //- img(v-if='event.image_path' slot="aside" :src="imgPath(event)" alt="Meia Aside" style='max-height: 60px')
el-tag.mr-1(:color='tag.color || "grey"' size='mini' v-for='tag in event.tags' :key='tag.tag') {{tag.tag}} //- small.float-right {{event.start_datetime|datetime}}
//- 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-input.mb-1(type='textarea' v-model='script')
el-button.float-right(plain type="primary" icon='el-icon-document' v-clipboard:copy="script") Copy el-button.float-right(plain type="primary" icon='el-icon-document' v-clipboard:copy="script") Copy
el-tab-pane.pt-1(label='calendar' name='calendar') el-tab-pane.pt-1(label='calendar' name='calendar')
p(v-html='$t(`export_calendar_explanation`)') p(v-html='$t(`export.calendar_description`)')
Calendar.mb-1 //- no-ssr
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' v-clipboard:copy="script") Copy
@ -57,13 +62,14 @@ import { mapState } from 'vuex'
import path from 'path' import path from 'path'
// import filters from '../filters' // import filters from '../filters'
import Calendar from '@/components/Calendar' import Calendar from '@/components/Calendar'
import List from '@/components/List'
import {intersection} from 'lodash' import {intersection} from 'lodash'
// import api from '@/api' // import api from '@/api'
import { Message } from 'element-ui' import { Message } from 'element-ui'
export default { export default {
name: 'Export', name: 'Export',
components: { Calendar }, components: { List },
data () { data () {
return { return {
type: 'email', type: 'email',
@ -71,6 +77,7 @@ export default {
export_list: true, export_list: true,
script: `<iframe>Ti piacerebbe</iframe>`, script: `<iframe>Ti piacerebbe</iframe>`,
notification: { email: '' }, notification: { email: '' },
list: { show_tags: true },
} }
}, },
// filters, // filters,
@ -113,7 +120,7 @@ export default {
}, },
}, },
computed: { computed: {
...mapState(['filters', 'user', 'logged', 'events']), ...mapState(['filters', 'events']),
filteredEvents () { filteredEvents () {
return this.$store.getters.filteredEvents.filter(e => !e.past) return this.$store.getters.filteredEvents.filter(e => !e.past)
}, },

View file

@ -26,7 +26,7 @@ export default {
// if (code) { // if (code) {
// const res = await api.setCode({code}) // const res = await api.setCode({code})
// } // }
const user = await $axios.$get('/user') const user = await $axios.$get('/auth/user')
user.mastodon_auth = '' user.mastodon_auth = ''
return { user } //, mastodon_instance: user.mastodon_auth.instance } return { user } //, mastodon_instance: user.mastodon_auth.instance }
// this.user = user // this.user = user

View file

@ -1,7 +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,
Form, Tabs, TabPane, Switch, Input, Loading, TimeSelect, Form, Tabs, TabPane, Switch, Input, Loading, TimeSelect,
TableColumn, ColorPicker, Pagination, Popover } from 'element-ui' TableColumn, ColorPicker, Pagination, Popover, Tooltip,
Container, Footer , Timeline, TimelineItem} 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'
@ -9,6 +10,11 @@ locale.use(localeIt)
export default () => { export default () => {
Vue.use(Button) Vue.use(Button)
Vue.use(Container)
Vue.use(Timeline)
Vue.use(TimelineItem)
Vue.use(Footer)
Vue.use(Tooltip)
Vue.use(Popover) Vue.use(Popover)
Vue.use(Card) Vue.use(Card)
Vue.use(Select) Vue.use(Select)

View file

@ -1,9 +1,9 @@
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' // import 'v-calendar/lib/v-calendar.min.css'
export default () => { export default () => {
Vue.use(VCalendar, { Vue.use(VCalendar, {
firstDayOfWeek: 2 firstDayOfWeek: 2
}) })
} }

View file

@ -1,8 +1,9 @@
// ~/plugins/vuex-persist.js // // ~/plugins/vuex-persist.js
import VuexPersistence from 'vuex-persist' // import VuexPersistence from 'vuex-persist'
export default ({ store }) => { // export default ({ store }) => {
return new VuexPersistence({ // const per = new VuexPersistence({
reducer: state => ({ logged: state.logged, user: state.user, token: state.token }) // reducer: state => ({ logged: state.logged, user: state.user, token: state.token })
}).plugin(store) // }).plugin(store)
} // store.dispatch('login')
// }

View file

@ -1,43 +1,30 @@
const jwt = require('jsonwebtoken')
const { Op } = require('sequelize') const { Op } = require('sequelize')
const config = require('./config') const config = require('./config')
const User = require('./models/user') const User = require('./models/user')
const Auth = { const Auth = {
fillUser(req, res, next) { async fillUser(req, res, next) {
const token = if (!req.user) return next(new Error('ERROR! No user'))
req.body.token || req.params.token || req.headers.authorization req.user = await User.findOne({
if (!token) return next() where: { id: { [Op.eq]: req.user.id }, is_active: true }
jwt.verify(token, config.secret, async (err, decoded) => {
if (err) return next()
req.user = await User.findOne({
where: { email: { [Op.eq]: decoded.email }, is_active: true }
})
next()
}) })
next()
}, },
isAuth(req, res, next) { async isAuth(req, res, next) {
const token = if (!req.user) {
(req.body && req.body.token) || return res
req.params.token || .status(403)
req.headers.authorization .send({ message: 'Failed to authenticate token ' })
if (!token) return res.status(403).send({ message: 'Token not found' }) }
jwt.verify(token, config.secret, async (err, decoded) => { req.user = await User.findOne({
if (err) { where: { id: { [Op.eq]: req.user.id }, is_active: true }
return res
.status(403)
.send({ message: 'Failed to authenticate token ' + err })
}
req.user = await User.findOne({
where: { email: { [Op.eq]: decoded.email }, is_active: true }
})
if (!req.user) {
return res
.status(403)
.send({ message: 'Failed to authenticate token ' + err })
}
next()
}) })
if (!req.user) {
return res
.status(403)
.send({ message: 'Failed to authenticate token ' + err })
}
next()
}, },
isAdmin(req, res, next) { isAdmin(req, res, next) {
if (req.user.is_admin && req.user.is_active) return next() if (req.user.is_admin && req.user.is_active) return next()

View file

@ -6,11 +6,11 @@ module.exports = {
locale: process.env.LOCALE || 'it', locale: process.env.LOCALE || 'it',
title: process.env.TITLE || 'GANCIO', title: process.env.TITLE || 'GANCIO',
description: process.env.DESCRIPTION || 'A calendar for radical communities', description: process.env.DESCRIPTION || 'A calendar for radical communities',
baseurl: process.env.BASE_URL || 'http://localhost:8080', baseurl: process.env.BASE_URL || 'http://localhost:3000',
apiurl: apiurl:
env === 'production' env === 'production'
? process.env.BASE_URL + '/api' ? process.env.BASE_URL + '/api'
: 'http://localhost:9000', : 'http://localhost:3000/api',
db, db,
admin: process.env.ADMIN_EMAIL, admin: process.env.ADMIN_EMAIL,

View file

@ -1,17 +1,29 @@
// const { User, Event, Comment, Tag } = require('../model') const { User, Event, Comment, Tag } = require('../model')
const config = require('../config') const config = 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
const settingsController = require('./settings')
const fs = require('fs') const fs = require('fs')
const path = require('path') const path = require('path')
const moment = require('moment') const moment = require('moment')
moment.locale('it') moment.locale('it')
const botController = { const botController = {
bots: [], bot: null,
// async initialize () { async initialize () {
// console.log('initialize bots') console.log('initialize bot')
const settings = await settingsController.settings()
if (!settings.mastodon_auth) return
const mastodon_auth = settings.mastodon_auth
console.log('instance ', `https://${mastodon_auth.instance}/api/v1/`)
botController.bot = new Mastodon({
access_token: mastodon_auth.access_token,
api_url: `https://${mastodon_auth.instance}/api/v1`
})
const listener = botController.bot.stream('/streaming/direct')
listener.on('message', botController.message)
listener.on('error', botController.error)
// const botUsers = await User.findAll({ where: { mastodon_auth: { [Op.ne]: null } } }) // const botUsers = await User.findAll({ where: { mastodon_auth: { [Op.ne]: null } } })
// console.log(botUsers) // console.log(botUsers)
// botController.bots = botUsers.map(user => { // botController.bots = botUsers.map(user => {
@ -21,7 +33,6 @@ const botController = {
// const bot = new Mastodon({ access_token, api_url: `https://${user.mastodon_instance}/api/v1/` }) // const bot = new Mastodon({ access_token, api_url: `https://${user.mastodon_instance}/api/v1/` })
// const listener = bot.stream('streaming/direct') // const listener = bot.stream('streaming/direct')
// listener.on('message', botController.message) // listener.on('message', botController.message)
// listener.on('error', botController.error)
// return { email: user.email, bot } // return { email: user.email, bot }
// }) // })
// console.log(botController.bots) // console.log(botController.bots)
@ -32,8 +43,9 @@ const botController = {
// listener.on('message', botController.message) // listener.on('message', botController.message)
// listener.on('error', botController.error) // listener.on('error', botController.error)
// botController.bots.push({ email: user.email, bot }) // botController.bots.push({ email: user.email, bot })
// }, },
async post (mastodon_auth, event) { async post (mastodon_auth, event) {
console.log('dentro post!')
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')} -
@ -41,28 +53,30 @@ ${event.description.length > 200 ? event.description.substr(0, 200) + '...' : ev
let media let media
if (event.image_path) { if (event.image_path) {
const file = path.join(__dirname, '..', '..', 'uploads', event.image_path) const file = path.join(__dirname, '..', '..', '..', 'uploads', event.image_path)
if (fs.statSync(file)) { if (fs.statSync(file)) {
media = await bot.post('media', { file: fs.createReadStream(file) }) media = await bot.post('media', { file: fs.createReadStream(file) })
} }
} }
return bot.post('statuses', { status, visibility: 'public', media_ids: media ? [media.data.id] : [] }) return bot.post('statuses', { status, visibility: 'direct', media_ids: media ? [media.data.id] : [] })
} },
// async message (msg) { async message (msg) {
// console.log(msg) console.log(msg)
// console.log(msg.data.accounts) console.log(msg.data.accounts)
// const replyid = msg.data.in_reply_to_id || msg.data.last_status.in_reply_to_id const replyid = msg.data.in_reply_to_id || msg.data.last_status.in_reply_to_id
// if (!replyid) return if (!replyid) return
// const event = await Event.findOne({ where: { activitypub_id: replyid } }) const event = await Event.findOne({ where: { activitypub_id: replyid } })
// if (!event) { if (!event) {
// check for comment.. console.error('associated event not found !')
// const comment = await Comment.findOne( {where: { }}) // check for comment..
// } // const comment = await Comment.findOne( {where: { }})
// const comment = await Comment.create({activitypub_id: msg.data.last_status.id, text: msg.data.last_status.content, author: msg.data.accounts[0].username }) return
// event.addComment(comment) }
// console.log(event) const comment = await Comment.create({activitypub_id: msg.data.last_status.id, text: msg.data.last_status.content, author: msg.data.accounts[0].username })
// const comment = await Comment.findOne( { where: {activitypub_id: msg.data.in_reply_to}} ) event.addComment(comment)
// console.log('dentro message ', data) console.log(event)
// const comment = await Comment.findOne( { where: {activitypub_id: msg.data.in_reply_to}} )
// console.log('dentro message ', data)
// add comment to specified event // add comment to specified event
// let comment // let comment
@ -72,11 +86,11 @@ ${event.description.length > 200 ? event.description.substr(0, 200) + '...' : ev
// } // }
// const comment = new Comment(req.body) // const comment = new Comment(req.body)
// event.addComment(comment) // event.addComment(comment)
// }, },
// error (err) { error (err) {
// console.log('error ', err) console.log('error ', err)
// } }
} }
// setTimeout(botController.initialize, 2000) setTimeout(botController.initialize, 2000)
module.exports = botController module.exports = botController

View file

@ -136,7 +136,6 @@ const eventController = {
}, },
async getAll(req, res) { async getAll(req, res) {
console.log('sono qui dentro !')
// this is due how v-calendar shows dates // this is due how v-calendar shows dates
const start = moment().year(req.params.year).month(req.params.month) const start = moment().year(req.params.year).month(req.params.month)
.startOf('month').startOf('isoWeek') .startOf('month').startOf('isoWeek')
@ -145,20 +144,20 @@ const eventController = {
if (shownDays <= 34) end = end.add(1, 'week') if (shownDays <= 34) end = end.add(1, 'week')
end = end.endOf('isoWeek') end = end.endOf('isoWeek')
const events = await Event.findAll({ const events = await Event.findAll({
// where: { where: {
// is_visible: true, is_visible: true,
// [Op.and]: [ [Op.and]: [
// { start_datetime: { [Op.gte]: start } }, { start_datetime: { [Op.gte]: start } },
// { start_datetime: { [Op.lte]: end } } { start_datetime: { [Op.lte]: end } }
// ] ]
// }, },
// order: [['start_datetime', 'ASC']], order: [['start_datetime', 'ASC']],
// include: [ include: [
// { model: User, required: false }, { model: User, required: false },
// Comment, Comment,
// Tag, Tag,
// { model: Place, required: false } { model: Place, required: false }
// ] ]
}) })
// console.log(events) // console.log(events)
res.json(events) res.json(events)

View file

@ -32,6 +32,8 @@ const exportController = {
return exportController.feed(res, events.slice(0, 20)) return exportController.feed(res, events.slice(0, 20))
case 'ics': case 'ics':
return exportController.ics(res, events) return exportController.ics(res, events)
case 'json':
return res.json(events)
} }
}, },

View file

@ -27,12 +27,12 @@ const userController = {
} else { } else {
// if user is found and password is right // if user is found and password is right
// create a token // create a token
const accessToken = jsonwebtoken.sign({ user: const accessToken = jsonwebtoken.sign(
{ {
id: user.id, id: user.id,
email: user.email, email: user.email,
scope: [user.is_admin ? 'admin' : 'user'] scope: [user.is_admin ? 'admin' : 'user']
}}, },
config.secret config.secret
) )

View file

@ -7,7 +7,7 @@ const userController = require('./controller/user')
const settingsController = require('./controller/settings') const settingsController = require('./controller/settings')
const config = require('./config') const config = require('./config')
// const botController = require('./controller/bot') const botController = require('./controller/bot')
const jwt = require('express-jwt')({secret: config.secret}) const jwt = require('express-jwt')({secret: config.secret})
const storage = require('./storage')({ const storage = require('./storage')({
@ -20,7 +20,7 @@ const api = express.Router()
// 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)
api.get('/auth/user', jwt, userController.current) api.get('/auth/user', jwt, fillUser, userController.current)
api.post('/user/recover', userController.forgotPassword) api.post('/user/recover', userController.forgotPassword)
api.post('/user/check_recover_code', userController.checkRecoverCode) api.post('/user/check_recover_code', userController.checkRecoverCode)
@ -33,32 +33,32 @@ api
// get current user // get current user
// .get(isAuth, userController.current) // .get(isAuth, userController.current)
// update user (eg. confirm) // update user (eg. confirm)
.put(isAuth, isAdmin, userController.update) .put(jwt, isAuth, isAdmin, userController.update)
// get all users // get all users
api.get('/users', isAuth, isAdmin, userController.getAll) api.get('/users', jwt, isAuth, isAdmin, userController.getAll)
// update a tag (modify color) // update a tag (modify color)
api.put('/tag', isAuth, isAdmin, eventController.updateTag) api.put('/tag', jwt, isAuth, isAdmin, eventController.updateTag)
// update a place (modify address..) // update a place (modify address..)
api.put('/place', isAuth, isAdmin, eventController.updatePlace) api.put('/place', jwt, isAuth, isAdmin, eventController.updatePlace)
api api
.route('/user/event') .route('/user/event')
// add event // add event
.post(fillUser, upload.single('image'), userController.addEvent) .post(jwt, fillUser, upload.single('image'), userController.addEvent)
// update event // update event
.put(isAuth, upload.single('image'), userController.updateEvent) .put(jwt, isAuth, upload.single('image'), userController.updateEvent)
// remove event // remove event
api.delete('/user/event/:id', isAuth, userController.delEvent) api.delete('/user/event/:id', jwt, isAuth, userController.delEvent)
// get tags/places // get tags/places
api.get('/event/meta', eventController.getMeta) api.get('/event/meta', eventController.getMeta)
// get unconfirmed events // get unconfirmed events
api.get('/event/unconfirmed', isAuth, isAdmin, eventController.getUnconfirmed) api.get('/event/unconfirmed', jwt, isAuth, isAdmin, eventController.getUnconfirmed)
// add event notification // add event notification
api.post('/event/notification', eventController.addNotification) api.post('/event/notification', eventController.addNotification)
@ -71,22 +71,17 @@ api.post('/settings', settingsController.setAdminSetting)
api.get('/event/:event_id', eventController.get) api.get('/event/:event_id', eventController.get)
// confirm event // confirm event
api.get('/event/confirm/:event_id', isAuth, isAdmin, eventController.confirm) api.get('/event/confirm/:event_id', jwt, isAuth, isAdmin, eventController.confirm)
api.get( api.get('/event/unconfirm/:event_id', jwt, isAuth, isAdmin, eventController.unconfirm)
'/event/unconfirm/:event_id',
isAuth,
isAdmin,
eventController.unconfirm
)
// export events (rss/ics) // export events (rss/ics)
api.get('/export/:type', exportController.export) api.get('/export/:type', exportController.export)
// get events in this range // get events in this range
api.get('/event/:year/:month', eventController.getAll) api.get('/event/:month/:year', eventController.getAll)
// mastodon oauth auth // mastodon oauth auth
api.post('/user/getauthurl', isAuth, userController.getAuthURL) api.post('/user/getauthurl', jwt, isAuth, userController.getAuthURL)
api.post('/user/code', isAuth, userController.code) api.post('/user/code', jwt, isAuth, userController.code)
module.exports = api module.exports = api

View file

@ -9,8 +9,9 @@ const Event = db.define('event', {
start_datetime: { type: Sequelize.DATE, index: true }, start_datetime: { type: Sequelize.DATE, index: true },
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,
activitypub_id: { type: Sequelize.INTEGER, index: true }, activitypub_id: { type: Sequelize.INTEGER, index: true },
is_visible: Sequelize.BOOLEAN // activitypub_ids: { type: Sequelize.ARRAY, index}
}) })
const Tag = db.define('tag', { const Tag = db.define('tag', {
@ -20,6 +21,8 @@ const Tag = db.define('tag', {
const Comment = db.define('comment', { const Comment = db.define('comment', {
activitypub_id: { type: Sequelize.INTEGER, index: true }, activitypub_id: { type: Sequelize.INTEGER, index: true },
url: Sequelize.STRING,
media_attachments: { type: Sequelize.ARRAY(Sequelize.STRING) },
author: Sequelize.STRING, author: Sequelize.STRING,
text: Sequelize.STRING text: Sequelize.STRING
}) })
@ -63,10 +66,10 @@ Event.belongsTo(Place)
User.hasMany(Event) User.hasMany(Event)
Place.hasMany(Event) Place.hasMany(Event)
// async function init() { async function init() {
// await Notification.findOrCreate({ where: { type: 'mastodon', filters: { is_visible: true } } }) await Notification.findOrCreate({ where: { type: 'mastodon', filters: { is_visible: true } } })
// await Notification.findOrCreate({ where: { type: 'admin_email', filters: { is_visible: false } } }) // await Notification.findOrCreate({ where: { type: 'admin_email', filters: { is_visible: false } } })
// } }
// init() init()
module.exports = { Event, Comment, Tag, Place, Notification, EventNotification } module.exports = { Event, Comment, Tag, Place, Notification, EventNotification }

65
server/cron.js Normal file
View file

@ -0,0 +1,65 @@
// const mail = require('./mail')
const bot = require('./api/controller/bot')
const settingsController = require('./api/controller/settings')
const config = require('./api/config.js')
const { Event, Notification, EventNotification,
User, Place, Tag } = require('./api/model')
let settings
async function sendNotification (notification, event, eventNotification) {
const promises = []
switch (notification.type) {
// case 'mail':
// return mail.send(notification.email, 'event', { event, config, notification })
// case 'admin_email':
// const admins = await User.findAll({ where: { is_admin: true } })
// const admin_emails = admins.map(admin => admin.email)
// return mail.send(admin_emails, 'event', { event, to_confirm: true, notification })
case 'mastodon':
// instance publish
if (settings.mastodon_auth.instance && settings.mastodon_auth.access_token) {
const b = bot.post(settings.mastodon_auth, event).then(b => {
console.log('ho postato admin post cose', b.data.id)
event.activitypub_id = b.data.id
return event.save()
})
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)
}
async function loop () {
settings = await settingsController.settings()
// get all event notification in queue
const eventNotifications = await EventNotification.findAll({ where: { status: 'new' } })
const promises = eventNotifications.map(async e => {
const event = await Event.findByPk(e.eventId, { include: [User, Place, Tag] })
if (!event.place) return
const notification = await Notification.findByPk(e.notificationId)
try {
await sendNotification(notification, event, e)
e.status = 'sent'
return e.save()
} catch (err) {
console.error(err)
e.status = 'error'
return e.save()
}
})
return Promise.all(promises)
}
setInterval(loop, 260000)
loop()

View file

@ -3,6 +3,7 @@ const consola = require('consola')
const morgan = require('morgan') const morgan = require('morgan')
const bodyParser = require('body-parser') const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser') const cookieParser = require('cookie-parser')
const path = require('path')
const { Nuxt, Builder } = require('nuxt') const { Nuxt, Builder } = require('nuxt')
const app = express() const app = express()
const cors = require('cors') const cors = require('cors')
@ -32,6 +33,7 @@ async function start() {
// Give nuxt middleware to express // Give nuxt middleware to express
app.use(cors(corsConfig)) app.use(cors(corsConfig))
app.use(morgan('dev')) app.use(morgan('dev'))
app.use('/media/', express.static(path.join(__dirname, '..', 'uploads')))
app.use(cookieParser()) app.use(cookieParser())
app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json()) app.use(bodyParser.json())

View file

@ -103,11 +103,13 @@ export const actions = {
// set user if logged! TODO // set user if logged! TODO
const now = new Date() const now = new Date()
// const events = await api.getAllEvents(now.getMonth() - 1, now.getFullYear()) // const events = await api.getAllEvents(now.getMonth() - 1, now.getFullYear())
const events = await this.$axios.$get(`/event/${now.getMonth() - 1}/${now.getFullYear()}`) const events = await this.$axios.$get(`/event/${now.getMonth()}/${now.getFullYear()}`)
commit('setEvents', events) 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}/${page.year}`) const events = await this.$axios.$get(`/event/${page.month-1}/${page.year}`)
commit('setEvents', events) commit('setEvents', events)
}, },
async updateMeta({ commit }) { async updateMeta({ commit }) {
@ -116,9 +118,7 @@ export const actions = {
}, },
async addEvent({ commit }, formData) { async addEvent({ commit }, formData) {
const event = await this.$axios.$post('/user/event', formData) // .addEvent(formData) const event = await this.$axios.$post('/user/event', formData) // .addEvent(formData)
if (this.state.logged) { commit('addEvent', event)
commit('addEvent', event)
}
}, },
async updateEvent({ commit }, formData) { async updateEvent({ commit }, formData) {
const event = await this.$axios.$put('/user/event', formData) const event = await this.$axios.$put('/user/event', formData)

View file

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Gancio Widget Example</title>
<script src="https://unpkg.com/vue"></script>
<script src='dist/gancio-widget.min.js'></script>
<link rel="stylesheet" href="../list/style.css">
</head>
<body>
<gancio-widget minimal></gancio-widget>
</body>
</html>

0
widgets/list/index.html Normal file
View file

12
widgets/list/index.js Normal file
View file

@ -0,0 +1,12 @@
import Vue from 'vue'
import vueCustomElement from 'vue-custom-element'
import App from '../../components/List'
// import router from './router'
// import store from '../../store'
Vue.use(vueCustomElement)
// App.store = store
// App.router = router
Vue.customElement('gancio-widget', App)
export default App

3
widgets/list/style.css Normal file
View file

@ -0,0 +1,3 @@
#gancio-widget {
border: 1px solid black;
}