Cleaned up recentRooms logic and storage

This commit is contained in:
Travis Shivers 2020-05-24 19:31:33 -05:00
parent 65469a5786
commit be9acc2f29
4 changed files with 67 additions and 56 deletions

View File

@ -30,13 +30,13 @@
<v-flex <v-flex
xs12 xs12
class="nicelist pa-4" class="nicelist pa-4"
v-if="!context.getters.getConnected && recents && Object.keys(recents).length > 0" v-if="!context.getters.getConnected && this.recentRooms.length > 0"
style="color:white !important;" style="color:white !important;"
> >
<v-subheader>Recent Rooms</v-subheader> <v-subheader>Recent Rooms</v-subheader>
<v-list class="pa-0"> <v-list class="pa-0">
<template v-for="(item, index) in recentsSorted"> <template v-for="(item, index) in this.recentRooms.slice(0, 3)">
<v-list-tile :key="index" v-if="index < 5" avatar @click="recentConnect(item)"> <v-list-tile :key="index" avatar @click="recentConnect(item)">
<v-list-tile-avatar> <v-list-tile-avatar>
<img :src="logos.light.small" style="width: 32px; height: auto" /> <img :src="logos.light.small" style="width: 32px; height: auto" />
</v-list-tile-avatar> </v-list-tile-avatar>
@ -53,7 +53,7 @@
color="white" color="white"
dark dark
slot="activator" slot="activator"
@click.stop="removeHistoryItem(item)" @click.stop="REMOVE_RECENT_ROOM(item)"
>close</v-icon>Remove >close</v-icon>Remove
</v-tooltip> </v-tooltip>
</v-list-tile-action> </v-list-tile-action>
@ -211,7 +211,7 @@
import Vue from 'vue'; import Vue from 'vue';
import axios from 'axios'; import axios from 'axios';
import { mapGetters, mapMutations } from 'vuex'; import { mapGetters, mapMutations, mapActions } from 'vuex';
export default { export default {
props: ['object'], props: ['object'],
@ -251,21 +251,14 @@ export default {
if (this.slRoom && this.slConnected && this.slServer) { if (this.slRoom && this.slConnected && this.slServer) {
this.$router.push('/browse'); this.$router.push('/browse');
} }
this.getRecents();
}, },
methods: { methods: {
...mapMutations('settings', [ ...mapMutations('settings', [
'SET_CUSTOM_SERVER_USER_INPUTTED_URL' 'SET_CUSTOM_SERVER_USER_INPUTTED_URL'
]), ]),
getRecents() { ...mapActions('settings', [
this.recents = JSON.parse(window.localStorage.getItem('recentrooms')); 'REMOVE_RECENT_ROOM'
}, ]),
removeHistoryItem(item) {
const recents = JSON.parse(window.localStorage.getItem('recentrooms'));
delete recents[`${item.server}/${item.room}`];
window.localStorage.setItem('recentrooms', JSON.stringify(recents));
return this.getRecents();
},
connectionQualityClass(value) { connectionQualityClass(value) {
if (value < 50) { if (value < 50) {
return ['green--text', 'text--lighten-1']; return ['green--text', 'text--lighten-1'];
@ -419,7 +412,8 @@ export default {
computed: { computed: {
...mapGetters({ ...mapGetters({
'syncloungeServers': 'GET_SYNCLOUNGE_SERVERS', 'syncloungeServers': 'GET_SYNCLOUNGE_SERVERS',
'GET_CUSTOM_SERVER_USER_INPUTTED_URL': 'settings/GET_CUSTOM_SERVER_USER_INPUTTED_URL' 'GET_CUSTOM_SERVER_USER_INPUTTED_URL': 'settings/GET_CUSTOM_SERVER_USER_INPUTTED_URL',
'recentRooms': 'settings/GET_RECENT_ROOMS'
}), }),
plex() { plex() {
return this.$store.state.plex; return this.$store.state.plex;
@ -429,22 +423,10 @@ export default {
}, },
context() { context() {
return this.$store; return this.$store;
},
recentsSorted() {
if (!this.recents) {
return [];
}
let arr = [];
for (const i in this.recents) {
const item = this.recents[i];
arr.push(item);
}
arr = arr.sort((a, b) => b.time - a.time);
if (arr.length > 3) {
return arr.slice(0, 3);
}
return arr;
} }
},
mounted() {
console.log(this.recentRooms)
} }
}; };
</script> </script>

View File

@ -217,8 +217,6 @@ const actions = {
// Playing something different! // Playing something different!
const server = state.plex.servers[mediaContainer.machineIdentifier]; const server = state.plex.servers[mediaContainer.machineIdentifier];
commit('settings/SET_LASTSERVER', mediaContainer.machineIdentifier); commit('settings/SET_LASTSERVER', mediaContainer.machineIdentifier);
// state.settings.LASTSERVER = mediaContainer.machineIdentifier;
// window.localStorage.setItem('LASTSERVER', mediaContainer.machineIdentifier);
if (!server) { if (!server) {
return; return;
} }

View File

@ -26,6 +26,7 @@ const state = () => ({
CLIENTIDENTIFIER: `${generateGuid()}-${generateGuid()}`, CLIENTIDENTIFIER: `${generateGuid()}-${generateGuid()}`,
lastServer: null, lastServer: null,
plexAuthToken: null, plexAuthToken: null,
recentRooms: [],
}); });
// Use stored value if not null, othewise fallback to config, then default values // Use stored value if not null, othewise fallback to config, then default values
@ -78,6 +79,7 @@ const getters = {
GET_LASTSERVER: state => state.lastServer, GET_LASTSERVER: state => state.lastServer,
GET_CUSTOM_SERVER_USER_INPUTTED_URL: state => state.customServerUserInputtedUrl, GET_CUSTOM_SERVER_USER_INPUTTED_URL: state => state.customServerUserInputtedUrl,
GET_PLEX_AUTH_TOKEN: state => state.plexAuthToken, GET_PLEX_AUTH_TOKEN: state => state.plexAuthToken,
GET_RECENT_ROOMS: state => state.recentRooms,
}; };
const mutations = { const mutations = {
@ -94,6 +96,31 @@ const mutations = {
SET_LASTSERVER: (state, server) => (state.lastServer = server), SET_LASTSERVER: (state, server) => (state.lastServer = server),
SET_SLPLAYERVOLUME: (state, volume) => (state.slPlayerVolume = volume), SET_SLPLAYERVOLUME: (state, volume) => (state.slPlayerVolume = volume),
SET_PLEX_AUTH_TOKEN: (state, token) => (state.plexAuthToken = token), SET_PLEX_AUTH_TOKEN: (state, token) => (state.plexAuthToken = token),
SET_RECENT_ROOMS: (state, rooms) => (state.recentRooms = rooms),
};
const actions = {
ADD_RECENT_ROOM: ({ commit, getters }, newRoom) => {
console.log('first filter');
const lol = Array.of(newRoom).concat(getters.GET_RECENT_ROOMS.filter((room) => {
console.log(`${room.server} !== ${newRoom.server}: ${room.server !== newRoom.server}`);
console.log(`${room.room} !== ${newRoom.room}: ${room.room !== newRoom.room}`);
console.log(`${room.server !== newRoom.server && room.room !== newRoom.room}`);
return room.server !== newRoom.server || room.room !== newRoom.room;
}));
console.log('new rooms');
console.log(lol);
commit(
'SET_RECENT_ROOMS',
Array.of(newRoom).concat(getters.GET_RECENT_ROOMS.filter(room => room.server !== newRoom.server || room.room !== newRoom.room)),
);
},
REMOVE_RECENT_ROOM: ({ commit, getters }, roomToRemove) =>
commit(
'SET_RECENT_ROOMS',
getters.GET_RECENT_ROOMS.filter(room => room.server !== roomToRemove.server || room.room !== roomToRemove.room),
),
}; };
export default { export default {
@ -101,4 +128,5 @@ export default {
state, state,
mutations, mutations,
getters, getters,
actions,
}; };

View File

@ -1,6 +1,7 @@
import Vue from 'vue'; import Vue from 'vue';
import axios from 'axios'; import axios from 'axios';
import moment from 'moment'; import moment from 'moment';
const EventEmitter = require('events'); const EventEmitter = require('events');
function sendNotification(message) { function sendNotification(message) {
@ -82,7 +83,7 @@ export default {
actions: { actions: {
async autoJoin({ async autoJoin({
state, commit, rootState, dispatch state, commit, rootState, dispatch,
}, data) { }, data) {
await dispatch('socketConnect', { await dispatch('socketConnect', {
address: data.server, address: data.server,
@ -141,7 +142,9 @@ export default {
}); });
}); });
}, },
joinRoom({ state, commit, rootState, rootGetters }, data) { joinRoom({
state, commit, dispatch, rootState, rootGetters,
}, data) {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
if (!state._socket || !state.connected) { if (!state._socket || !state.connected) {
throw new Error('Not connected to a server!'); throw new Error('Not connected to a server!');
@ -155,7 +158,7 @@ export default {
let username = data.user.username; let username = data.user.username;
if (rootGetters['settings/GET_HIDEUSERNAME']) { if (rootGetters['settings/GET_HIDEUSERNAME']) {
username = rootGetters['settings/GET_ALTUSERNAME'] username = rootGetters['settings/GET_ALTUSERNAME'];
} }
state._socket.emit( state._socket.emit(
'join', 'join',
@ -174,22 +177,20 @@ export default {
sendNotification(`Joined room: ${_data.room}`); sendNotification(`Joined room: ${_data.room}`);
// Add this item to our recently-connected list // Add this item to our recently-connected list
let recents = window.localStorage.getItem('recentrooms'); dispatch(
if (!recents) { 'settings/ADD_RECENT_ROOM',
recents = {}; {
} else { server: state.server,
recents = JSON.parse(recents); room: state.room,
} password: state.password,
recents[`${state.server}/${state.room}`] = { time: new Date().getTime(),
server: state.server, },
room: state.room, { root: true },
password: state.password, );
time: new Date().getTime(),
};
window.localStorage.setItem('recentrooms', JSON.stringify(recents));
// Generate our short url/invite link // Generate our short url/invite link
let urlOrigin = window.location.origin + (rootGetters['config/GET_CONFIG'].webroot || ''); let urlOrigin =
window.location.origin + (rootGetters['config/GET_CONFIG'].webroot || '');
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
urlOrigin = 'http://app.synclounge.tv'; urlOrigin = 'http://app.synclounge.tv';
} }
@ -301,8 +302,9 @@ export default {
} }
// Check if we need to autoplay // Check if we need to autoplay
if ( if (
(ourTimeline.state === 'stopped' || !ourTimeline.state) && ((ourTimeline.state === 'stopped' || !ourTimeline.state) &&
hostTimeline.playerState !== 'stopped' || rootState.rawTitle !== hostTimeline.rawTitle hostTimeline.playerState !== 'stopped') ||
rootState.rawTitle !== hostTimeline.rawTitle
) { ) {
if (rootState.blockAutoPlay || !hostTimeline.rawTitle) { if (rootState.blockAutoPlay || !hostTimeline.rawTitle) {
return resolve(); return resolve();
@ -332,7 +334,9 @@ export default {
.catch(async (e) => { .catch(async (e) => {
const hostServer = rootState.plex.servers[hostTimeline.machineIdentifier]; const hostServer = rootState.plex.servers[hostTimeline.machineIdentifier];
if (hostServer && hostTimeline.key) { if (hostServer && hostTimeline.key) {
if (!rootGetters['settings/GET_BLOCKEDSERVERS'].includes(hostTimeline.machineIdentifier)) { if (
!rootGetters['settings/GET_BLOCKEDSERVERS'].includes(hostTimeline.machineIdentifier)
) {
try { try {
await rootState.chosenClient.playMedia({ await rootState.chosenClient.playMedia({
ratingKey: hostTimeline.key, ratingKey: hostTimeline.key,
@ -344,12 +348,12 @@ export default {
rootState.blockAutoPlay = false; rootState.blockAutoPlay = false;
}, 15000); }, 15000);
return resolve(); return resolve();
} catch (e) { } } catch (e) {}
} }
} }
sendNotification(`Failed to find a compatible copy of ${ sendNotification(`Failed to find a compatible copy of ${
hostTimeline.rawTitle hostTimeline.rawTitle
}. If you have access to the content try manually playing it.`); }. If you have access to the content try manually playing it.`);
setTimeout(() => { setTimeout(() => {
rootState.blockAutoPlay = false; rootState.blockAutoPlay = false;
}, 15000); }, 15000);
@ -541,6 +545,5 @@ export default {
}); });
} }
}, },
getServerList() { },
}, },
}; };