further move functionality into store and services

This commit is contained in:
Jonas Heinrich 2021-01-18 14:51:53 +01:00
parent 855b5b2efe
commit bff3abd16c
12 changed files with 873 additions and 5 deletions

View File

@ -10,6 +10,8 @@
[234](https://git.project-insanity.org/onny/nextcloud-app-radio/-/issues/234) @onny
- Move menuState and volumeState into localStorage
[236](https://git.project-insanity.org/onny/nextcloud-app-radio/-/issues/236) @onny
- Create seperate store modules for player, favorites and recent
[239](https://git.project-insanity.org/onny/nextcloud-app-radio/-/issues/239) @onny
## 1.0.1 - 2020-12
### Added

View File

@ -23,3 +23,18 @@
<template>
<router-view />
</template>
<script>
import axios from '@nextcloud/axios'
export default {
name: 'App',
created() {
axios.defaults.headers.common = {
'User-Agent': 'Nextcloud Radio App/' + this.$version,
}
this.$store.dispatch('loadFavorites')
this.$store.dispatch('loadRecent')
},
}
</script>

View File

@ -42,9 +42,9 @@
class="stationIcon"
width="32"
height="32"
:hash="station.blurHash"
:hash="station.blurHash || 'L1TSUA?bj[?b~qfQfQj[ayfQfQfQ'"
:src="station.favicon" />
<span :class="{ 'icon-starred': favorites.flat().includes(station.stationuuid) }" />
<span :class="{ 'icon-starred': isFavorite(station) }" />
</td>
<td class="nameColumn" @click="doPlay(idx, station)">
<span class="innernametext">
@ -54,14 +54,14 @@
<td class="actionColumn">
<Actions>
<ActionButton
v-if="!favorites.flat().includes(station.stationuuid)"
v-if="!isFavorite(station)"
icon="icon-star"
:close-after-click="true"
@click="doFavor(idx, station)">
{{ t('radio', 'Add to favorites') }}
</ActionButton>
<ActionButton
v-if="favorites.flat().includes(station.stationuuid)"
v-if="isFavorite(station)"
icon="icon-star"
:close-after-click="true"
@click="doFavor(idx, station)">
@ -100,6 +100,7 @@
<script>
import Actions from '@nextcloud/vue/dist/Components/Actions'
import ActionButton from '@nextcloud/vue/dist/Components/ActionButton'
import Vuex from 'vuex'
export default {
name: 'Table',
@ -121,6 +122,9 @@ export default {
activeItem: null,
}),
computed: {
...Vuex.mapGetters([
'isFavorite',
]),
isFolder() {
if (this.stationData[0]) {
if (this.stationData[0].type === 'folder') {

View File

@ -38,7 +38,6 @@ Vue.prototype.t = translate
Vue.prototype.n = translatePlural
Vue.prototype.OC = window.OC
Vue.prototype.OCA = window.OCA
Vue.prototype.$apiUrl = 'https://de1.api.radio-browser.info'
Vue.prototype.$version = '1.0.2'
Vue.use(VueClipboard)

74
src/services/Player.js Normal file
View File

@ -0,0 +1,74 @@
/*
* @copyright Copyright (c) 2021 Jonas Heinrich <onny@project-insanity.org>
*
* @author Jonas Heinrich <onny@project-insanity.org>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
import { Howl, Howler } from 'howler'
import { showError } from '@nextcloud/dialogs'
import store from './../store/main.js'
let audioPlayer = null
export class Player {
doPlay(src) {
if (audioPlayer !== null) {
audioPlayer.fade(store.state.player.volume, 0, 500)
Howler.unload()
}
audioPlayer = new Howl({
src,
html5: true,
volume: store.state.player.volume,
onplay() {
store.dispatch('setPlaying', true)
store.dispatch('setBuffering', false)
},
onpause() {
store.dispatch('setPlaying', false)
store.dispatch('setBuffering', false)
},
onend() {
showError(t('radio', 'Lost connection to podcast station, retrying ...'))
store.dispatch('setPlaying', false)
store.dispatch('setBuffering', true)
},
})
audioPlayer.unload()
audioPlayer.play()
audioPlayer.fade(0, store.state.player.volume, 500)
}
doPause() {
audioPlayer.pause()
}
doResume() {
audioPlayer.play()
}
setVolume(volume) {
audioPlayer.volume(volume)
}
}

153
src/services/RadioApi.js Normal file
View File

@ -0,0 +1,153 @@
/*
* @copyright Copyright (c) 2021 Jonas Heinrich <onny@project-insanity.org>
*
* @author Jonas Heinrich <onny@project-insanity.org>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
import axios from '@nextcloud/axios'
import { generateUrl } from '@nextcloud/router'
const requesttoken = axios.defaults.headers.requesttoken
export class RadioApi {
url(url) {
url = `/apps/radio/api${url}`
return generateUrl(url)
}
addFavorite(station) {
let stationSrc = ''
if (!station.url_resolved) {
stationSrc = station.urlresolved
} else {
stationSrc = station.url_resolved
}
station = {
id: -1,
name: station.name.toString(),
urlresolved: stationSrc.toString(),
favicon: station.favicon.toString(),
stationuuid: station.stationuuid.toString(),
bitrate: station.bitrate.toString(),
country: station.country.toString(),
language: station.language.toString(),
homepage: station.homepage.toString(),
codec: station.codec.toString(),
tags: station.tags.toString(),
}
axios.defaults.headers.requesttoken = requesttoken
return axios.post(this.url('/favorites'), station)
.then(
(response) => {
return Promise.resolve(response.data)
},
(err) => {
return Promise.reject(err)
}
)
.catch((err) => {
return Promise.reject(err)
})
}
removeFavorite(station) {
axios.defaults.headers.requesttoken = requesttoken
return axios.delete(this.url(`/favorites/${station.id}`))
.then(
(response) => {
return Promise.resolve(response.data)
},
(err) => {
return Promise.reject(err)
}
)
.catch((err) => {
return Promise.reject(err)
})
}
loadFavorites() {
axios.defaults.headers.requesttoken = requesttoken
return axios.get(this.url('/favorites'))
.then(
(response) => {
return Promise.resolve(response.data)
},
(err) => {
return Promise.reject(err)
}
)
.catch((err) => {
return Promise.reject(err)
})
}
addRecent(station) {
let stationSrc = ''
if (!station.url_resolved) {
stationSrc = station.urlresolved
} else {
stationSrc = station.url_resolved
}
station = {
id: -1,
name: station.name.toString(),
urlresolved: stationSrc.toString(),
favicon: station.favicon.toString(),
stationuuid: station.stationuuid.toString(),
bitrate: station.bitrate.toString(),
country: station.country.toString(),
language: station.language.toString(),
homepage: station.homepage.toString(),
codec: station.codec.toString(),
tags: station.tags.toString(),
}
axios.defaults.headers.requesttoken = requesttoken
return axios.post(this.url('/recent'), station)
.then(
(response) => {
return Promise.resolve(response.data)
},
(err) => {
return Promise.reject(err)
}
)
.catch((err) => {
return Promise.reject(err)
})
}
loadRecent() {
axios.defaults.headers.requesttoken = requesttoken
return axios.get(this.url('/recent'))
.then(
(response) => {
return Promise.resolve(response.data)
},
(err) => {
return Promise.reject(err)
}
)
.catch((err) => {
return Promise.reject(err)
})
}
}

View File

@ -0,0 +1,104 @@
/*
* @copyright Copyright (c) 2021 Jonas Heinrich <onny@project-insanity.org>
*
* @author Jonas Heinrich <onny@project-insanity.org>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
import axios from '@nextcloud/axios'
export class RadioBrowserApi {
url() {
const url = 'https://de1.api.radio-browser.info'
return url
}
countClick(station) {
delete axios.defaults.headers.requesttoken
return axios.get(this.url() + '/json/url/' + station.stationuuid)
.then(
(response) => {
return Promise.resolve(response.data)
},
(err) => {
return Promise.reject(err)
}
)
.catch((err) => {
return Promise.reject(err)
})
}
queryList(listName, offset) {
let order = 'clickcount'
if (listName === 'NEW') {
order = 'lastchangetime'
}
delete axios.defaults.headers.requesttoken
return axios.get(this.url() + '/json/stations', {
params: {
limit: 20,
order,
reverse: true,
offset,
},
})
.then(
(response) => {
return Promise.resolve(response.data)
},
(err) => {
return Promise.reject(err)
}
)
.catch((err) => {
return Promise.reject(err)
})
}
searchStations(query, offset) {
delete axios.defaults.headers.requesttoken
return axios.get(this.url() + '/json/stations/byname/' + query, {
params: {
limit: 20,
order: 'clickcount',
offset,
},
})
.then(
(response) => {
return Promise.resolve(response.data)
},
(err) => {
return Promise.reject(err)
}
)
.catch((err) => {
return Promise.reject(err)
})
}
}

View File

@ -19,3 +19,58 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
import { RadioApi } from './../services/RadioApi'
const apiClient = new RadioApi()
export default {
state: {
favorites: [],
},
getters: {
favorites: state => {
return state.favorites
},
isFavorite: state => (station) => {
if (station !== undefined) {
const index = state.favorites.findIndex(_station => _station.stationuuid === station.stationuuid)
if (index !== -1) {
return true
}
}
return false
},
},
mutations: {
addFavorite(state, station) {
state.favorites.push(station)
},
removeFavorite(state, station) {
const existingIndex = state.favorites.findIndex(_station => _station.id === station.id)
if (existingIndex !== -1) {
state.favorites.splice(existingIndex, 1)
}
},
setFavorites(state, stations) {
state.favorites = stations
},
},
actions: {
async loadFavorites({ commit }) {
const stations = await apiClient.loadFavorites()
commit('setFavorites', stations)
},
addFavorite({ commit }, station) {
apiClient.addFavorite(station)
.then((station) => {
commit('addFavorite', station)
})
},
removeFavorite({ commit }, station) {
apiClient.removeFavorite(station)
.then((station) => {
commit('removeFavorite', station)
})
},
},
}

View File

@ -24,6 +24,7 @@ import Vue from 'vue'
import Vuex from 'vuex'
import player from './player'
import favorites from './favorites'
import recent from './recent'
Vue.use(Vuex)
@ -31,6 +32,7 @@ export default new Vuex.Store({
modules: {
player,
favorites,
recent,
},
state: {
menu: localStorage.getItem('radio.menu') || 'top',

View File

@ -20,6 +20,9 @@
*
*/
import { Player } from './../services/Player'
const player = new Player()
export default ({
state: {
isPlaying: false,
@ -83,5 +86,18 @@ export default ({
setTitle(context, title) {
context.commit('setTitle', title)
},
playStation(context, station) {
if (context.state.isPaused) {
context.commit('setPausing', false)
context.commit('setBuffering', true)
player.doResume()
} else {
context.commit('setBuffering', true)
context.commit('setTitle', station.name)
context.commit('setPausing', false)
player.doPlay(station.enclosure)
}
},
},
})

67
src/store/recent.js Normal file
View File

@ -0,0 +1,67 @@
/*
* @copyright Copyright (c) 2021 Jonas Heinrich <onny@project-insanity.org>
*
* @author Jonas Heinrich <onny@project-insanity.org>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
import { RadioApi } from './../services/RadioApi'
const apiClient = new RadioApi()
export default {
state: {
recent: [],
},
getters: {
recent: state => {
return state.recent
},
},
mutations: {
addRecent(state, station) {
state.recent.push(station)
},
removeRecent(state, station) {
const existingIndex = state.recent.findIndex(_station => _station.id === station.id)
if (existingIndex !== -1) {
state.recent.splice(existingIndex, 1)
}
},
setRecent(state, stations) {
state.recent = stations
},
},
actions: {
async loadRecent({ commit }) {
const stations = await apiClient.loadRecent()
commit('setRecent', stations)
},
addRecent({ commit }, station) {
apiClient.addRecent(station)
.then((station) => {
commit('addRecent', station)
})
},
removeRecent({ commit }, station) {
apiClient.removeRecent(station)
.then((station) => {
commit('removeRecent', station)
})
},
},
}

377
src/views/Main.vue Normal file
View File

@ -0,0 +1,377 @@
<!--
- @copyright Copyright (c) 2021 Jonas Heinrich
-
- @author Jonas Heinrich <onny@project-insanity.org>
-
- @license GNU AGPL version 3 or any later version
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as
- published by the Free Software Foundation, either version 3 of the
- License, or (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Affero General Public License for more details.
-
- You should have received a copy of the GNU Affero General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-->
<template>
<Content app-name="radio">
<Navigation
:station-data="stations" />
<AppContent>
<Table
v-show="!pageLoading && stations.length > 0"
v-resize="onResize"
:station-data="stations"
:favorites="favorites"
@doPlay="doPlay"
@doFavor="doFavor"
@toggleSidebar="toggleSidebar" />
<EmptyContent
v-if="pageLoading"
icon="icon-loading" />
<EmptyContent
v-if="stations.length === 0 && !pageLoading"
:icon="emptyContentIcon">
{{ emptyContentMessage }}
<template #desc>
{{ emptyContentDesc }}
</template>
</EmptyContent>
</AppContent>
<Sidebar
:show-sidebar="showSidebar"
:sidebar-station="sidebarStation"
@toggleSidebar="toggleSidebar" />
</Content>
</template>
<script>
import Content from '@nextcloud/vue/dist/Components/Content'
import AppContent from '@nextcloud/vue/dist/Components/AppContent'
import EmptyContent from '@nextcloud/vue/dist/Components/EmptyContent'
import Navigation from './../components/Navigation'
import Table from './../components/Table'
import Sidebar from './../components/Sidebar'
import { Howl, Howler } from 'howler'
import { showError } from '@nextcloud/dialogs'
import Vuex from 'vuex'
import { RadioBrowserApi } from './../services/RadioBrowserApi'
const apiClient = new RadioBrowserApi()
let audioPlayer = null
export default {
name: 'Main',
components: {
Navigation,
Content,
AppContent,
Table,
EmptyContent,
Sidebar,
},
data: () => ({
pageLoading: false,
blurHashes: require('../assets/blurHashes.json'),
showSidebar: false,
sidebarStation: {},
queryParams: {},
tableData: [],
}),
computed: {
...Vuex.mapGetters([
'favorites',
'recent',
'isFavorite',
]),
stations() {
if (this.$route.name === 'FAVORITES') {
return this.favorites
} else if (this.$route.name === 'RECENT') {
return this.recent
}
return this.tableData
},
player() {
return this.$store.state.player
},
emptyContentMessage() {
if (this.$route.name === 'FAVORITES') {
return t('radio', 'No favorites yet')
} else if (this.$route.name === 'RECENT') {
return t('radio', 'No recent stations yet')
} else if (this.$route.name === 'SEARCH') {
return t('radio', 'No search results')
}
return 'No stations here'
},
emptyContentIcon() {
if (this.$route.name === 'FAVORITES') {
return 'icon-star'
} else if (this.$route.name === 'RECENT') {
return 'icon-recent'
} else if (this.$route.name === 'SEARCH') {
return 'icon-search'
}
return 'icon-radio'
},
emptyContentDesc() {
if (this.$route.name === 'FAVORITES') {
return t('radio', 'Stations you mark as favorite will show up here')
} else if (this.$route.name === 'RECENT') {
return t('radio', 'Stations you recently played will show up here')
} else if (this.$route.name === 'SEARCH') {
return t('radio', 'No stations were found matching your search term')
}
return t('radio', 'No stations here')
},
},
watch: {
$route: 'onRoute',
'player.volume'(newVolume, oldVolume) {
if (audioPlayer !== null) {
audioPlayer.volume(newVolume)
}
},
'player.isPaused'(newState, oldState) {
if (newState === true && audioPlayer !== null) {
audioPlayer.pause()
} else if (newState === false && audioPlayer !== null) {
audioPlayer.play()
}
},
},
mounted() {
this.onRoute()
this.scroll()
},
methods: {
onResize({ width, height }) {
const contentHeight = document.getElementById('app-content-vue').scrollHeight
const tableHeight = height
if (tableHeight < contentHeight) {
this.preFill()
}
},
preFill() {
const route = this.$route
this.loadStations(route.name)
},
async onRoute() {
this.tableData = []
this.pageLoading = true
const route = this.$route
this.loadStations(route.name)
},
/**
* Favor a new station by sending the information to the server
* @param {Object} station Station object
*/
async doFavor(station) {
if (this.isFavorite(station)) {
this.$store.dispatch('removeFavorite', station)
} else {
this.$store.dispatch('addFavorite', station)
}
},
/**
* Start playing a radio station and counting the playback
* @param {Object} station Station object
*/
async doPlay(station) {
const vm = this
vm.$store.dispatch('isBuffering', true)
if (audioPlayer !== null) {
audioPlayer.fade(vm.player.volume, 0, 500)
}
vm.$store.dispatch('setTitle', station.name)
let stationSrc = ''
if (!station.url_resolved) {
stationSrc = station.urlresolved
} else {
stationSrc = station.url_resolved
}
Howler.unload()
audioPlayer = new Howl({
src: stationSrc,
html5: true,
volume: vm.player.volume,
onplay() {
vm.$store.dispatch('isPlaying', true)
vm.$store.dispatch('isBuffering', false)
},
onpause() {
vm.$store.dispatch('isPlaying', false)
vm.$store.dispatch('isBuffering', false)
},
onend() {
showError(t('radio', 'Lost connection to radio station, retrying ...'))
vm.$store.dispatch('isPlaying', false)
vm.$store.dispatch('isBuffering', true)
},
})
audioPlayer.unload()
audioPlayer.play()
audioPlayer.fade(0, vm.player.volume, 500)
/* Count click */
apiClient.countClick(station)
/* Put into recent stations */
this.$store.dispatch('addRecent', station)
},
async loadStations(menuState = 'TOP') {
// Skip loading more stations on certain sites
if (this.tableData.length > 0
&& (this.$route.name === 'FAVORITES'
|| this.$route.name === 'RECENT'
|| this.$route.name === 'CATEGORIES')) {
return true
}
if (menuState === 'FAVORITES' || menuState === 'RECENT') {
this.pageLoading = false
} else if (menuState === 'SEARCH') {
const stations = await apiClient.searchStations(this.$route.params.query, this.tableData.length)
this.tableData = this.tableData.concat(stations)
this.pageLoading = false
} else if (menuState === 'NEW' || menuState === 'TOP') {
const stations = await apiClient.queryList(menuState, this.tableData.length)
this.tableData = this.tableData.concat(stations)
this.pageLoading = false
}
/* if (this.$route.name === 'CATEGORIES') {
if (this.$route.path === '/categories') {
this.tableData = [
{
name: t('radio', 'Countries'),
type: 'folder',
path: '/categories/countries',
},
{
name: t('radio', 'States'),
type: 'folder',
path: '/categories/states',
},
{
name: t('radio', 'Languages'),
type: 'folder',
path: '/categories/languages',
},
{
name: t('radio', 'Tags'),
type: 'folder',
path: '/categories/tags',
},
]
this.pageLoading = false
return true
} else if (this.$route.params.category === 'tags') {
if (this.$route.params.query) {
queryURI = this.$apiUrl + '/json/stations/search?tag=' + this.$route.params.query + '&tagExact=true'
} else {
queryURI = this.$apiUrl + '/json/tags'
}
} else if (this.$route.params.category === 'countries') {
if (this.$route.params.query) {
queryURI = this.$apiUrl + '/json/stations/search?country=' + this.$route.params.query + '&countryExact=true'
} else {
queryURI = this.$apiUrl + '/json/countries'
}
} else if (this.$route.params.category === 'states') {
if (this.$route.params.query) {
queryURI = this.$apiUrl + '/json/stations/search?state=' + this.$route.params.query + '&stateExact=true'
} else {
queryURI = this.$apiUrl + '/json/states'
}
} else if (this.$route.params.category === 'languages') {
if (this.$route.params.query) {
queryURI = this.$apiUrl + '/json/stations/search?language=' + this.$route.params.query + '&languageExact=true'
} else {
queryURI = this.$apiUrl + '/json/languages'
}
}
} */
/* try {
delete axios.defaults.headers.requesttoken
await axios.get(queryURI, {
params: vm.queryParams,
})
.then(function(response) {
for (let i = 0; i < response.data.length; i++) {
const obj = response.data[i]
if (obj.stationuuid) {
let blurHash = vm.blurHashes[obj.stationuuid]
if (!blurHash) {
blurHash = 'L1TSUA?bj[?b~qfQfQj[ayfQfQfQ'
}
response.data[i].blurHash = blurHash
} else {
response.data[i].type = 'folder'
response.data[i].path = vm.$route.path + '/' + obj.name
}
}
vm.tableData = vm.tableData.concat(response.data)
vm.pageLoading = false
})
} catch (error) {
showError(t('radio', 'Could not fetch stations from remote API'))
} */
},
/**
* On scroll event, load more stations if bottom reached
*/
scroll() {
window.onscroll = () => {
if ((window.innerHeight + window.scrollY) >= document.body.scrollHeight) {
const route = this.$route
this.loadStations(route.name)
}
}
},
toggleSidebar(station = null) {
if (station) {
this.showSidebar = true
this.sidebarStation = station
} else {
this.showSidebar = false
}
},
},
}
</script>
<style>
@media only screen and (min-width: 1024px) {
.app-navigation-toggle {
display: none;
}
}
</style>