funkwhale/front/src/App.vue

455 wiersze
17 KiB
Vue
Czysty Zwykły widok Historia

<template>
<div id="app" :key="String($store.state.instance.instanceUrl)" :class="[$store.state.ui.queueFocused ? 'queue-focused' : '', {'has-bottom-player': $store.state.queue.tracks.length > 0}, `is-${ $store.getters['ui/windowSize']}`]">
<!-- here, we display custom stylesheets, if any -->
2018-12-04 14:13:37 +00:00
<link
v-for="url in customStylesheets"
rel="stylesheet"
property="stylesheet"
:href="url"
:key="url"
>
<template>
<sidebar></sidebar>
<set-instance-modal @update:show="showSetInstanceModal = $event" :show="showSetInstanceModal"></set-instance-modal>
2020-02-25 13:43:14 +00:00
<service-messages></service-messages>
<transition name="queue">
<queue @touch-progress="$refs.player.setCurrentTime($event)" v-if="$store.state.ui.queueFocused"></queue>
</transition>
<router-view role="main" :class="{hidden: $store.state.ui.queueFocused}"></router-view>
<player ref="player"></player>
2018-12-04 14:13:37 +00:00
<app-footer
:class="{hidden: $store.state.ui.queueFocused}"
2018-12-04 14:13:37 +00:00
:version="version"
@show:shortcuts-modal="showShortcutsModal = !showShortcutsModal"
@show:set-instance-modal="showSetInstanceModal = !showSetInstanceModal"
2018-12-04 14:13:37 +00:00
></app-footer>
<playlist-modal v-if="$store.state.auth.authenticated"></playlist-modal>
<channel-upload-modal v-if="$store.state.auth.authenticated"></channel-upload-modal>
2019-02-14 09:49:06 +00:00
<filter-modal v-if="$store.state.auth.authenticated"></filter-modal>
2019-09-09 09:10:25 +00:00
<report-modal></report-modal>
<shortcuts-modal @update:show="showShortcutsModal = $event" :show="showShortcutsModal"></shortcuts-modal>
2018-12-04 14:13:37 +00:00
<GlobalEvents @keydown.h.exact="showShortcutsModal = !showShortcutsModal"/>
</template>
</div>
</template>
<script>
import Vue from 'vue'
import axios from 'axios'
import _ from '@/lodash'
import {mapState, mapGetters, mapActions} from 'vuex'
2018-09-13 15:18:23 +00:00
import { WebSocketBridge } from 'django-channels'
import GlobalEvents from '@/components/utils/global-events'
import moment from 'moment'
import locales from './locales'
import {getClientOnlyRadio} from '@/radios'
2018-03-20 18:57:34 +00:00
export default {
name: 'app',
2018-02-17 20:23:45 +00:00
components: {
Player: () => import(/* webpackChunkName: "audio" */ "@/components/audio/Player"),
Queue: () => import(/* webpackChunkName: "audio" */ "@/components/Queue"),
PlaylistModal: () => import(/* webpackChunkName: "auth-audio" */ "@/components/playlists/PlaylistModal"),
ChannelUploadModal: () => import(/* webpackChunkName: "auth-audio" */ "@/components/channels/UploadModal"),
Sidebar: () => import(/* webpackChunkName: "core" */ "@/components/Sidebar"),
AppFooter: () => import(/* webpackChunkName: "core" */ "@/components/Footer"),
ServiceMessages: () => import(/* webpackChunkName: "core" */ "@/components/ServiceMessages"),
SetInstanceModal: () => import(/* webpackChunkName: "core" */ "@/components/SetInstanceModal"),
ShortcutsModal: () => import(/* webpackChunkName: "core" */ "@/components/ShortcutsModal"),
FilterModal: () => import(/* webpackChunkName: "moderation" */ "@/components/moderation/FilterModal"),
ReportModal: () => import(/* webpackChunkName: "moderation" */ "@/components/moderation/ReportModal"),
GlobalEvents,
2018-02-17 20:23:45 +00:00
},
data () {
return {
2018-09-13 15:18:23 +00:00
bridge: null,
instanceUrl: null,
showShortcutsModal: false,
showSetInstanceModal: false,
initialTitle: document.title,
width: window.innerWidth
}
},
2019-09-23 09:14:54 +00:00
async created () {
if (navigator.serviceWorker) {
navigator.serviceWorker.addEventListener(
'controllerchange', () => {
if (this.serviceWorker.refreshing) return;
this.$store.commit('ui/serviceWorker', {
refreshing: true
})
window.location.reload();
}
);
}
window.addEventListener('resize', this.handleResize);
this.handleResize();
2018-09-13 15:18:23 +00:00
this.openWebsocket()
2018-03-01 23:14:40 +00:00
let self = this
if (!this.$store.state.ui.selectedLanguage) {
this.autodetectLanguage()
}
2018-03-01 22:46:32 +00:00
setInterval(() => {
// used to redraw ago dates every minute
self.$store.commit('ui/computeLastDate')
}, 1000 * 60)
2019-09-23 09:14:54 +00:00
const urlParams = new URLSearchParams(window.location.search);
const serverUrl = urlParams.get('_server')
if (serverUrl) {
this.$store.commit('instance/instanceUrl', serverUrl)
}
const url = urlParams.get('_url')
if (url) {
this.$router.replace(url)
}
2019-09-23 09:14:54 +00:00
else if (!this.$store.state.instance.instanceUrl) {
// we have several way to guess the API server url. By order of precedence:
// 1. use the url provided in settings.json, if any
// 2. use the url specified when building via VUE_APP_INSTANCE_URL
// 3. use the current url
let defaultInstanceUrl = this.$store.state.instance.frontSettings.defaultServerUrl || process.env.VUE_APP_INSTANCE_URL || this.$store.getters['instance/defaultUrl']()
this.$store.commit('instance/instanceUrl', defaultInstanceUrl)
2018-08-21 18:24:35 +00:00
} else {
// needed to trigger initialization of axios / service worker
2018-08-21 18:24:35 +00:00
this.$store.commit('instance/instanceUrl', this.$store.state.instance.instanceUrl)
}
2019-09-23 09:14:54 +00:00
await this.fetchNodeInfo()
this.$store.dispatch('auth/check')
setInterval(() => {
// used to refresh profile every now and then (important for refreshing scoped tokens)
self.$store.dispatch('auth/check')
}, 1000 * 60 * 60 * 8)
this.$store.dispatch('instance/fetchSettings')
2018-09-13 15:18:23 +00:00
this.$store.commit('ui/addWebsocketEventHandler', {
eventName: 'inbox.item_added',
id: 'sidebarCount',
handler: this.incrementNotificationCountInSidebar
})
this.$store.commit('ui/addWebsocketEventHandler', {
eventName: 'mutation.created',
id: 'sidebarReviewEditCount',
handler: this.incrementReviewEditCountInSidebar
})
this.$store.commit('ui/addWebsocketEventHandler', {
eventName: 'mutation.updated',
id: 'sidebarReviewEditCount',
handler: this.incrementReviewEditCountInSidebar
})
this.$store.commit('ui/addWebsocketEventHandler', {
eventName: 'report.created',
id: 'sidebarPendingReviewReportCount',
handler: this.incrementPendingReviewReportsCountInSidebar
})
2020-03-18 10:57:33 +00:00
this.$store.commit('ui/addWebsocketEventHandler', {
eventName: 'user_request.created',
id: 'sidebarPendingReviewRequestCount',
handler: this.incrementPendingReviewRequestsCountInSidebar
})
this.$store.commit('ui/addWebsocketEventHandler', {
eventName: 'Listen',
id: 'handleListen',
handler: this.handleListen
})
2018-09-13 15:18:23 +00:00
},
mounted () {
let self = this
// slight hack to allow use to have internal links in <translate> tags
// while preserving router behaviour
document.documentElement.addEventListener('click', function (event) {
if (!event.target.matches('a.internal')) return;
self.$router.push(event.target.getAttribute('href'))
event.preventDefault();
}, false);
this.$nextTick(() => {
document.getElementById('fake-content').classList.add('loaded')
})
},
2018-09-13 15:18:23 +00:00
destroyed () {
this.$store.commit('ui/removeWebsocketEventHandler', {
eventName: 'inbox.item_added',
id: 'sidebarCount',
})
this.$store.commit('ui/removeWebsocketEventHandler', {
eventName: 'mutation.created',
id: 'sidebarReviewEditCount',
})
this.$store.commit('ui/removeWebsocketEventHandler', {
eventName: 'mutation.updated',
id: 'sidebarReviewEditCount',
})
this.$store.commit('ui/removeWebsocketEventHandler', {
eventName: 'mutation.updated',
id: 'sidebarPendingReviewReportCount',
})
2020-03-18 10:57:33 +00:00
this.$store.commit('ui/removeWebsocketEventHandler', {
eventName: 'user_request.created',
id: 'sidebarPendingReviewRequestCount',
})
this.$store.commit('ui/removeWebsocketEventHandler', {
eventName: 'Listen',
id: 'handleListen',
})
2018-09-13 15:18:23 +00:00
this.disconnect()
},
methods: {
2018-09-13 15:18:23 +00:00
incrementNotificationCountInSidebar (event) {
this.$store.commit('ui/incrementNotifications', {type: 'inbox', count: 1})
},
incrementReviewEditCountInSidebar (event) {
this.$store.commit('ui/incrementNotifications', {type: 'pendingReviewEdits', value: event.pending_review_count})
},
incrementPendingReviewReportsCountInSidebar (event) {
this.$store.commit('ui/incrementNotifications', {type: 'pendingReviewReports', value: event.unresolved_count})
},
2020-03-18 10:57:33 +00:00
incrementPendingReviewRequestsCountInSidebar (event) {
this.$store.commit('ui/incrementNotifications', {type: 'pendingReviewRequests', value: event.pending_count})
},
handleListen (event) {
if (this.$store.state.radios.current && this.$store.state.radios.running) {
let current = this.$store.state.radios.current
if (current.clientOnly && current.type === 'account') {
getClientOnlyRadio(current).handleListen(current, event, this.$store)
}
}
},
2019-09-23 09:14:54 +00:00
async fetchNodeInfo () {
let response = await axios.get('instance/nodeinfo/2.0/')
this.$store.commit('instance/nodeinfo', response.data)
},
autodetectLanguage () {
let userLanguage = navigator.language || navigator.userLanguage
let available = locales.locales.map(e => { return e.code })
let self = this
let candidate
let matching = available.filter((a) => {
return userLanguage.replace('-', '_') === a
})
let almostMatching = available.filter((a) => {
return userLanguage.replace('-', '_').split('_')[0] === a.split('_')[0]
})
if (matching.length > 0) {
candidate = matching[0]
} else if (almostMatching.length > 0) {
candidate = almostMatching[0]
} else {
return
}
this.$store.commit('ui/currentLanguage', candidate)
2018-09-13 15:18:23 +00:00
},
disconnect () {
if (!this.bridge) {
return
}
this.bridge.socket.close(1000, 'goodbye', {keepClosed: true})
},
openWebsocket () {
if (!this.$store.state.auth.authenticated) {
return
}
this.disconnect()
let self = this
let token = this.$store.state.auth.token
// let token = 'test'
2018-09-13 15:18:23 +00:00
const bridge = new WebSocketBridge()
this.bridge = bridge
let url = this.$store.getters['instance/absoluteUrl'](`api/v1/activity?token=${token}`)
2018-09-13 15:18:23 +00:00
url = url.replace('http://', 'ws://')
url = url.replace('https://', 'wss://')
bridge.connect(
url,
[],
2018-12-20 13:31:56 +00:00
{reconnectInterval: 1000 * 60})
2018-09-13 15:18:23 +00:00
bridge.listen(function (event) {
self.$store.dispatch('ui/websocketEvent', event)
})
bridge.socket.addEventListener('open', function () {
console.log('Connected to WebSocket')
})
},
getTrackInformationText(track) {
const trackTitle = track.title
2020-02-05 14:06:07 +00:00
const albumArtist = (track.album) ? track.album.artist.name : null
const artistName = (
2020-02-05 14:06:07 +00:00
(track.artist) ? track.artist.name : albumArtist)
const text = `${trackTitle}${artistName}`
return text
},
updateDocumentTitle() {
let parts = []
const currentTrackPart = (
(this.currentTrack) ? this.getTrackInformationText(this.currentTrack)
: null)
if (currentTrackPart) {
parts.push(currentTrackPart)
}
if (this.$store.state.ui.pageTitle) {
parts.push(this.$store.state.ui.pageTitle)
}
parts.push(this.initialTitle || 'Funkwhale')
document.title = parts.join(' – ')
},
2020-02-25 13:43:14 +00:00
updateApp () {
this.$store.commit('ui/serviceWorker', {updateAvailable: false})
if (!this.serviceWorker.registration || !this.serviceWorker.registration.waiting) { return; }
this.serviceWorker.registration.waiting.postMessage({command: 'skipWaiting'})
},
handleResize() {
this.width = window.innerWidth
}
},
computed: {
...mapState({
2019-09-23 09:14:54 +00:00
messages: state => state.ui.messages,
nodeinfo: state => state.instance.nodeinfo,
playing: state => state.player.playing,
bufferProgress: state => state.player.bufferProgress,
isLoadingAudio: state => state.player.isLoadingAudio,
serviceWorker: state => state.ui.serviceWorker,
}),
...mapGetters({
hasNext: "queue/hasNext",
currentTrack: 'queue/currentTrack',
progress: "player/progress",
}),
labels() {
let play = this.$pgettext('Sidebar/Player/Icon.Tooltip/Verb', "Play track")
let pause = this.$pgettext('Sidebar/Player/Icon.Tooltip/Verb', "Pause track")
let next = this.$pgettext('Sidebar/Player/Icon.Tooltip', "Next track")
let expandQueue = this.$pgettext('Sidebar/Player/Icon.Tooltip/Verb', "Expand queue")
return {
play,
pause,
next,
expandQueue,
}
},
suggestedInstances () {
2019-01-17 11:17:29 +00:00
let instances = this.$store.state.instance.knownInstances.slice(0)
if (this.$store.state.instance.frontSettings.defaultServerUrl) {
2019-01-17 11:17:29 +00:00
let serverUrl = this.$store.state.instance.frontSettings.defaultServerUrl
if (!serverUrl.endsWith('/')) {
serverUrl = serverUrl + '/'
}
instances.push(serverUrl)
}
2019-01-17 11:17:29 +00:00
instances.push(this.$store.getters['instance/defaultUrl'](), 'https://demo.funkwhale.audio/')
return _.uniq(instances.filter((e) => {return e}))
},
version () {
if (!this.nodeinfo) {
return null
}
return _.get(this.nodeinfo, 'software.version')
},
customStylesheets () {
if (this.$store.state.instance.frontSettings) {
return this.$store.state.instance.frontSettings.additionalStylesheets || []
}
},
},
watch: {
'$store.state.instance.instanceUrl' (v) {
this.$store.dispatch('instance/fetchSettings')
this.fetchNodeInfo()
},
2019-06-17 06:45:31 +00:00
'$store.state.ui.theme': {
immediate: true,
handler (newValue, oldValue) {
let oldTheme = oldValue || 'light'
document.body.classList.remove(`theme-${oldTheme}`)
document.body.classList.add(`theme-${newValue}`)
},
},
2018-09-13 15:18:23 +00:00
'$store.state.auth.authenticated' (newValue) {
if (!newValue) {
this.disconnect()
} else {
this.openWebsocket()
}
},
'$store.state.ui.currentLanguage': {
immediate: true,
handler(newValue) {
let self = this
let htmlLocale = newValue.toLowerCase().replace('_', '-')
document.documentElement.setAttribute('lang', htmlLocale);
if (newValue === 'en_US') {
self.$language.current = 'noop'
self.$language.current = newValue
return self.$store.commit('ui/momentLocale', 'en')
}
import(/* webpackChunkName: "locale-[request]" */ `./translations/${newValue}.json`).then((response) =>{
Vue.$translations[newValue] = response.default[newValue]
}).finally(() => {
// set current language twice, otherwise we seem to have a cache somewhere
// and rendering does not happen
self.$language.current = 'noop'
self.$language.current = newValue
})
let momentLocale = newValue.replace('_', '-').toLowerCase()
import(/* webpackChunkName: "moment-locale-[request]" */ `moment/locale/${momentLocale}.js`).then(() => {
self.$store.commit('ui/momentLocale', momentLocale)
}).catch(() => {
console.log('No momentjs locale available for', momentLocale)
let shortLocale = momentLocale.split('-')[0]
import(/* webpackChunkName: "moment-locale-[request]" */ `moment/locale/${shortLocale}.js`).then(() => {
self.$store.commit('ui/momentLocale', shortLocale)
}).catch(() => {
console.log('No momentjs locale available for', shortLocale)
})
})
}
},
'currentTrack': {
immediate: true,
handler(newValue) {
this.updateDocumentTitle()
},
},
'$store.state.ui.pageTitle': {
immediate: true,
handler(newValue) {
this.updateDocumentTitle()
},
},
2020-02-25 13:43:14 +00:00
'serviceWorker.updateAvailable': {
handler (v) {
if (!v) {
return
}
2020-02-25 13:43:14 +00:00
let self = this
this.$store.commit('ui/addMessage', {
content: this.$pgettext("App/Message/Paragraph", "A new version of the app is available."),
date: new Date(),
key: 'refreshApp',
displayTime: 0,
classActions: 'bottom attached opaque',
2020-02-25 13:43:14 +00:00
actions: [
{
text: this.$pgettext("App/Message/Paragraph", "Update"),
class: "primary",
click: function () {
self.updateApp()
},
},
{
text: this.$pgettext("App/Message/Paragraph", "Later"),
class: "basic",
}
]
})
},
immediate: true,
}
}
}
</script>
<style lang="scss">
2018-12-19 21:04:35 +00:00
@import "style/_main";
</style>