-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_info.js
177 lines (175 loc) · 9.48 KB
/
get_info.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import {
plexApiKey, plexServerUrl
}
from './apikey.js';
let realOffset = 0; // Initialize realOffset globally
let lastViewOffset = 0;
let lastTrackData = null;
let trackStartTime = 0;
let trackStartOffset = 0;
let trackDurationInSeconds = 0;
let intervalId; // Store the interval ID to clear it later
async function fetchNowPlaying() {
const url = `${plexServerUrl}/status/sessions?X-Plex-Token=${plexApiKey}`;
console.log(`Session URL: ${url}`); // Corrected logging
try {
const response = await fetch(url);
const text = await response.text();
console.log(text); // Log raw XML data for debugging
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(text, "application/xml");
const track = xmlDoc.querySelector('Track');
const player = xmlDoc.querySelector('Player'); // Get the Player element
if (track) {
const viewOffset = track.getAttribute('viewOffset');
const newViewOffset = parseInt(viewOffset, 10) || 0;
// Only reset realOffset if a new viewOffset is received
if (newViewOffset !== lastViewOffset) {
realOffset = newViewOffset / 1000; // Convert to seconds
lastViewOffset = newViewOffset;
console.log('Updated viewOffset:', realOffset);
// Clear the previous interval if it exists
if (intervalId) {
clearInterval(intervalId);
}
// Start a new interval to increment realOffset by 1 second every second
intervalId = setInterval(() => {
realOffset += 1;
console.log('realOffset incremented to:', realOffset);
}, 1000);
}
// Ensure that track duration is updated here
const trackDuration = track.getAttribute('duration'); // Duration in ms
if (trackDuration) {
trackDurationInSeconds = Math.floor(trackDuration / 1000); // Convert to seconds
console.log('Track duration updated:', trackDurationInSeconds);
}
// Handle the track and player data
const artist = track.getAttribute('originalTitle');
const albumArtist = track.getAttribute('grandparentTitle');
console.log('album artist: ', albumArtist)
const album = track.getAttribute('parentTitle');
const trackTitle = track.getAttribute('title');
const albumArt = `${plexServerUrl}/library/metadata/${track.getAttribute('parentRatingKey')}/thumb/${track.getAttribute('thumb').split('/').pop()}?X-Plex-Token=${plexApiKey}`;
const albumYear = track.getAttribute('parentYear');
const trackUrl = `${plexServerUrl}${track.getAttribute('key')}?X-Plex-Token=${plexApiKey}`;
const audioInfo = track.querySelector('Media > Part > Stream');
const audioBitDepth = audioInfo ? audioInfo.getAttribute('bitDepth') : 'Unknown';
const audioBitrate = audioInfo ? audioInfo.getAttribute('bitrate') : 'Unknown';
const samplingRate = audioInfo ? audioInfo.getAttribute('samplingRate') : 'Unknown';
const audioCodec = audioInfo ? audioInfo.getAttribute('codec') : 'Unknown';
const playerTitle = player ? player.getAttribute('title') : 'Unknown Player';
const AOTYartistSearchLink = `https://www.albumoftheyear.org/search/albums/?q=${encodeURIComponent(album)}`;
const lastFMartistSearchLink = `https://www.last.fm/search/albums?q=${encodeURIComponent(album)}`;
const discogsArtistLink = `https://www.discogs.com/search/?q=${encodeURIComponent(album)}&type=release`;
console.log(AOTYartistSearchLink);
console.log(lastFMartistSearchLink);
console.log(discogsArtistLink);
// Find the music-connections paragraph
const musicConnectionsParagraph = document.querySelector('#music-connections');
// Update the content of the paragraph with the search links and images
musicConnectionsParagraph.innerHTML = `
<a href="${AOTYartistSearchLink}" target="_blank"><img src="images/aoty.png" alt="AOTY" class="music-icon"/></a><a href="${lastFMartistSearchLink}" target="_blank"><img src="images/last.fm.png" alt="Last.fm" class="music-icon"/></a><a href="${discogsArtistLink}" target="_blank"><img src="images/discogs.png" alt="Discogs" class="music-icon"/></a>
`;
const currentTrackData = {
albumArtist, artist, album, trackTitle, albumArt, albumYear, trackDuration, trackUrl, audioBitDepth, audioBitrate, audioCodec, playerTitle
};
if (hasTrackChanged(currentTrackData)) {
trackStartTime = 0; // Reset on track change
trackStartOffset = 0;
document.querySelector('#track-title').textContent = trackTitle.slice(0, 40);
document.querySelector('#track-artist').textContent = artist;
document.querySelector('#album-title').textContent = album;
document.querySelector('#album-year').textContent = albumYear;
document.querySelector('#album-art').src = albumArt;
// this runs the function to get the album art dominant color
getDominantColor(albumArt);
const formattedSamplingRate = samplingRate !== 'Unknown' ? Math.floor(samplingRate / 1000) : 'Unknown';
const formattedAudioInfo = `${formattedSamplingRate}/${audioBitDepth}, ${audioBitrate}kbps ${audioCodec}`;
document.querySelector('#audio-info').textContent = `${formattedAudioInfo} playing on ${playerTitle}`;
document.title = `${trackTitle} - ${artist}`;
lastTrackData = currentTrackData;
}
}
else {
resetNowPlaying();
}
}
catch (error) {
console.error('Error fetching now playing data:', error);
resetNowPlaying();
}
}
// Function to log the remaining time and update the HTML
// Retrieve the saved track start time from localStorage
const savedTrackStartTime = localStorage.getItem('trackStartTime');
// Log the retrieved value (if it exists)
if (savedTrackStartTime) {
trackStartTime = parseInt(savedTrackStartTime); // Use saved value if it exists
console.log('Track start time retrieved from localStorage:', trackStartTime);
}
else {
trackStartTime = Date.now(); // If no saved value, use current time
localStorage.setItem('trackStartTime', trackStartTime); // Save it for later
console.log('Track start time set to current time:', trackStartTime);
}
// Function to log the remaining time and update the HTML
function progressTimer() {
console.log('realOffset is:', realOffset); // Log the current realOffset
console.log('Track duration is:', trackDurationInSeconds);
// If the track duration is valid and realOffset is available, update the display
if (trackDurationInSeconds > 0) {
// Calculate the elapsed time based on realOffset (in seconds)
const elapsedTime = Math.floor(realOffset); // Round to nearest second
// Convert elapsed time to MM:SS format
const elapsedMinutes = Math.floor(elapsedTime / 60);
const elapsedSeconds = elapsedTime % 60;
const formattedElapsedTime = `${elapsedMinutes}:${elapsedSeconds.toString().padStart(2, '0')}`;
// Convert total track duration to MM:SS format
const totalMinutes = Math.floor(trackDurationInSeconds / 60);
const totalSeconds = trackDurationInSeconds % 60;
const formattedTotalDuration = `${totalMinutes}:${totalSeconds.toString().padStart(2, '0')}`;
// Update the track-remaining span with the elapsed time and total track duration
const trackRemainingElement = document.querySelector('#track-remaining');
trackRemainingElement.textContent = `${formattedElapsedTime} / ${formattedTotalDuration}`;
// Calculate the progress as a percentage
const progressPercentage = (elapsedTime / trackDurationInSeconds) * 100;
// Update the progress bar width
const progressBar = document.querySelector('#progress-bar');
progressBar.style.width = `${progressPercentage}%`; // Update the width based on the progress percentage
}
else {
console.log('Track duration is not available');
}
}
function hasTrackChanged(currentTrackData) {
if (!lastTrackData) {
return true;
}
return Object.keys(currentTrackData).some(key => currentTrackData[key] !== lastTrackData[key]);
}
window.toggleFullscreen = function () {
if (document.fullscreenElement) {
document.exitFullscreen();
}
else {
document.documentElement.requestFullscreen();
}
};
function resetNowPlaying() {
document.querySelector('#track-title').textContent = 'No track playing';
document.querySelector('#track-artist').textContent = 'Unknown Artist';
document.querySelector('#album-title').textContent = 'Unknown Album';
document.querySelector('#album-year').textContent = '----';
document.querySelector('#track-remaining').textContent = '0:00/0:00'; // Default time
document.querySelector('#album-art').src = 'images/no_song.png'; // Path to a default image
document.querySelector('#audio-info').textContent = 'No audio information available';
document.title = 'Plex Now Playing';
}
setInterval(progressTimer, 1000); // Call progressTimer every second
setInterval(fetchNowPlaying, 900);
import {
getDominantColor
}
from './getColour.js';
fetchNowPlaying();