chore: code formatting

This commit is contained in:
github-actions[bot]
2022-04-23 23:18:43 +00:00
parent 73cd43c18f
commit 4c98629bbc
130 changed files with 1839 additions and 1788 deletions

View File

@@ -3,28 +3,28 @@ import crypto from "crypto"
//Supported providers
const providers = {
apple:{
name:"Apple Music",
embed:/^https:..embed.music.apple.com.\w+.playlist/,
apple: {
name: "Apple Music",
embed: /^https:..embed.music.apple.com.\w+.playlist/,
},
spotify:{
name:"Spotify",
embed:/^https:..open.spotify.com.embed.playlist/,
spotify: {
name: "Spotify",
embed: /^https:..open.spotify.com.embed.playlist/,
},
lastfm:{
name:"Last.fm",
embed:/^\b$/,
lastfm: {
name: "Last.fm",
embed: /^\b$/,
},
youtube:{
name:"YouTube Music",
embed:/^https:..music.youtube.com.playlist/,
youtube: {
name: "YouTube Music",
embed: /^https:..music.youtube.com.playlist/,
},
}
//Supported modes
const modes = {
playlist:"Suggested tracks",
recent:"Recently played",
top:"Top played",
playlist: "Suggested tracks",
recent: "Recently played",
top: "Top played",
}
//Setup
@@ -47,7 +47,7 @@ export default async function({login, imports, data, q, account}, {enabled = fal
let tracks = null
//Load inputs
let {provider, mode, playlist, limit, user, "played.at":played_at, "time.range":time_range, "top.type":top_type, token:_token} = imports.metadata.plugins.music.inputs({data, account, q})
let {provider, mode, playlist, limit, user, "played.at": played_at, "time.range": time_range, "top.type": top_type, token: _token} = imports.metadata.plugins.music.inputs({data, account, q})
if ((sandbox) && (_token)) {
token = _token
console.debug(`metrics/compute/${login}/plugins > music > overriden token value through user inputs as sandbox mode is enabled`)
@@ -71,16 +71,16 @@ export default async function({login, imports, data, q, account}, {enabled = fal
}
//Provider
if (!(provider in providers))
throw {error:{message:provider ? `Unsupported provider "${provider}"` : "Missing provider"}, ...raw}
throw {error: {message: provider ? `Unsupported provider "${provider}"` : "Missing provider"}, ...raw}
//Mode
if (!(mode in modes))
throw {error:{message:`Unsupported mode "${mode}"`}, ...raw}
throw {error: {message: `Unsupported mode "${mode}"`}, ...raw}
//Playlist mode
if (mode === "playlist") {
if (!playlist)
throw {error:{message:"Missing playlist url"}, ...raw}
throw {error: {message: "Missing playlist url"}, ...raw}
if (!providers[provider].embed.test(playlist))
throw {error:{message:"Unsupported playlist url format"}, ...raw}
throw {error: {message: "Unsupported playlist url format"}, ...raw}
}
//Limit
limit = Math.max(1, Math.min(100, Number(limit)))
@@ -111,9 +111,9 @@ export default async function({login, imports, data, q, account}, {enabled = fal
...await frame.evaluate(() => {
const tracklist = document.querySelector("embed-root").shadowRoot.querySelector(".audio-tracklist")
return [...tracklist.querySelectorAll("embed-audio-tracklist-item")].map(item => ({
name:item.querySelector(".audio-tracklist-item__metadata h3").innerText,
artist:item.querySelector(".audio-tracklist-item__metadata h4").innerText,
artwork:item.querySelector("apple-music-artwork")?.shadowRoot?.querySelector("picture source")?.srcset?.split(",")?.[0]?.replace(/\s+\d+x$/, ""),
name: item.querySelector(".audio-tracklist-item__metadata h3").innerText,
artist: item.querySelector(".audio-tracklist-item__metadata h4").innerText,
artwork: item.querySelector("apple-music-artwork")?.shadowRoot?.querySelector("picture source")?.srcset?.split(",")?.[0]?.replace(/\s+\d+x$/, ""),
}))
}),
]
@@ -124,11 +124,12 @@ export default async function({login, imports, data, q, account}, {enabled = fal
//Parse tracklist
await frame.waitForSelector("table")
tracks = [
...await frame.evaluate(() => [...document.querySelectorAll("table tr")].map(tr => ({
name:tr.querySelector("td:nth-child(2) div div:nth-child(1)").innerText,
artist:tr.querySelector("td:nth-child(2) div div:nth-child(2)").innerText,
...await frame.evaluate(() =>
[...document.querySelectorAll("table tr")].map(tr => ({
name: tr.querySelector("td:nth-child(2) div div:nth-child(1)").innerText,
artist: tr.querySelector("td:nth-child(2) div div:nth-child(2)").innerText,
//Spotify doesn't provide artworks so we fallback on playlist artwork instead
artwork:window.getComputedStyle(document.querySelector("button[title=Play]")?.parentNode ?? document.querySelector("button").parentNode, null).backgroundImage.match(/^url\("(?<url>https:...+)"\)$/)?.groups?.url ?? null,
artwork: window.getComputedStyle(document.querySelector("button[title=Play]")?.parentNode ?? document.querySelector("button").parentNode, null).backgroundImage.match(/^url\("(?<url>https:...+)"\)$/)?.groups?.url ?? null,
}))
),
]
@@ -140,10 +141,11 @@ export default async function({login, imports, data, q, account}, {enabled = fal
await frame.evaluate(() => window.scrollBy(0, window.innerHeight))
//Parse tracklist
tracks = [
...await frame.evaluate(() => [...document.querySelectorAll("ytmusic-playlist-shelf-renderer ytmusic-responsive-list-item-renderer")].map(item => ({
name:item.querySelector("yt-formatted-string.title > a")?.innerText ?? "",
artist:item.querySelector(".secondary-flex-columns > yt-formatted-string > a")?.innerText ?? "",
artwork:item.querySelector("img").src,
...await frame.evaluate(() =>
[...document.querySelectorAll("ytmusic-playlist-shelf-renderer ytmusic-responsive-list-item-renderer")].map(item => ({
name: item.querySelector("yt-formatted-string.title > a")?.innerText ?? "",
artist: item.querySelector(".secondary-flex-columns > yt-formatted-string > a")?.innerText ?? "",
artwork: item.querySelector("img").src,
}))
),
]
@@ -151,7 +153,7 @@ export default async function({login, imports, data, q, account}, {enabled = fal
}
//Unsupported
default:
throw {error:{message:`Unsupported mode "${mode}" for provider "${provider}"`}, ...raw}
throw {error: {message: `Unsupported mode "${mode}" for provider "${provider}"`}, ...raw}
}
//Close browser
console.debug(`metrics/compute/${login}/plugins > music > closing browser`)
@@ -160,7 +162,7 @@ export default async function({login, imports, data, q, account}, {enabled = fal
if (Array.isArray(tracks)) {
//Tracks
console.debug(`metrics/compute/${login}/plugins > music > found ${tracks.length} tracks`)
console.debug(imports.util.inspect(tracks, {depth:Infinity, maxStringLength:256}))
console.debug(imports.util.inspect(tracks, {depth: Infinity, maxStringLength: 256}))
//Shuffle tracks
tracks = imports.shuffle(tracks)
}
@@ -175,14 +177,14 @@ export default async function({login, imports, data, q, account}, {enabled = fal
//Prepare credentials
const [client_id, client_secret, refresh_token] = token.split(",").map(part => part.trim())
if ((!client_id) || (!client_secret) || (!refresh_token))
throw {error:{message:"Spotify token must contain client id/secret and refresh token"}}
throw {error: {message: "Spotify token must contain client id/secret and refresh token"}}
//API call and parse tracklist
try {
//Request access token
console.debug(`metrics/compute/${login}/plugins > music > requesting access token with spotify refresh token`)
const {data:{access_token:access}} = await imports.axios.post("https://accounts.spotify.com/api/token", `${new imports.url.URLSearchParams({grant_type:"refresh_token", refresh_token, client_id, client_secret})}`, {
headers:{
"Content-Type":"application/x-www-form-urlencoded",
const {data: {access_token: access}} = await imports.axios.post("https://accounts.spotify.com/api/token", `${new imports.url.URLSearchParams({grant_type: "refresh_token", refresh_token, client_id, client_secret})}`, {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})
console.debug(`metrics/compute/${login}/plugins > music > got access token`)
@@ -193,16 +195,16 @@ export default async function({login, imports, data, q, account}, {enabled = fal
//Load track half-hour by half-hour
const timestamp = Date.now() - hours * 60 * 60 * 1000
const loaded = (await imports.axios.get(`https://api.spotify.com/v1/me/player/recently-played?after=${timestamp}`, {
headers:{
"Content-Type":"application/json",
Accept:"application/json",
Authorization:`Bearer ${access}`,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${access}`,
},
})).data.items.map(({track, played_at}) => ({
name:track.name,
artist:track.artists[0].name,
artwork:track.album.images[0].url,
played_at:played_at ? `${imports.format.date(played_at, {time:true})} on ${imports.format.date(played_at, {date:true})}` : null,
name: track.name,
artist: track.artists[0].name,
artwork: track.album.images[0].url,
played_at: played_at ? `${imports.format.date(played_at, {time: true})} on ${imports.format.date(played_at, {date: true})}` : null,
}))
//Ensure no duplicate are added
for (const track of loaded) {
@@ -221,7 +223,7 @@ export default async function({login, imports, data, q, account}, {enabled = fal
const description = error.response.data?.error_description ?? null
const message = `API returned ${status}${description ? ` (${description})` : ""}`
error = error.response?.data ?? null
throw {error:{message, instance:error}, ...raw}
throw {error: {message, instance: error}, ...raw}
}
throw error
}
@@ -233,14 +235,14 @@ export default async function({login, imports, data, q, account}, {enabled = fal
try {
console.debug(`metrics/compute/${login}/plugins > music > querying lastfm api`)
tracks = (await imports.axios.get(`https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=${user}&api_key=${token}&limit=${limit}&format=json`, {
headers:{
"User-Agent":"lowlighter/metrics",
Accept:"application/json",
headers: {
"User-Agent": "lowlighter/metrics",
Accept: "application/json",
},
})).data.recenttracks.track.map(track => ({
name:track.name,
artist:track.artist["#text"],
artwork:track.image.reverse()[0]["#text"],
name: track.name,
artist: track.artist["#text"],
artwork: track.image.reverse()[0]["#text"],
}))
}
//Handle errors
@@ -250,7 +252,7 @@ export default async function({login, imports, data, q, account}, {enabled = fal
const description = error.response.data?.message ?? null
const message = `API returned ${status}${description ? ` (${description})` : ""}`
error = error.response?.data ?? null
throw {error:{message, instance:error}, ...raw}
throw {error: {message, instance: error}, ...raw}
}
throw error
}
@@ -267,25 +269,25 @@ export default async function({login, imports, data, q, account}, {enabled = fal
//Request access token
console.debug(`metrics/compute/${login}/plugins > music > requesting access token with youtube refresh token`)
const res = await imports.axios.post("https://music.youtube.com/youtubei/v1/browse?alt=json&key=AIzaSyC9XL3ZjWddXya6X74dJoCTL-WEYFDNX30", {
browseEndpointContextSupportedConfigs:{
browseEndpointContextMusicConfig:{
pageType:"MUSIC_PAGE_TYPE_PLAYLIST",
browseEndpointContextSupportedConfigs: {
browseEndpointContextMusicConfig: {
pageType: "MUSIC_PAGE_TYPE_PLAYLIST",
},
},
context:{
client:{
clientName:"WEB_REMIX",
clientVersion:"1.20211129.00.01",
gl:"US",
hl:"en",
context: {
client: {
clientName: "WEB_REMIX",
clientVersion: "1.20211129.00.01",
gl: "US",
hl: "en",
},
},
browseId:"FEmusic_history",
browseId: "FEmusic_history",
}, {
headers:{
Authorization:SAPISIDHASH,
Cookie:token,
"x-origin":"https://music.youtube.com",
headers: {
Authorization: SAPISIDHASH,
Cookie: token,
"x-origin": "https://music.youtube.com",
},
})
//Retrieve tracks
@@ -296,9 +298,9 @@ export default async function({login, imports, data, q, account}, {enabled = fal
for (let i = 0; i < parsedHistory.length; i++) {
let track = parsedHistory[i]
tracks.push({
name:track.flexColumns[0].musicResponsiveListItemFlexColumnRenderer.text.runs[0].text,
artist:track.flexColumns[1].musicResponsiveListItemFlexColumnRenderer.text.runs[0].text,
artwork:track.thumbnail.musicThumbnailRenderer.thumbnail.thumbnails[0].url,
name: track.flexColumns[0].musicResponsiveListItemFlexColumnRenderer.text.runs[0].text,
artist: track.flexColumns[1].musicResponsiveListItemFlexColumnRenderer.text.runs[0].text,
artwork: track.thumbnail.musicThumbnailRenderer.thumbnail.thumbnails[0].url,
})
//Early break
if (tracks.length >= limit)
@@ -312,7 +314,7 @@ export default async function({login, imports, data, q, account}, {enabled = fal
const description = error.response.data?.error_description ?? null
const message = `API returned ${status}${description ? ` (${description})` : ""}`
error = error.response?.data ?? null
throw {error:{message, instance:error}, ...raw}
throw {error: {message, instance: error}, ...raw}
}
throw error
}
@@ -320,7 +322,7 @@ export default async function({login, imports, data, q, account}, {enabled = fal
}
//Unsupported
default:
throw {error:{message:`Unsupported mode "${mode}" for provider "${provider}"`}, ...raw}
throw {error: {message: `Unsupported mode "${mode}" for provider "${provider}"`}, ...raw}
}
break
}
@@ -337,7 +339,7 @@ export default async function({login, imports, data, q, account}, {enabled = fal
time_msg = "overall"
break
default:
throw {error:{message:`Unsupported time range "${time_range}"`}, ...raw}
throw {error: {message: `Unsupported time range "${time_range}"`}, ...raw}
}
if (top_type === "artists") {
@@ -362,17 +364,17 @@ export default async function({login, imports, data, q, account}, {enabled = fal
//Prepare credentials
const [client_id, client_secret, refresh_token] = token.split(",").map(part => part.trim())
if ((!client_id) || (!client_secret) || (!refresh_token))
throw {error:{message:"Spotify token must contain client id/secret and refresh token"}}
throw {error: {message: "Spotify token must contain client id/secret and refresh token"}}
else if (limit > 50)
throw {error:{message:"Spotify top limit cannot be greater than 50"}}
throw {error: {message: "Spotify top limit cannot be greater than 50"}}
//API call and parse tracklist
try {
//Request access token
console.debug(`metrics/compute/${login}/plugins > music > requesting access token with spotify refresh token`)
const {data:{access_token:access}} = await imports.axios.post("https://accounts.spotify.com/api/token", `${new imports.url.URLSearchParams({grant_type:"refresh_token", refresh_token, client_id, client_secret})}`, {
headers:{
"Content-Type":"application/x-www-form-urlencoded",
const {data: {access_token: access}} = await imports.axios.post("https://accounts.spotify.com/api/token", `${new imports.url.URLSearchParams({grant_type: "refresh_token", refresh_token, client_id, client_secret})}`, {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})
console.debug(`metrics/compute/${login}/plugins > music > got access token`)
@@ -384,33 +386,33 @@ export default async function({login, imports, data, q, account}, {enabled = fal
await imports.axios.get(
`https://api.spotify.com/v1/me/top/artists?time_range=${time_range}_term&limit=${limit}`,
{
headers:{
"Content-Type":"application/json",
Accept:"application/json",
Authorization:`Bearer ${access}`,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${access}`,
},
},
)
).data.items.map(({name, genres, images}) => ({
name,
artist:genres.join(" • "),
artwork:images[0].url,
artist: genres.join(" • "),
artwork: images[0].url,
}))
: (
await imports.axios.get(
`https://api.spotify.com/v1/me/top/tracks?time_range=${time_range}_term&limit=${limit}`,
{
headers:{
"Content-Type":"application/json",
Accept:"application/json",
Authorization:`Bearer ${access}`,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${access}`,
},
},
)
).data.items.map(({name, artists, album}) => ({
name,
artist:artists[0].name,
artwork:album.images[0].url,
artist: artists[0].name,
artwork: album.images[0].url,
}))
//Ensure no duplicate are added
for (const track of loaded) {
@@ -425,7 +427,7 @@ export default async function({login, imports, data, q, account}, {enabled = fal
const description = error.response.data?.error_description ?? null
const message = `API returned ${status}${description ? ` (${description})` : ""}`
error = error.response?.data ?? null
throw {error:{message, instance:error}, ...raw}
throw {error: {message, instance: error}, ...raw}
}
throw error
}
@@ -442,31 +444,31 @@ export default async function({login, imports, data, q, account}, {enabled = fal
await imports.axios.get(
`https://ws.audioscrobbler.com/2.0/?method=user.gettopartists&user=${user}&api_key=${token}&limit=${limit}&period=${period}&format=json`,
{
headers:{
"User-Agent":"lowlighter/metrics",
Accept:"application/json",
headers: {
"User-Agent": "lowlighter/metrics",
Accept: "application/json",
},
},
)
).data.topartists.artist.map(artist => ({
name:artist.name,
artist:`Play count: ${artist.playcount}`,
artwork:artist.image.reverse()[0]["#text"],
name: artist.name,
artist: `Play count: ${artist.playcount}`,
artwork: artist.image.reverse()[0]["#text"],
}))
: (
await imports.axios.get(
`https://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user=${user}&api_key=${token}&limit=${limit}&period=${period}&format=json`,
{
headers:{
"User-Agent":"lowlighter/metrics",
Accept:"application/json",
headers: {
"User-Agent": "lowlighter/metrics",
Accept: "application/json",
},
},
)
).data.toptracks.track.map(track => ({
name:track.name,
artist:track.artist.name,
artwork:track.image.reverse()[0]["#text"],
name: track.name,
artist: track.artist.name,
artwork: track.image.reverse()[0]["#text"],
}))
}
//Handle errors
@@ -476,7 +478,7 @@ export default async function({login, imports, data, q, account}, {enabled = fal
const description = error.response.data?.message ?? null
const message = `API returned ${status}${description ? ` (${description})` : ""}`
error = error.response?.data ?? null
throw {error:{message, instance:error}, ...raw}
throw {error: {message, instance: error}, ...raw}
}
throw error
}
@@ -484,13 +486,13 @@ export default async function({login, imports, data, q, account}, {enabled = fal
}
//Unsupported
default:
throw {error:{message:`Unsupported mode "${mode}" for provider "${provider}"`}, ...raw}
throw {error: {message: `Unsupported mode "${mode}" for provider "${provider}"`}, ...raw}
}
break
}
//Unsupported
default:
throw {error:{message:`Unsupported mode "${mode}"`}, ...raw}
throw {error: {message: `Unsupported mode "${mode}"`}, ...raw}
}
//Format tracks
@@ -511,13 +513,13 @@ export default async function({login, imports, data, q, account}, {enabled = fal
}
//Unhandled error
throw {error:{message:"An error occured (could not retrieve tracks)"}}
throw {error: {message: "An error occured (could not retrieve tracks)"}}
}
//Handle errors
catch (error) {
if (error.error?.message)
throw error
throw {error:{message:"An error occured", instance:error}}
throw {error: {message: "An error occured", instance: error}}
}
}