diff --git a/.github/ISSUE_TEMPLATE/i-have-an-idea-.md b/.github/ISSUE_TEMPLATE/i-have-an-idea-.md new file mode 100644 index 0000000..61c57e2 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/i-have-an-idea-.md @@ -0,0 +1,20 @@ +--- +name: I have an idea! +about: Suggest an idea for this project +title: '' +labels: enhancement +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/ISSUE_TEMPLATE/something-isn-t-working-.md b/.github/ISSUE_TEMPLATE/something-isn-t-working-.md new file mode 100644 index 0000000..9e2e026 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/something-isn-t-working-.md @@ -0,0 +1,31 @@ +--- +name: Something isn't working! +about: Create a report to help me fix issues +title: '' +labels: bug +assignees: '' + +--- + +**Preamble** +[ ] I have checked previous open and closed issues and didn't find any help +[ ] I agree to follow the [code of conduct](https://www.contributor-covenant.org/version/2/1/code_of_conduct/) + +**Cider Version used** +e.g. 2.5.0 + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Additional context** +Add any other context about the problem here. diff --git a/.gitignore b/.gitignore index 470d402..ccd8dd1 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,4 @@ CiderWSPlaying.json +.vscode/settings.json +.history/ +exampleData.jsonc diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..ffb518d --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +conduct@finnley.dev. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/README.md b/README.md index 6005755..41509d8 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,33 @@ +
+ + # 🎵 Cider 4 OBS 🔴 ### Connect your Cider Client to OBS and show what you're listening to! +![Apple Music](https://img.shields.io/badge/Apple_Music-9933CC?style=for-the-badge&logo=apple-music&logoColor=white) +![JavaScript](https://img.shields.io/badge/javascript-%23323330.svg?style=for-the-badge&logo=javascript&logoColor=%23F7DF1E) +![Socket.io](https://img.shields.io/badge/Socket.io-black?style=for-the-badge&logo=socket.io&badgeColor=010101) +![GitHub Pages](https://img.shields.io/badge/github%20pages-121013?style=for-the-badge&logo=github&logoColor=white) + + +#### This project is NOT dormant, I'm always open for suggestions and issues! :) + +
+ ## ❗ Requirements * [Open Broadcaster Software](https://obsproject.com/) -* [Cider 2.3+](https://cider.sh) +* [Cider Version 3+](https://cider.sh) * An Apple Music subscription (duh) ## 🛠 Setup -1. Setup Cider if you haven't done so already and open the settings. Go to "Connectivity" and scroll down all the way. Enable the Switch "WebSockets API". -2. Create a new Browser Source in OBS and set the URL to [`https://ryzetech.github.io/cider4obs/`](https://ryzetech.github.io/cider4obs/). -3. The source will spawn with a width of `800` by default. Resize it if necessary (my personal sweet spot is `400`) and change the height to `170` or something like that. -4. The browser in OBS will now attempt to connect to Cider every five seconds and reestablish the connection if necessary! +1. Setup Cider if you haven't done so already and open the settings. Go to **Connectivity** and scroll down all the way. Enable the **WebSockets API** switch. This isn't technically needed anymore, but it's good to have it enabled nevertheless. +2. Create a new **Browser Source** in OBS and set the URL to [`https://ryzetech.github.io/cider4obs/`](https://ryzetech.github.io/cider4obs/). +3. The source will spawn with a default width of `800`. Resize it if necessary (recommended: `400` width) and set the height to approximately `170`. +4. The browser will automatically attempt to connect to Cider and reestablish the connection if needed! +5. To customize appearance and behavior, see the customization section below. Add your custom CSS to the **Custom CSS** box in the OBS browser source settings! ## 🎨 Customization & Settings -Unhappy with the way the app looks and behaves by default? You can change the settings with the "Custom CSS" box in the OBS browser source. I have compiled some **examples** below to just copy and change to your liking. +Not happy with the default appearance and behavior? You can customize everything using the **Custom CSS** box in the OBS browser source settings. Here are some examples to copy and modify: To pick colors, I recommend https://rgbacolorpicker.com/. @@ -29,7 +43,7 @@ To pick colors, I recommend https://rgbacolorpicker.com/. ``` ### Text Customization -Customizable elements are `span, #title, #artist, #album` +Customizable elements are `span, .track-title, .track-artist, .track-album` ```css /* to change the text color, do */ span { @@ -38,19 +52,24 @@ span { } /* to make the title look neutral instead of bold, do: */ -#title { +.track-title { font-weight: normal; } /* similar with the album name (pay attention to the attribute!) */ -#album { +.track-album { font-style: normal; } /* you can even hide elements: */ -#album { +.track-album { display: none; } + +/* or target by ID if you prefer: */ +#title, #artist, #album { + /* your styles here */ +} ``` @@ -73,28 +92,99 @@ Customizable elements are `#progressBg, #progressBar`. } ``` -### Settings -Some settings adjusting the behavior of certain elements. +## ⚙️ Configuration Options + +You can control the behavior of the Cider4OBS overlay using CSS custom properties. Add these to the `body` selector in the OBS browser source's Custom CSS box: + ```css body { - /* general key: 1=on, 0=off */ - - /* fade the box in and out depending on whether music is playing or not */ - --fade-on-stop: 1; + /* Fade the box in/out when music is paused or stopped */ + --fade-on-stop: 1; /* 1 = enabled, 0 = disabled */ + + /* Fade the box in/out when Cider disconnects */ + --fade-on-disconnect: 1; /* 1 = enabled, 0 = disabled */ + + /* Delay (ms) before fading out after pausing/stopping */ + --fade-delay: 2000; /* Default: 2000ms */ + + /* Delay (ms) before fading out after disconnecting */ + --fade-disconnect-delay: 2000; /* Default: 2000ms, falls back to --fade-delay if not set */ + + /* Hide the box when connected but Cider is idle */ + --hide-on-idle-connect: 1; /* 1 = enabled, 0 = disabled */ - /* how long playback must be paused until the box fades (if enabled) */ + /* Hide the box unless music is playing */ + --hide-unless-playing: 1; /* 1 = enabled, 0 = disabled */ +} +``` + +**Tip:** You can combine these options to customize exactly when the overlay appears or fades out. For example, to only show the overlay when music is playing and fade out quickly when paused: + +```css +body { + --fade-on-stop: 1; --fade-delay: 1000; + --hide-unless-playing: 1; } ``` +### [NEW] Additional Display Options + +- `--show-time-labels`: Set to `inline-block` to show current playback time and song duration on either end of the progress bar. Default: `none` (hidden) + ```css + #overlay { + --show-time-labels: inline-block; + } + ``` + +- `--show-next-in-queue`: Set to `block` to show a box with the next song in queue that fades/slides in before the current song ends. Default: `none` (hidden) + ```css + #overlay { + --show-next-in-queue: block; + } + ``` + +- `--next-in-queue-reveal-time`: Number of seconds before the current song ends to reveal the next-in-queue box. Default: `10` + ```css + #overlay { + --next-in-queue-reveal-time: 15; + } + ``` + +- `--next-in-queue-slide-direction`: Direction from which the next-in-queue box slides in. Options: `top`, `bottom`, `left`, `right`, or `none` to disable slide animation. Default: `top` + ```css + #overlay { + --next-in-queue-slide-direction: left; + } + ``` + ## 💜 Trusted by streamers -Thank you for supporting this project with links and by word-of-mouth! You are my heroes! +Thank you for supporting this project by using and spreading it! You are my heroes! + +
-| [ 🥇 iamtheratio](https://www.twitch.tv/iamtheratio) | -|:-----------------------------------------------------------------------------------------:| +| [ 🥇 iamtheratio](https://www.twitch.tv/amtheratio) | +|:-:| | [![iamtheratio](https://zip.finnley.dev/r/DErk2u.png)](https://www.twitch.tv/iamtheratio) | +
+ Do you want to appear here? Open a new issue and outline your involvement. I'll be happy to add you here! +## ❤ Special Thanks +A list of entities I want to thank for supporting me in different ways! + +
+ +| [![logo](https://avatars.githubusercontent.com/u/87914859?s=70)
Cider Collective](https://github.com/ciderapp/) | +| :-: | +| Thank you so much for giving me access to early builds,
making change response much faster! | + +| [![logo](https://static-cdn.jtvnw.net/jtv_user_pictures/245fe4a9-fc34-411f-8db8-c27728ca6e7e-profile_image-70x70.png)
Aquasius](https://www.twitch.tv/aquasius) | +| :-: | +| Thanks for the original idea, initial feedback,
and the driving force to make this open source! | +
+ ## Issues, Ideas, Comments? -Tell me in the issues tab! <3 \ No newline at end of file +Tell me in the issues tab! <3 +Don't have a GitHub account? Feel free to contact me on [Discord](https://discord.com/users/373135347791560706), [Telegram](https://t.me/finnleyfox), or via [Mail](mailto:cider4obs@finnley.dev) diff --git a/c4obs.png b/c4obs.png new file mode 100644 index 0000000..193550c Binary files /dev/null and b/c4obs.png differ diff --git a/configurator.html b/configurator.html deleted file mode 100644 index 208f1f8..0000000 --- a/configurator.html +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - Cider4OBS Configurator - - - - -
-
- -
- Cider4OBS Connector | Connecting...
- -/-
- -/- -
-
-
-
-
-
- -
- -

Configuration

- - -

- -
-
- - -
-
- - -

- - -
-
- -
- - - - \ No newline at end of file diff --git a/connector.js b/connector.js index abaa0f3..77eb181 100644 --- a/connector.js +++ b/connector.js @@ -1,93 +1,352 @@ +// Constants +const CIDER_SOCKET_URL = "http://localhost:10767/"; +const SETTINGS_LOAD_DELAY = 100; +const DEFAULT_FADE_DELAY = 2000; +const DEFAULT_QUEUE_REVEAL_TIME = 10; + +// Element IDs +const ELEMENTS = { + content: 'content', + title: 'title', + artist: 'artist', + album: 'album', + albumImg: 'albumimg', + progressBar: 'progressBar', + currentTime: 'currentTime', + duration: 'duration', + nextInQueue: 'nextInQueue', + nextQueueBox: 'nextQueueBox', + nextTitle: 'nextTitle', + nextArtist: 'nextArtist', + nextAlbumImg: 'nextAlbumImg' +}; + +// State let pauseTimer; +let disconnectTimer; let settings; +let elements = {}; +let currentTrackName = null; + +/** + * Cache DOM elements for better performance + */ +function cacheElements() { + Object.keys(ELEMENTS).forEach(key => { + elements[key] = document.getElementById(ELEMENTS[key]); + }); + + // Set slide direction attribute on nextQueueBox element + if (elements.nextQueueBox && settings) { + const direction = settings.next_in_queue_slide_direction; + if (['top', 'bottom', 'left', 'right'].includes(direction)) { + elements.nextQueueBox.setAttribute('data-slide', direction); + } + } +} -function getVarFromBody(name) { return window.getComputedStyle(document.body).getPropertyValue(name); } +/** + * Get CSS variable value from body + */ +function getCSSVariable(name) { + return window.getComputedStyle(document.body).getPropertyValue(name); +} +/** + * Parse settings from CSS variables + */ function getSettings() { return { - fade_on_stop: getVarFromBody('--fade-on-stop') == 1, - fade_delay: getVarFromBody('--fade-delay') || 2000, + fade_on_stop: getCSSVariable('--fade-on-stop') === '1', + fade_on_disconnect: getCSSVariable('--fade-on-disconnect') === '1', + fade_delay: parseInt(getCSSVariable('--fade-delay')) || DEFAULT_FADE_DELAY, + fade_disconnect_delay: parseInt(getCSSVariable('--fade-disconnect-delay')) || + parseInt(getCSSVariable('--fade-delay')) || DEFAULT_FADE_DELAY, + hide_on_idle_connect: getCSSVariable('--hide-on-idle-connect') === '1', + hide_unless_playing: getCSSVariable('--hide-unless-playing') === '1', + show_time_labels: getCSSVariable('--show-time-labels') === '1', + show_next_in_queue: getCSSVariable('--show-next-in-queue') === '1', + next_in_queue_reveal_time: parseInt(getCSSVariable('--next-in-queue-reveal-time')) || DEFAULT_QUEUE_REVEAL_TIME, + next_in_queue_slide_direction: getCSSVariable('--next-in-queue-slide-direction').trim() || 'top' + }; +} + +/** + * Format seconds to M:SS or H:MM:SS format + */ +function formatTime(seconds) { + if (!seconds || isNaN(seconds)) return '0:00'; + + const hours = Math.floor(seconds / 3600); + const minutes = Math.floor((seconds % 3600) / 60); + const secs = Math.floor(seconds % 60); + + if (hours > 0) { + return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`; + } + return `${minutes}:${secs.toString().padStart(2, '0')}`; +} + +/** + * Set element opacity with optional delay + */ +function setOpacity(element, value, delay = 0) { + if (delay > 0) { + return setTimeout(() => { + element.style.opacity = value; + }, delay); + } + element.style.opacity = value; + return null; +} + +/** + * Clear and reset timer + */ +function clearTimer(timer) { + if (timer) { + clearTimeout(timer); + } + return undefined; +} + +/** + * Update display components with track data + */ +function updateComponents(data) { + elements.title.innerText = data.name; + elements.artist.innerText = data.artistName; + elements.album.innerText = data.albumName; + + // Store current track name for queue matching + currentTrackName = data.name; + + const artworkUrl = data.artwork.url + .replace("{w}", data.artwork.width) + .replace("{h}", data.artwork.height); + elements.albumImg.src = artworkUrl; +} + +/** + * Fetch current now playing information from API + */ +async function fetchNowPlaying() { + try { + const response = await fetch(`${CIDER_SOCKET_URL}api/v1/playback/now-playing`); + const data = await response.json(); + + if (data.status === 'ok' && data.info) { + updateComponents(data.info); + return true; + } + return false; + } catch (error) { + console.debug('[DEBUG] [API] Failed to fetch now playing:', error); + return false; + } +} + +/** + * Fetch queue and update next in queue display + */ +async function fetchQueue() { + if (!settings.show_next_in_queue) return; + + try { + const response = await fetch(`${CIDER_SOCKET_URL}api/v1/playback/queue`); + const queue = await response.json(); + + if (Array.isArray(queue) && queue.length > 0 && currentTrackName) { + // Find the currently playing track by matching the track name + const currentIndex = queue.findIndex(track => + track.attributes && track.attributes.name === currentTrackName + ); + + // Get the next track after the currently playing one + if (currentIndex >= 0 && currentIndex < queue.length - 1) { + const nextTrack = queue[currentIndex + 1]; + if (nextTrack.attributes) { + updateNextInQueue(nextTrack.attributes); + // Don't show immediately, wait for time-based reveal + return; + } + } + } + + hideNextInQueue(); + } catch (error) { + console.debug('[DEBUG] [API] Failed to fetch queue:', error); + hideNextInQueue(); + } +} + +/** + * Update next in queue display + */ +function updateNextInQueue(data) { + elements.nextTitle.innerText = data.name; + elements.nextArtist.innerText = data.artistName; + + const artworkUrl = data.artwork.url + .replace("{w}", data.artwork.width) + .replace("{h}", data.artwork.height); + elements.nextAlbumImg.src = artworkUrl; +} + +/** + * Hide next in queue display + */ +function hideNextInQueue() { + elements.nextInQueue.classList.remove('visible'); +} + +/** + * Check if next in queue should be revealed based on time remaining + */ +function checkQueueReveal(currentTime, duration) { + if (!settings.show_next_in_queue) return; + + const timeRemaining = duration - currentTime; + const shouldReveal = timeRemaining <= settings.next_in_queue_reveal_time && timeRemaining > 0.5; + + if (shouldReveal && elements.nextTitle.innerText !== '-') { + elements.nextInQueue.classList.add('visible'); + } else { + elements.nextInQueue.classList.remove('visible'); + } +} + +/** + * Handle playback state changes + */ +function handlePlaybackStateChange(state) { + if (state === "paused" && !pauseTimer && (settings.fade_on_stop || settings.hide_unless_playing)) { + pauseTimer = setOpacity(elements.content, 0, settings.fade_delay); + } else if (state === "playing") { + pauseTimer = clearTimer(pauseTimer); + elements.content.style.opacity = 1; + } +} + +/** + * Handle connection state + */ +async function handleConnect() { + console.debug('[DEBUG] [Init] Socket.io connection established!'); + + // Try to fetch current track information + const hasTrack = await fetchNowPlaying(); + + // Fetch queue if enabled + if (settings.show_next_in_queue) { + await fetchQueue(); + } + + if (!hasTrack) { + elements.title.innerText = "Cider4OBS Connector | Connection established!"; + elements.artist.innerText = "Start playing something!"; + elements.album.innerText = "-/-"; + } + + if (settings.hide_on_idle_connect || settings.hide_unless_playing) { + elements.content.style.opacity = 0; + } else { + elements.content.style.opacity = 1; + } + + if (disconnectTimer) { + disconnectTimer = clearTimer(disconnectTimer); + if (!settings.hide_unless_playing) { + elements.content.style.opacity = 1; + } } } +/** + * Handle disconnection state + */ +function handleDisconnect() { + elements.title.innerText = "Cider4OBS Connector | Disconnected! Retrying..."; + elements.artist.innerText = "-/-"; + elements.album.innerText = "-/-"; + elements.albumImg.src = "c4obs.png"; + console.debug('[DEBUG] [Init] Socket.io connection closed!'); + console.debug("[DEBUG] [Init] Retrying automatically..."); + + if (settings.hide_unless_playing) { + elements.content.style.opacity = 0; + } else if (!disconnectTimer && settings.fade_on_disconnect) { + disconnectTimer = setOpacity(elements.content, 0, settings.fade_disconnect_delay); + } +} + +/** + * Handle playback API events + */ +function handlePlaybackEvent({ data, type }) { + switch (type) { + case "playbackStatus.playbackStateDidChange": + handlePlaybackStateChange(data.state); + updateComponents(data.attributes); + break; + + case "playbackStatus.nowPlayingItemDidChange": + updateComponents(data); + if (settings.show_next_in_queue) { + fetchQueue(); + } + break; + + case "playbackStatus.playbackTimeDidChange": + elements.progressBar.style.width = + `${(data.currentPlaybackTime / data.currentPlaybackDuration) * 100}%`; + + if (settings.show_time_labels) { + elements.currentTime.innerText = formatTime(data.currentPlaybackTime); + elements.duration.innerText = formatTime(data.currentPlaybackDuration); + } + + // Check if next in queue should be revealed + checkQueueReveal(data.currentPlaybackTime, data.currentPlaybackDuration); + break; + + default: + console.debug(type, data); + } +} + +/** + * Initialize WebSocket connection + */ function startWebSocket() { try { - // pausing so obs has time to inject the css - // why does this work lmao + // Pause to allow OBS to inject CSS setTimeout(() => { settings = getSettings(); - }, 100); + cacheElements(); + + // Set initial state + if (settings.hide_unless_playing) { + elements.content.style.opacity = 0; + } + }, SETTINGS_LOAD_DELAY); - // Connect to the websocket server console.debug('[DEBUG] [Init] Configuring websocket connection...'); - const CiderApp = new WebSocket('ws://localhost:10766/ws'); - window.app = CiderApp; - - CiderApp.addEventListener("open", (event) => { - console.debug('[DEBUG] [Init] Websocket connection established!'); - document.getElementById("title").innerText = "Cider4OBS Connector | Connection established!"; - document.getElementById("artist").innerText = "Start playing something!"; - document.getElementById("album").innerText = "-/-"; + const CiderApp = io(CIDER_SOCKET_URL, { + transports: ['websocket'] }); - // Set up websocket artwork/information handling - CiderApp.addEventListener("message", (event) => { - if (event.data !== undefined || event.data !== null) { - try { - let playbackInfo = JSON.parse(event.data); - - if (playbackInfo.data?.status !== undefined || playbackInfo.data?.artwork?.url !== undefined || playbackInfo.data?.name !== undefined) { - updateComponents(playbackInfo.data); - if (pauseTimer && playbackInfo.data?.isPlaying) { - clearTimeout(pauseTimer); - pauseTimer = undefined; - document.getElementById("content").style.opacity = 1; - } - - // console.debug(playbackInfo.data); - } else { - if (!playbackInfo.data?.isPlaying && !pauseTimer && settings.fade_on_stop) { - pauseTimer = setTimeout(() => { - document.getElementById("content").style.opacity = 0; - }, settings.fade_delay); - } - console.debug("[DEBUG] [WS] PlaybackInfo is undefined or null, skipping to avoid errors.") - console.debug(event) - } - } catch (error) { - console.debug('[DEBUG] [WS] Websocket parsing error:', error); - } - } else { - console.log("[DEBUG] [WS] Websocket message is undefined or null, skipping.") - } - }); - CiderApp.addEventListener("close", (event) => { - document.getElementById("title").innerText = "Cider4OBS Connector | Connection failed! Retrying..."; - document.getElementById("artist").innerText = "Are you sure Cider (version 2.3 and above) is running and you have WebSockets enabled? (Settings > Connectivity > WebSockets API)"; - document.getElementById("album").innerText = "-/-" - console.debug('[DEBUG] [Init] Websocket connection closed!'); - console.debug("[DEBUG] [Init] Retrying in 5 seconds...") - setTimeout(startWebSocket, 5000); - }); - CiderApp.addEventListener("error", (error) => { - console.debug('[DEBUG] [Init] Websocket error:', error); - console.debug("[DEBUG] [Init] Retrying in 5 seconds...") - setTimeout(startWebSocket, 5000); + CiderApp.on("connect", handleConnect); + CiderApp.on("API:Playback", handlePlaybackEvent); + CiderApp.on("disconnect", handleDisconnect); + CiderApp.on("connect_error", (error) => { + elements.albumImg.src = "c4obs.png"; + console.debug("[DEBUG] [Init] Connect Error: " + error); + console.debug("[DEBUG] [Init] Retrying automatically..."); }); + } catch (error) { console.debug('[DEBUG] [Init] Code error:', error); - console.debug("[DEBUG] [Init] Retrying in 5 seconds...") - setTimeout(startWebSocket, 1000); + console.debug("[DEBUG] [Init] Retrying automatically..."); } -} -function updateComponents(pb) { - document.getElementById("title").innerText = pb.name; - document.getElementById("artist").innerText = pb.artistName; - document.getElementById("album").innerText = pb.albumName; - document.getElementById("progressBar").style.width = (((pb.currentPlaybackTime / pb.durationInMillis) * 100000) + "%"); - let aw = pb.artwork; - let tmp = aw.url.replace("{w}", aw.width); - tmp = tmp.replace("{h}", aw.height); - // console.debug(tmp); - document.getElementById("albumimg").src = tmp; } \ No newline at end of file diff --git a/index.html b/index.html index ee6b411..41f897a 100644 --- a/index.html +++ b/index.html @@ -5,21 +5,51 @@ Cider4OBS + -
+
- -
- Cider4OBS Connector | Connecting...
- -/-
- -/- + Album artwork +
+ Cider4OBS Connector | Connecting... + -/- + -/-
-
-
+
+ 0:00 +
+
+
+ 0:00 +
+
+ +
+
+ Next track artwork +
+ Next in Queue + - + - +
diff --git a/style.css b/style.css index 50daf2d..89fd518 100644 --- a/style.css +++ b/style.css @@ -1,49 +1,139 @@ +/* Body and root container */ +body { + background-color: rgba(0, 0, 0, 0); + margin: 0; + overflow: hidden; +} + #content { width: 90%; - background-color: #55555555; + background-color: rgba(69, 69, 69, 0); border-radius: 5px; margin: 10px; padding: 10px; + opacity: 0; transition: opacity 1s; } +/* Layout */ #mainbox { display: flex; align-items: center; - justify-content: left; + justify-content: flex-start; } -h1, label, span { - font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; +.track-info { + padding-left: 10px; + display: flex; + flex-direction: column; + gap: 2px; } +/* Text styles */ span { text-overflow: ellipsis; - color:white; -} - -#albumimg { - border-radius: 5px; + font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; + color: white; + filter: drop-shadow(0px 0px 10px #000000); } -#title { +.track-title { font-weight: bold; } -#album { +.track-album { font-style: italic; } -#progressBg { +/* Album artwork */ +#albumimg { + border-radius: 5px; + filter: drop-shadow(0px 0px 10px #000000); +} + +/* Progress bar */ +#progressContainer { + display: flex; + align-items: center; + gap: 8px; margin-top: 10px; - width: 100%; - height: auto; +} + +#progressBg { + flex: 1; + height: 10px; border-radius: 5px; background-color: #55555555; + filter: drop-shadow(0px 0px 10px #000000); } #progressBar { border-radius: 5px; - height: 10px; + height: 100%; background-color: #70e000; + transition: width 0.25s linear; +} + +.time-label { + font-size: 0.85em; + min-width: 40px; + text-align: center; + display: var(--show-time-labels, none); +} + +/* Next in Queue */ +#nextInQueue { + width: 90%; + margin: 0 10px; + max-height: 0; + opacity: 0; + overflow: hidden; + transition: max-height 0.5s ease-out, opacity 0.5s ease-out, margin-top 0.5s ease-out; + display: var(--show-next-in-queue, none); +} + +#nextInQueue.visible { + max-height: 200px; + opacity: 1; + margin-top: 10px; +} + +#nextQueueBox { + background-color: rgba(69, 69, 69, 0); + margin-left: 15px; + border-radius: 5px; + padding: 10px; + display: flex; + align-items: center; + justify-content: flex-start; + transition: transform 0.5s ease-out; + transform: translate(0, 0); +} + +#nextInQueue:not(.visible) #nextQueueBox[data-slide="top"] { + transform: translateY(-20px); +} + +#nextInQueue:not(.visible) #nextQueueBox[data-slide="bottom"] { + transform: translateY(20px); +} + +#nextInQueue:not(.visible) #nextQueueBox[data-slide="left"] { + transform: translateX(-20px); +} + +#nextInQueue:not(.visible) #nextQueueBox[data-slide="right"] { + transform: translateX(20px); +} + +#nextAlbumImg { + border-radius: 5px; + filter: drop-shadow(0px 0px 10px #000000); +} + +.queue-label { + font-size: 0.75em; + opacity: 0.7; + text-transform: uppercase; + letter-spacing: 0.5px; } \ No newline at end of file