Skip to content

Commit

Permalink
🎨 Refactoring for mopidy connection
Browse files Browse the repository at this point in the history
  • Loading branch information
cristianpb committed Mar 2, 2024
1 parent 98475b4 commit 8b4e5f3
Show file tree
Hide file tree
Showing 8 changed files with 138 additions and 122 deletions.
5 changes: 1 addition & 4 deletions src/lib/components/AddToPlaylist.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
<script>
import { onMount } from 'svelte';
import { mopidy, playlists } from '../tools/stores';
import { connectWS, getPlaylists, getPlaylistTracks } from '../tools/mopidyTools';
import { getPlaylists, getPlaylistTracks } from '../tools/mopidyTools';
import FontAwesomeIcon from '../components/FontAwesomeIcon.svelte'
import {
faPlus,
Expand All @@ -79,9 +79,6 @@
let savePlaylistPromise
onMount(async () => {
// $mopidy = await connectWS()
const message = await connectWS()
console.log("in playlist", message);
$playlists = await getPlaylists()
})
Expand Down
7 changes: 1 addition & 6 deletions src/lib/components/CreatePlaylist.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,8 @@
</div>

<script>
import { onMount } from 'svelte';
import { mopidy, playlists } from '../tools/stores';
import { connectWS, getPlaylists } from '../tools/mopidyTools';
import { getPlaylists } from '../tools/mopidyTools';
import FontAwesomeIcon from '../components/FontAwesomeIcon.svelte'
import {
faCheck,
Expand All @@ -51,10 +50,6 @@
export let showCreatePlaylistModal;
onMount(() => {
connectWS()
})
const createPlaylist = async () => {
const res = await $mopidy.playlists.create({name: playlistName})
if (res) {
Expand Down
28 changes: 3 additions & 25 deletions src/lib/components/NavBottom.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,6 @@
</nav>

<script>
import { onMount } from 'svelte';
import { slide } from 'svelte/transition';
import FontAwesomeIcon from './FontAwesomeIcon.svelte'
import {
Expand All @@ -322,34 +321,13 @@
faRedo,
faRecycle
} from '@fortawesome/free-solid-svg-icons';
import { snapGroups, snapClientsVisibility, snapClientsEditVisibility, currentTrack, currentPlaytime, totalPlaytime, currentState, currentVolume, currentMute, mopidy, currentRandom, currentConsume, currentRepeat, currentSingle, mopidyHost, mopidyPort, mopidySSL, snapcastHost, snapcastPort, snapcastSSL } from '../tools/stores';
import { convertSencondsToString, normalizeTime, setTrackTime, connectWS } from '../tools/mopidyTools';
import { connectSnapcast, changeHandler, muteClient } from '../tools/snapcast';
import { snapGroups, snapClientsVisibility, snapClientsEditVisibility, currentTrack, currentPlaytime, totalPlaytime, currentState, currentVolume, currentMute, mopidy, currentRandom, currentConsume, currentRepeat, currentSingle } from '../tools/stores';
import { convertSencondsToString, normalizeTime, setTrackTime } from '../tools/mopidyTools';
import { changeHandler, muteClient } from '../tools/snapcast';
let config;
let burgerState = false;
$: currentPlaytimePercent = normalizeTime($currentPlaytime, $totalPlaytime)
onMount(async () => {
const res = await fetch('/muse/config')
if (res.status === 200) {
config = await res.json()
}
$mopidyHost = config && config.mopidy && config.mopidy.host ? config.mopidy.host : $mopidyHost ? $mopidyHost : window.location.hostname;
$mopidyPort = config && config.mopidy && config.mopidy.port ? config.mopidy.port : $mopidyPort ? $mopidyPort : window.location.port;
$mopidySSL = config && config.mopidy && config.mopidy.ssl ? Boolean(config.mopidy.ssl).toString() : $mopidySSL ? $mopidySSL : window.location.protocol === 'https:' ? 'true' : 'false';
$snapcastHost = config && config.snapcast && config.snapcast.host ? config.snapcast.host : $snapcastHost ? $snapcastHost : window.location.hostname;
$snapcastPort = config && config.snapcast && config.snapcast.port ? config.snapcast.port : $snapcastPort ? $snapcastPort : 1780;
$snapcastSSL = config && config.snapcast && config.snapcast.ssl ? Boolean(config.snapcast.ssl).toString() : $snapcastSSL ? $snapcastSSL : window.location.protocol === 'https:' ? 'true' : 'false';
// $mopidy = await connectWS()
const message = await connectWS()
console.log("in navbottom", message);
try {
await connectSnapcast()
} catch(e) {
console.log('[Snapcast]: catch error:', e);
}
})
const togglePlayPause = (state) => {
if (state === 'playing') {
Expand Down
137 changes: 89 additions & 48 deletions src/lib/tools/mopidyTools.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,8 @@ let currentPlaytimeLocal;
let totalPlaytimeLocal;
let interval;
let connecting = false;
let config;

mopidy.subscribe((value) => {
mopidyWS = value;
});
mopidyHost.subscribe((value) => {
mopidyHostLocal = value;
});
Expand Down Expand Up @@ -64,23 +62,13 @@ export function convertPercentToSeconds(percent, total) {
return ~~((total * percent) / 100);
}

let promiseConnecting;

const connectingFunction = () => {
const connectingFunction = (host, port, ssl) => {
return new Promise((resolve, reject) => {
connecting = true;
const host = mopidyHostLocal ? mopidyHostLocal : window.location.hostname;
const port = mopidyPortLocal ? mopidyPortLocal : window.location.port;
const protocol = mopidySSLLocal
? mopidySSLLocal
: window.location.protocol === "https:"
? "true"
: "false";
mopidyWS = new Mopidy({
webSocketUrl: `ws${protocol === "true" ? "s" : ""}://${host}:${port}/mopidy/ws/`,
webSocketUrl: `ws${ssl === "true" ? "s" : ""}://${host}:${port}/mopidy/ws/`,
});
mopidyWS.on("state:online", async () => {
console.log("[Mopidy]: Connected", mopidyWS);
console.log("[Mopidy]: Connected");

const currentTrackTL = await upgradeCurrentTrack();
currentPlaytimeLocal = await mopidyWS.playback.getTimePosition();
Expand Down Expand Up @@ -120,7 +108,6 @@ const connectingFunction = () => {
connecting = false;
mopidy.set(mopidyWS);
resolve("Connected");
//resolve(mopidyWS);
});

mopidyWS.on("state", (x) => console.log("[Mopidy]:", x));
Expand Down Expand Up @@ -202,31 +189,55 @@ const connectingFunction = () => {
});
};

export function connectWS(reconnect) {
// return new Promise(function(resolve, reject) {
if (mopidyWS && !reconnect) {
if (connecting) {
console.log("connecting", promiseConnecting);
// resolve('Connecting')
return promiseConnecting;
// console.log('[Mopidy]: Waiting for connection');
//setTimeout(() => {
// console.log('[Mopidy]: Already connected');
// resolve(mopidyWS)
//}, 1000)
} else {
// resolve('Connected')
console.log("already connected");
return promiseConnecting;
// resolve('Connected')
//resolve(mopidyWS)
const get_config = async () => {
const res = await fetch("/muse/config");
if (res.status === 200) {
config = await res.json();
}
};

export const connectWS = async (reconnect) => {
if (connecting) {
while (connecting) {
console.log("[Mopidy]: already connecting");
await new Promise((r) => setTimeout(r, 200));
}
return "[Mopidy]: finish waiting connection";
} else {
promiseConnecting = connectingFunction();
return promiseConnecting;
if (mopidyWS === undefined || reconnect) {
connecting = true;
console.log("[Mopidy]: try to connect");
await get_config();
const host =
config && config.mopidy && config.mopidy.host
? config.mopidy.host
: mopidyHostLocal
? mopidyHostLocal
: document.defaultView.location.hostname;
const port =
config && config.mopidy && config.mopidy.port
? config.mopidy.port
: mopidyPortLocal
? mopidyPortLocal
: document.defaultView.location.port;
const ssl =
config && config.mopidy && config.mopidy.ssl
? Boolean(config.mopidy.ssl).toString()
: mopidySSLLocal
? mopidySSLLocal
: document.defaultView.location.protocol === "https:"
? "true"
: "false";
mopidyHost.set(host);
mopidyPort.set(port);
mopidySSL.set(ssl);
await connectingFunction(host, port, ssl);
return "[Mopidy]: first connection connected";
} else {
return "[Mopidy]: already connected";
}
}
// });
}
};

export const upgradeCurrentTrack = async () => {
const currentTrackTL = await mopidyWS.playback.getCurrentTlTrack();
Expand All @@ -242,10 +253,40 @@ export const upgradeCurrentTrack = async () => {
}
};

export const loadUris = async () => {
await connectWS();
return await mopidyWS.library.browse({ uri: null });
};

export const loadUrisResults = async (selectedUris, hideUris) => {
await connectWS();
const urisResult = await mopidyWS.getUriSchemes();
if (urisResult) {
const uris = urisResult.filter((x) => hideUris.indexOf(x) === -1);
uris.forEach((uri) => (selectedUris[uri] = true));
return uris;
}
};

export const searchFunction = async (selectedUris, searchTerm) => {
const urisRequest = Object.entries(selectedUris)
.filter((x) => x[1])
.map((x) => `${x[0]}:`);
const res = await mopidyWS.library.search({
query: { any: [searchTerm] },
uris: [`${urisRequest}`],
});
if (res && res.length > 0) {
let { tracks } = res.pop();
if (tracks) {
return tracks;
}
}
return [];
};

export async function getPlaylists() {
// mopidyWS = await connectWS()
const message = await connectWS();
console.log("getting playlists", message);
await connectWS();
const playlistsRaw = await mopidyWS.playlists.asList();
playlistsLocal = playlistsRaw.map((playlistRaw) => {
playlistRaw.slug = playlistRaw.name;
Expand Down Expand Up @@ -273,9 +314,7 @@ export async function getCurrentTrackList() {
}

export async function getCurrentTlTrackList() {
// mopidyWS = await connectWS()
const message = await connectWS();
console.log("get curren tracklist", message);
await connectWS();
const currentTrackList = await mopidyWS.tracklist.getTlTracks();
if (currentTrackList) {
return currentTrackList;
Expand Down Expand Up @@ -370,11 +409,13 @@ export const loadAlbumImage = async (track) => {
console.log("[Mopidy]: Searching images for ", track.uri);
const trackImages = await mopidyWS.library.getImages({ uris: [track.uri] });
if (Object.values(trackImages)[0].length > 0) {
return Object.values(trackImages)[0].find((x) => x.__model__ == "Image")
.uri;
const image = Object.values(trackImages)[0].find(
(x) => x.__model__ == "Image",
).uri;
return image;
} else if (track && track.album) {
const res = await fetch(
`https://ws.audioscrobbler.com/2.0/?format=json&method=album.getInfo&album=${track.album.name}&artist=${track.artists[0].name}&api_key=12bbc4850d7cb77e2842f0a2f7bcc2e3`,
`https://ws.audioscrobbler.com/2.0/?format=json&method=album.getInfo&album=${track.album.name.replace(/[^\w\s]/gi, "")}&artist=${track.artists[0].name.replace(/[^\w\s]/gi, "")}&api_key=12bbc4850d7cb77e2842f0a2f7bcc2e3&&autocorrect=1`,
);
const lastfm = await res.json();
console.log("[Lastfm]: Result information", lastfm);
Expand Down
21 changes: 21 additions & 0 deletions src/routes/+layout.svelte
Original file line number Diff line number Diff line change
@@ -1,10 +1,31 @@
<script>
import { onMount } from 'svelte';
import Nav from './Nav.svelte';
import NavBottom from '../lib/components/NavBottom.svelte';
import SnapClients from '../lib/components/SnapClients.svelte';
import { snapcastHost, snapcastPort, snapcastSSL } from '../lib/tools/stores';
import { connectSnapcast } from '../lib/tools/snapcast';
import { connectWS } from '../lib/tools/mopidyTools';
import '../global.css';
export let segment;
let config;
onMount(async () => {
connectWS()
const res = await fetch('/muse/config')
if (res.status === 200) {
config = await res.json()
}
$snapcastHost = config && config.snapcast && config.snapcast.host ? config.snapcast.host : $snapcastHost ? $snapcastHost : document.defaultView.location.hostname;
$snapcastPort = config && config.snapcast && config.snapcast.port ? config.snapcast.port : $snapcastPort ? $snapcastPort : 1780;
$snapcastSSL = config && config.snapcast && config.snapcast.ssl ? Boolean(config.snapcast.ssl).toString() : $snapcastSSL ? $snapcastSSL : document.defaultView.location.protocol === 'https:' ? 'true' : 'false';
try {
await connectSnapcast()
} catch(e) {
console.log('[Snapcast]: catch error:', e);
}
})
</script>

<style>
Expand Down
9 changes: 2 additions & 7 deletions src/routes/browse/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@
import { onMount } from 'svelte';
import { mopidy } from '../../lib/tools/stores';
import { clickOutside } from '../../lib/tools/clickOutside';
import { connectWS, playTrackSingle, addTrackNext, addTrackQueue, addTracksQueue, shufflePlayAllTracks, playAllTracks } from '../../lib/tools/mopidyTools';
import { loadUris, playTrackSingle, addTrackNext, addTrackQueue, addTracksQueue, shufflePlayAllTracks, playAllTracks } from '../../lib/tools/mopidyTools';
import FontAwesomeIcon from '../../lib/components/FontAwesomeIcon.svelte';
import {
faSpinner,
Expand All @@ -152,14 +152,9 @@
let mopidyConnectionStatus;
onMount(async () => {
promise = loadUris()
results = await loadUris()
})
const loadUris = async () => {
mopidyConnectionStatus = await connectWS()
results = await $mopidy.library.browse({uri: null})
}
const browserUri = async (result, idx, location) => {
if (['directory', 'artist', 'album', 'playlist'].indexOf(result.type) > -1) {
options = null
Expand Down
19 changes: 13 additions & 6 deletions src/routes/playlists/[slug]/+page.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// import { mopidy, playlists } from '../../../lib/tools/stores';
// import { playlists } from '../../../lib/tools/stores';
import { error } from "@sveltejs/kit";
import {
getPlaylists,
Expand All @@ -8,11 +8,18 @@ import {
const loadTracks = async (slug) => {
const playlists = await getPlaylists();
const selectedPlaylist = playlists.find((playlist) => playlist.name === slug);
const playlistsTracks = await getPlaylistTracks(selectedPlaylist.uri);
return {
playlistsTracks,
selectedPlaylist,
};
if (selectedPlaylist) {
const playlistsTracks = await getPlaylistTracks(selectedPlaylist.uri);
return {
playlistsTracks,
selectedPlaylist,
};
} else {
return {
playlistsTracks: [],
selectedPlaylist: "",
};
}
};

/** @type {import('./$types').PageLoad} */
Expand Down
Loading

0 comments on commit 8b4e5f3

Please sign in to comment.