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": [],
"in-progress": [],
"done": [
{
"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": [
{
"assignedTo": {
@ -15,18 +48,6 @@
}
],
"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": {
"name": "lesion"
@ -99,21 +120,19 @@
"name": "lesion"
},
"category": "feature",
"creation_time": "2019-04-23T19:46:46.332Z",
"id": "3",
"prio": 0,
"creation_time": "2019-04-23T19:44:56.705Z",
"id": "1",
"references": [],
"title": "export lista"
"title": "popup sul calendario"
},
{
"assignedTo": {
"name": "lesion"
},
"category": "feature",
"creation_time": "2019-04-23T19:44:56.705Z",
"id": "1",
"creation_time": "2019-04-27T19:44:33.769Z",
"id": "12",
"references": [],
"title": "popup sul calendario"
"title": "rifare il calendario o solo il popup"
},
{
"assignedTo": {
@ -137,6 +156,15 @@
"references": [],
"title": "documentare sorgenti",
"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">
v-calendar#calendar.card(
title-position='left'
locale='it'
is-dark
show-caps
:attributes='attributes'
:from-page.sync='page'
is-expanded is-inline)
//- div(slot='popover', slot-scope='{ customData }')
//- router-link(:to="`/event/${customData.id}`") {{customData.start_datetime|hour}} - {{customData.title}} @{{customData.place.name}}
div(slot='popover', slot-scope='{ customData, attributes }')
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>
<script>
import { mapState, mapActions } from 'vuex'
// import filters from '@/filters'
import moment from 'dayjs'
import { intersection } from 'lodash'
@ -21,12 +30,11 @@ export default {
const year = moment().year()
return {
page: { month, year},
selectedEvent: {},
daysWithEvents: {}
}
},
// async mounted () {
// await this.updateEvents(this.page)
// },
watch: {
page () {
this.updateEvents(this.page)
@ -34,17 +42,28 @@ export default {
},
methods: {
...mapActions(['updateEvents']),
nextEvent () {
},
eventToAttribute(event) {
let e = {
key: event.id,
customData: event,
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)'
if (event.past) color = 'rgba(200,200,200,0.5)'
if (event.multidate) {
@ -65,14 +84,14 @@ export default {
filteredEvents () {
return this.$store.getters.filteredEvents
},
...mapState(['events', 'filters', 'user', 'logged']),
...mapState(['events', 'filters']),
attributes () {
return [
{ key: 'todaly', dates: new Date(),
{ key: 'today', dates: new Date(),
highlight: {
backgroundColor: '#aaffaa'
},
// popover: {label: this.$t('Today')}
popover: {label: this.$t('common.today')}
},
...this.filteredEvents.map(this.eventToAttribute)
]

View file

@ -5,9 +5,9 @@
:img-src='imgPath')
strong {{event.title}}
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
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}}
</template>
<script>
@ -20,7 +20,7 @@ export default {
computed: {
...mapState(['user']),
imgPath() {
return this.event.image_path && '/uploads/thumb/' + this.event.image_path
return this.event.image_path && '/media/thumb/' + this.event.image_path
},
mine() {
return this.event.userId === this.user.id

View file

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

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')}}
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')}}
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')}}
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')}}
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')}}
b-nav-item
b-navbar-nav.ml-auto
b-nav-item(to='/about')
span {{$t('common.info')}} <v-icon color='#ff9fc4' name='question-circle'/>
@ -26,7 +27,7 @@ import {mapState, mapActions} from 'vuex'
export default {
name: 'Nav',
computed: {
...mapState(['filters', 'auth']),
...mapState(['filters']),
filters_tags: {
set (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",
"what": "Cosa",
"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": {
@ -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.",
"address_description": "",
"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/i18n', '@/plugins/bootstrap-vue',
'@/plugins/vue-awesome',
'@/plugins/v-calendar',
{ src: '@/plugins/vuex-persist', ssr: false },
{ src: '@/plugins/v-calendar', ssr: false },
{ src: '@/plugins/vuex-persist.js', ssr: false },
'@/plugins/magic-grid'],
/*
@ -68,7 +68,7 @@ module.exports = {
endpoints: {
login: { url: '/auth/login', method: 'post', propertyName: 'token' },
logout: { url: '/auth/logout', method: 'post' },
user: { url: '/auth/user', method: 'get', propertyName: 'user' }
user: { url: '/auth/user', method: 'get', propertyName: false }
},
// tokenRequired: true,
// tokenType: 'bearer',

View file

@ -40,6 +40,7 @@
"sqlite3": "^4.0.6",
"v-calendar": "^0.9.7",
"vue-awesome": "^3.5.1",
"vue-custom-element": "^3.2.6",
"vue-i18n": "^8.10.0",
"vue-magic-grid": "^0.0.4",
"vuex-persist": "^2.0.0"
@ -61,6 +62,7 @@
"eslint-plugin-vue": "^5.2.2",
"nodemon": "^1.18.9",
"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')
//- 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'/>
p(v-html="$t('event.anon_description')")
el-button.float-right(@click='next' :disabled='!couldProceed') {{$t('common.next')}}
@ -13,7 +13,14 @@
//- WHERE
el-tab-pane
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-option(v-for='place in places_name' :label='place' :value='place' :key='place.id')
div {{$t("common.address")}}
@ -119,7 +126,6 @@ export default {
places_name: state => state.places.map(p => p.name ),
places: state => state.places,
user: state => state.user,
logged: state => state.logged
}),
disableAddress () {
console.log('dentro disable Address')
@ -128,7 +134,7 @@ export default {
return ret
},
couldProceed () {
const t = this.logged ? -1 : 0
const t = this.$auth.loggedIn ? -1 : 0
switch(Number(this.activeTab)) {
case 0+t:
return true
@ -209,7 +215,7 @@ export default {
this.updateMeta()
this.sending = false
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) {
this.sending = false
console.error(e)

View file

@ -1,5 +1,5 @@
<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')
el-tabs(tabPosition='left' v-model='tab')
@ -7,55 +7,56 @@
el-tab-pane.pt-1
template(slot='label')
v-icon(name='users')
span.ml-1 {{$t('Users')}}
span.ml-1 {{$t('common.users')}}
el-table(:data='paginatedUsers' small)
el-table-column(label='Email')
template(slot-scope='data')
el-popover(trigger='hover' :content='data.row.description' width='400')
span(slot='reference') {{data.row.email}}
el-table-column(label='Azioni')
el-table-column(:label="$t('common.actions')")
template(slot-scope='data')
el-button.mr-1(size='mini'
: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'
: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')
//- PLACES
el-tab-pane.pt-1
template(slot='label')
v-icon(name='map-marker-alt')
span.ml-1 {{$t('Places')}}
p {{$t('admin_place_explanation')}}
span.ml-1 {{$t('common.places')}}
p {{$t('admin.place_description')}}
el-form.mb-2(:inline='true' label-width='120px')
el-form-item(:label="$t('Name')")
el-input.mr-1(:placeholder='$t("Name")' v-model='place.name')
el-form-item(:label="$t('Address')")
el-input.mr-1(:placeholder='$t("Address")' v-model='place.address')
el-button(variant='primary' @click='savePlace') {{$t('Save')}}
b-table(selectable :items='places' :fields='placeFields' striped hover
small selectedVariant='success' primary-key='id'
select-mode="single" @row-selected='placeSelected'
:per-page='perPage' :current-page='placePage')
el-form-item(:label="$t('common.name')")
el-input.mr-1(:placeholder='$t("common.name")' v-model='place.name')
el-form-item(:label="$t('common.address')")
el-input.mr-1(:placeholder='$t("common.address")' v-model='place.address')
el-button(variant='primary' @click='savePlace') {{$t('common.save')}}
el-table(:data='paginatedPlaces' small)
el-table-column(:label="$t('common.name')")
template(slot-scope='data') {{data.row.name}}
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')
//- EVENTS
el-tab-pane.pt-1
template(slot='label')
v-icon(name='calendar')
span.ml-1 {{$t('Events')}}
p {{$t('event_confirm_explanation')}}
span.ml-1 {{$t('common.events')}}
p {{$t('admin.event_confirm_description')}}
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}}
el-table-column(:label='$t("Where")')
el-table-column(:label='$t("common.where")')
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')
el-button(type='primary' @click='confirm(data.row.id)' size='mini') {{$t('Confirm')}}
el-button(type='success' @click='preview(data.row.id)' size='mini') {{$t('Preview')}}
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('common.preview')}}
el-pagination(:page-size='perPage' :currentPage.sync='eventPage' :total='events.length')
@ -63,29 +64,29 @@
el-tab-pane.pt-1
template(slot='label')
v-icon(name='tag')
span {{$t('Tags')}}
p {{$t('admin_tag_explanation')}}
el-tag(v-if='tag.tag' :color='tag.color || "grey"' size='mini') {{tag.tag}}
span {{$t('common.tags')}}
p {{$t('admin.tag_description')}}
el-tag(v-if='tag.tag' :color='tag.color' size='mini') {{tag.tag}}
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-table(:data='paginatedTags' striped small hover
highlight-current-row @current-change="tagSelected")
el-table-column(label='Tag')
el-table-column(:label="$t('common.tag')")
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')
//- SETTINGS
el-tab-pane.pt-1
template(slot='label')
v-icon(name='tools')
span {{$t('Settings')}}
el-form(inline)
span {{$t('admin_mastodon_explanation')}}
span {{$t('common.settings')}}
el-form(inline @submit.prevent.stop='associatemastodon_instance')
span {{$t('admin.mastodon_description')}}
el-input(v-model="mastodon_instance")
span(slot='prepend') {{$t('Mastodon instance')}}
el-button(slot='append' @click='associate' variant='success' type='success') {{$t('Associate')}}
span(slot='prepend') {{$t('admin.mastodon_instance')}}
el-button(slot='append' @click='associate' :disabled='!mastodon_instance.length') {{$t('common.associate')}}
</template>
<script>
@ -117,21 +118,28 @@ export default {
tab: "0",
}
},
// async mounted () {
// const code = this.$route.query.code
// if (code) {
// this.tab = "4"
// const instance = await api.setCode({code, is_admin: true})
// }
async mounted () {
console.log('sono dentro mounted', this.$route)
const code = this.$route.query.code
if (code) {
this.tab = "4"
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()
// this.mastodon_instance = this.settings.mastodon_auth && this.settings.mastodon_auth.instance
// },
},
async asyncData ({ $axios, params, store }) {
console.log(store.state)
const users = await $axios.$get('/users')
return { users }
try {
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: {
...mapState(['tags', 'places']),
@ -146,7 +154,11 @@ export default {
paginatedUsers () {
return this.users.slice((this.userPage-1) * this.perPage,
this.userPage * this.perPage)
}
},
paginatedPlaces () {
return this.places.slice((this.placePage-1) * this.perPage,
this.placePage * this.perPage)
},
},
methods: {
placeSelected (items) {
@ -160,7 +172,7 @@ export default {
this.place.id = item.id
},
tagSelected (tag) {
this.tag = tag
this.tag = { color: tag.color, tag: tag.tag }
},
async savePlace () {
const place = await api.updatePlace(this.place)
@ -174,20 +186,25 @@ export default {
const newuser = await api.updateUser(user)
},
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) {
this.$router.push(`/event/${id}`)
},
async associate () {
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);
},
async confirm (id) {
try {
this.loading = true
await api.confirmEvent(id)
await this.$axios.$get(`/event/confirm/${id}`)
this.loading = false
Message({
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')
nuxt-link(to='/')
el-button.close_button(circle icon='el-icon-close' type='success'
@click='$refs.eventDetail.hide()')
@click.prevent='$refs.eventDetail.hide()')
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}}
span {{event.place.name}} - {{event.place.address}}
br
b-card-body(v-if='event.description || event.tags')
pre(v-html='event.description')
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}}
.ml-auto(v-if='mine')
div(v-if='mine')
hr
el-button(v-if='event.is_visible' plain type='warning' @click.prevents='toggle' icon='el-icon-view') {{$t('Unconfirm')}}
el-button(v-else plain type='success' @click.prevents='toggle' icon='el-icon-view') {{$t('Confirm')}}
el-button(plain type='danger' @click.prevent='remove' icon='el-icon-remove') {{$t('Remove')}}
el-button(plain type='primary' @click='$router.replace("/edit/"+event.id)') <v-icon color='orange' name='edit'/> {{$t('Edit')}}
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')}}
//- COMMENTS ...
//- b-navbar(type="dark" variant="dark" toggleable='lg')
@ -34,10 +34,17 @@
//- span.mr-3 {{event.comments.length}} <v-icon name='comments'/>
//- a(href='#', @click='remove')
v-icon(color='orange' name='times')
//- b-card-footer(v-for='comment in event.comments')
strong {{comment.author}}
div(v-html='comment.text')
//- el-footer(v-for='comment in event.comments')
strong {{comment.author}}
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>
<script>
import { mapState, mapActions } from 'vuex';
@ -46,13 +53,27 @@ import { mapState, mapActions } from 'vuex';
export default {
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: {
...mapState(['user']),
...mapState([]),
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 () {
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 () {
@ -90,11 +111,9 @@ export default {
try {
if (this.event.is_visible) {
await this.$axios.$get(`/event/unconfirm/${this.id}`)
// await api.unconfirmEvent(this.id)
this.event.is_visible = false
} else {
await this.$axios.$get(`/event/confirm/${this.id}`)
// await api.confirmEvent(this.id)
this.event.is_visible = true
}
} catch (e) {

View file

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

View file

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

View file

@ -1,7 +1,8 @@
import Vue from 'vue'
import { Button, Select, Tag, Option, Table, FormItem, Card,
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 localeIt from 'element-ui/lib/locale/lang/it'
import locale from 'element-ui/lib/locale'
@ -9,6 +10,11 @@ locale.use(localeIt)
export default () => {
Vue.use(Button)
Vue.use(Container)
Vue.use(Timeline)
Vue.use(TimelineItem)
Vue.use(Footer)
Vue.use(Tooltip)
Vue.use(Popover)
Vue.use(Card)
Vue.use(Select)

View file

@ -1,9 +1,9 @@
import Vue from 'vue'
import VCalendar from 'v-calendar'
import 'v-calendar/lib/v-calendar.min.css'
// import 'v-calendar/lib/v-calendar.min.css'
export default () => {
Vue.use(VCalendar, {
firstDayOfWeek: 2
})
}
}

View file

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

View file

@ -1,43 +1,30 @@
const jwt = require('jsonwebtoken')
const { Op } = require('sequelize')
const config = require('./config')
const User = require('./models/user')
const Auth = {
fillUser(req, res, next) {
const token =
req.body.token || req.params.token || req.headers.authorization
if (!token) return next()
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()
async fillUser(req, res, next) {
if (!req.user) return next(new Error('ERROR! No user'))
req.user = await User.findOne({
where: { id: { [Op.eq]: req.user.id }, is_active: true }
})
next()
},
isAuth(req, res, next) {
const token =
(req.body && req.body.token) ||
req.params.token ||
req.headers.authorization
if (!token) return res.status(403).send({ message: 'Token not found' })
jwt.verify(token, config.secret, async (err, decoded) => {
if (err) {
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()
async isAuth(req, res, next) {
if (!req.user) {
return res
.status(403)
.send({ message: 'Failed to authenticate token ' })
}
req.user = await User.findOne({
where: { id: { [Op.eq]: req.user.id }, is_active: true }
})
if (!req.user) {
return res
.status(403)
.send({ message: 'Failed to authenticate token ' + err })
}
next()
},
isAdmin(req, res, 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',
title: process.env.TITLE || 'GANCIO',
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:
env === 'production'
? process.env.BASE_URL + '/api'
: 'http://localhost:9000',
: 'http://localhost:3000/api',
db,
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 Mastodon = require('mastodon-api')
// const Sequelize = require('sequelize')
// const Op = Sequelize.Op
const settingsController = require('./settings')
const fs = require('fs')
const path = require('path')
const moment = require('moment')
moment.locale('it')
const botController = {
bots: [],
// async initialize () {
// console.log('initialize bots')
bot: null,
async initialize () {
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 } } })
// console.log(botUsers)
// 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 listener = bot.stream('streaming/direct')
// listener.on('message', botController.message)
// listener.on('error', botController.error)
// return { email: user.email, bot }
// })
// console.log(botController.bots)
@ -32,8 +43,9 @@ const botController = {
// listener.on('message', botController.message)
// listener.on('error', botController.error)
// botController.bots.push({ email: user.email, bot })
// },
},
async post (mastodon_auth, event) {
console.log('dentro post!')
const { access_token, instance } = mastodon_auth
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')} -
@ -41,28 +53,30 @@ ${event.description.length > 200 ? event.description.substr(0, 200) + '...' : ev
let media
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)) {
media = await bot.post('media', { file: fs.createReadStream(file) })
}
}
return bot.post('statuses', { status, visibility: 'public', media_ids: media ? [media.data.id] : [] })
}
// async message (msg) {
// console.log(msg)
// console.log(msg.data.accounts)
// const replyid = msg.data.in_reply_to_id || msg.data.last_status.in_reply_to_id
// if (!replyid) return
// const event = await Event.findOne({ where: { activitypub_id: replyid } })
// if (!event) {
// check for comment..
// const comment = await Comment.findOne( {where: { }})
// }
// const comment = await Comment.create({activitypub_id: msg.data.last_status.id, text: msg.data.last_status.content, author: msg.data.accounts[0].username })
// event.addComment(comment)
// console.log(event)
// const comment = await Comment.findOne( { where: {activitypub_id: msg.data.in_reply_to}} )
// console.log('dentro message ', data)
return bot.post('statuses', { status, visibility: 'direct', media_ids: media ? [media.data.id] : [] })
},
async message (msg) {
console.log(msg)
console.log(msg.data.accounts)
const replyid = msg.data.in_reply_to_id || msg.data.last_status.in_reply_to_id
if (!replyid) return
const event = await Event.findOne({ where: { activitypub_id: replyid } })
if (!event) {
console.error('associated event not found !')
// check for comment..
// const comment = await Comment.findOne( {where: { }})
return
}
const comment = await Comment.create({activitypub_id: msg.data.last_status.id, text: msg.data.last_status.content, author: msg.data.accounts[0].username })
event.addComment(comment)
console.log(event)
// const comment = await Comment.findOne( { where: {activitypub_id: msg.data.in_reply_to}} )
// console.log('dentro message ', data)
// add comment to specified event
// let comment
@ -72,11 +86,11 @@ ${event.description.length > 200 ? event.description.substr(0, 200) + '...' : ev
// }
// const comment = new Comment(req.body)
// event.addComment(comment)
// },
// error (err) {
// console.log('error ', err)
// }
},
error (err) {
console.log('error ', err)
}
}
// setTimeout(botController.initialize, 2000)
setTimeout(botController.initialize, 2000)
module.exports = botController

View file

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

View file

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

View file

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

View file

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

View file

@ -9,8 +9,9 @@ const Event = db.define('event', {
start_datetime: { type: Sequelize.DATE, index: true },
end_datetime: { type: Sequelize.DATE, index: true },
image_path: Sequelize.STRING,
is_visible: Sequelize.BOOLEAN,
activitypub_id: { type: Sequelize.INTEGER, index: true },
is_visible: Sequelize.BOOLEAN
// activitypub_ids: { type: Sequelize.ARRAY, index}
})
const Tag = db.define('tag', {
@ -20,6 +21,8 @@ const Tag = db.define('tag', {
const Comment = db.define('comment', {
activitypub_id: { type: Sequelize.INTEGER, index: true },
url: Sequelize.STRING,
media_attachments: { type: Sequelize.ARRAY(Sequelize.STRING) },
author: Sequelize.STRING,
text: Sequelize.STRING
})
@ -63,10 +66,10 @@ Event.belongsTo(Place)
User.hasMany(Event)
Place.hasMany(Event)
// async function init() {
// await Notification.findOrCreate({ where: { type: 'mastodon', filters: { is_visible: true } } })
// await Notification.findOrCreate({ where: { type: 'admin_email', filters: { is_visible: false } } })
// }
async function init() {
await Notification.findOrCreate({ where: { type: 'mastodon', filters: { is_visible: true } } })
// await Notification.findOrCreate({ where: { type: 'admin_email', filters: { is_visible: false } } })
}
// init()
init()
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 bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const path = require('path')
const { Nuxt, Builder } = require('nuxt')
const app = express()
const cors = require('cors')
@ -32,6 +33,7 @@ async function start() {
// Give nuxt middleware to express
app.use(cors(corsConfig))
app.use(morgan('dev'))
app.use('/media/', express.static(path.join(__dirname, '..', 'uploads')))
app.use(cookieParser())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

View file

@ -103,11 +103,13 @@ export const actions = {
// 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() - 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) {
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)
},
async updateMeta({ commit }) {
@ -116,9 +118,7 @@ export const actions = {
},
async addEvent({ commit }, 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) {
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;
}