Refactor plugins and erros
This commit is contained in:
@@ -1,40 +1,29 @@
|
||||
//Setup
|
||||
export default function ({login, imports, data, computed, pending, q}, {enabled = false} = {}) {
|
||||
//Check if plugin is enabled and requirements are met
|
||||
if (!enabled)
|
||||
return computed.plugins.followup = null
|
||||
if (!q.followup)
|
||||
return computed.plugins.followup = null
|
||||
console.debug(`metrics/compute/${login}/plugins > followup`)
|
||||
|
||||
export default async function ({computed, q}, {enabled = false} = {}) {
|
||||
//Plugin execution
|
||||
pending.push(new Promise(async solve => {
|
||||
try {
|
||||
//Define getters
|
||||
const followup = {
|
||||
issues:{
|
||||
get count() { return this.open + this.closed },
|
||||
get open() { return computed.repositories.issues_open },
|
||||
get closed() { return computed.repositories.issues_closed },
|
||||
},
|
||||
pr:{
|
||||
get count() { return this.open + this.merged },
|
||||
get open() { return computed.repositories.pr_open },
|
||||
get merged() { return computed.repositories.pr_merged }
|
||||
}
|
||||
try {
|
||||
//Check if plugin is enabled and requirements are met
|
||||
if ((!enabled)||(!q.followup))
|
||||
return null
|
||||
//Define getters
|
||||
const followup = {
|
||||
issues:{
|
||||
get count() { return this.open + this.closed },
|
||||
get open() { return computed.repositories.issues_open },
|
||||
get closed() { return computed.repositories.issues_closed },
|
||||
},
|
||||
pr:{
|
||||
get count() { return this.open + this.merged },
|
||||
get open() { return computed.repositories.pr_open },
|
||||
get merged() { return computed.repositories.pr_merged }
|
||||
}
|
||||
//Save results
|
||||
computed.plugins.followup = followup
|
||||
console.debug(`metrics/compute/${login}/plugins > followup > success`)
|
||||
console.debug(JSON.stringify(computed.plugins.followup))
|
||||
solve()
|
||||
}
|
||||
catch (error) {
|
||||
//Generic error
|
||||
computed.plugins.followup = {error:`An error occured`}
|
||||
console.debug(`metrics/compute/${login}/plugins > followup > error`)
|
||||
console.debug(error)
|
||||
solve()
|
||||
}
|
||||
}))
|
||||
}
|
||||
//Results
|
||||
return followup
|
||||
}
|
||||
//Handle errors
|
||||
catch (error) {
|
||||
console.debug(error)
|
||||
throw {error:{message:`An error occured`}}
|
||||
}
|
||||
}
|
||||
@@ -1,66 +1,52 @@
|
||||
//Setup
|
||||
export default function ({login, imports, rest, computed, pending, q}, {enabled = false, from:defaults = 100} = {}) {
|
||||
//Check if plugin is enabled and requirements are met
|
||||
if (!enabled)
|
||||
return computed.plugins.habits = null
|
||||
if (!q.habits)
|
||||
return computed.plugins.habits = null
|
||||
console.debug(`metrics/compute/${login}/plugins > habits`)
|
||||
|
||||
//Parameters override
|
||||
let {"habits.from":from = defaults.from ?? 100} = q
|
||||
//Events
|
||||
from = Math.max(1, Math.min(100, Number(from)))
|
||||
//Debug
|
||||
console.debug(`metrics/compute/${login}/plugins > habits > ${JSON.stringify({from})}`)
|
||||
|
||||
export default async function ({login, rest, q}, {enabled = false, from:defaults = 100} = {}) {
|
||||
//Plugin execution
|
||||
pending.push(new Promise(async solve => {
|
||||
try {
|
||||
//Initialization
|
||||
const habits = {commits:{hour:NaN, hours:{}}, indents:{style:"", spaces:0, tabs:0}}
|
||||
//Get user recent commits from events
|
||||
const events = await rest.activity.listEventsForAuthenticatedUser({username:login, per_page:from})
|
||||
const commits = events.data
|
||||
.filter(({type}) => type === "PushEvent")
|
||||
.filter(({actor}) => actor.login === login)
|
||||
//Commit hour
|
||||
{
|
||||
//Compute commit hours
|
||||
const hours = commits.map(({created_at}) => (new Date(created_at)).getHours())
|
||||
for (const hour of hours)
|
||||
habits.commits.hours[hour] = (habits.commits.hours[hour] ?? 0) + 1
|
||||
//Compute hour with most commits
|
||||
habits.commits.hour = hours.length ? Object.entries(habits.commits.hours).sort(([an, a], [bn, b]) => b - a).map(([hour, occurence]) => hour)[0] : NaN
|
||||
}
|
||||
//Indent style
|
||||
{
|
||||
//Retrieve edited files
|
||||
const edited = await Promise.allSettled(commits
|
||||
.flatMap(({payload}) => payload.commits).map(commit => commit.url)
|
||||
.map(async commit => (await rest.request(commit)).data.files)
|
||||
)
|
||||
//Attemp to guess whether tabs or spaces are used from patch
|
||||
edited
|
||||
.filter(({status}) => status === "fulfilled")
|
||||
.map(({value}) => value)
|
||||
.flatMap(files => files.flatMap(file => (file.patch ?? "").match(/(?<=^[+])((?:\t)|(?: )) /gm) ?? []))
|
||||
.forEach(indent => habits.indents[/^\t/.test(indent) ? "tabs" : "spaces"]++)
|
||||
//Compute indent style
|
||||
habits.indents.style = habits.indents.spaces > habits.indents.tabs ? "spaces" : habits.indents.tabs > habits.indents.spaces ? "tabs" : ""
|
||||
}
|
||||
//Save results
|
||||
computed.plugins.habits = habits
|
||||
console.debug(`metrics/compute/${login}/plugins > habits > success`)
|
||||
console.debug(JSON.stringify(computed.plugins.habits))
|
||||
solve()
|
||||
}
|
||||
catch (error) {
|
||||
//Generic error
|
||||
computed.plugins.habits = {error:`An error occured`}
|
||||
console.debug(`metrics/compute/${login}/plugins > habits > error`)
|
||||
console.debug(error)
|
||||
solve()
|
||||
}
|
||||
}))
|
||||
try {
|
||||
//Check if plugin is enabled and requirements are met
|
||||
if ((!enabled)||(!q.habits))
|
||||
return null
|
||||
//Parameters override
|
||||
let {"habits.from":from = defaults.from ?? 100} = q
|
||||
//Events
|
||||
from = Math.max(1, Math.min(100, Number(from)))
|
||||
//Initialization
|
||||
const habits = {commits:{hour:NaN, hours:{}}, indents:{style:"", spaces:0, tabs:0}}
|
||||
//Get user recent commits from events
|
||||
const events = await rest.activity.listEventsForAuthenticatedUser({username:login, per_page:from})
|
||||
const commits = events.data
|
||||
.filter(({type}) => type === "PushEvent")
|
||||
.filter(({actor}) => actor.login === login)
|
||||
//Commit hour
|
||||
{
|
||||
//Compute commit hours
|
||||
const hours = commits.map(({created_at}) => (new Date(created_at)).getHours())
|
||||
for (const hour of hours)
|
||||
habits.commits.hours[hour] = (habits.commits.hours[hour] ?? 0) + 1
|
||||
//Compute hour with most commits
|
||||
habits.commits.hour = hours.length ? `${Object.entries(habits.commits.hours).sort(([an, a], [bn, b]) => b - a).map(([hour, occurence]) => hour)[0]}`.padStart(2, "0") : NaN
|
||||
}
|
||||
//Indent style
|
||||
{
|
||||
//Retrieve edited files
|
||||
const edited = await Promise.allSettled(commits
|
||||
.flatMap(({payload}) => payload.commits).map(commit => commit.url)
|
||||
.map(async commit => (await rest.request(commit)).data.files)
|
||||
)
|
||||
//Attemp to guess whether tabs or spaces are used from patch
|
||||
edited
|
||||
.filter(({status}) => status === "fulfilled")
|
||||
.map(({value}) => value)
|
||||
.flatMap(files => files.flatMap(file => (file.patch ?? "").match(/(?<=^[+])((?:\t)|(?: )) /gm) ?? []))
|
||||
.forEach(indent => habits.indents[/^\t/.test(indent) ? "tabs" : "spaces"]++)
|
||||
//Compute indent style
|
||||
habits.indents.style = habits.indents.spaces > habits.indents.tabs ? "spaces" : habits.indents.tabs > habits.indents.spaces ? "tabs" : ""
|
||||
}
|
||||
//Results
|
||||
return habits
|
||||
}
|
||||
//Handle errors
|
||||
catch (error) {
|
||||
console.debug(error)
|
||||
throw {error:{message:`An error occured`}}
|
||||
}
|
||||
}
|
||||
@@ -1,41 +1,30 @@
|
||||
//Setup
|
||||
export default function ({login, imports, data, computed, pending, q}, {enabled = false} = {}) {
|
||||
//Check if plugin is enabled and requirements are met
|
||||
if (!enabled)
|
||||
return computed.plugins.languages = null
|
||||
if (!q.languages)
|
||||
return computed.plugins.languages = null
|
||||
console.debug(`metrics/compute/${login}/plugins > languages`)
|
||||
|
||||
export default async function ({data, q}, {enabled = false} = {}) {
|
||||
//Plugin execution
|
||||
pending.push(new Promise(async solve => {
|
||||
try {
|
||||
//Iterate through user's repositories and retrieve languages data
|
||||
const languages = {colors:{}, total:0, stats:{}}
|
||||
for (const repository of data.user.repositories.nodes) {
|
||||
for (const {size, node:{color, name}} of Object.values(repository.languages.edges)) {
|
||||
languages.stats[name] = (languages.stats[name] || 0) + size
|
||||
languages.colors[name] = color || "#ededed"
|
||||
languages.total += size
|
||||
}
|
||||
try {
|
||||
//Check if plugin is enabled and requirements are met
|
||||
if ((!enabled)||(!q.languages))
|
||||
return null
|
||||
//Iterate through user's repositories and retrieve languages data
|
||||
const languages = {colors:{}, total:0, stats:{}}
|
||||
for (const repository of data.user.repositories.nodes) {
|
||||
for (const {size, node:{color, name}} of Object.values(repository.languages.edges)) {
|
||||
languages.stats[name] = (languages.stats[name] ?? 0) + size
|
||||
languages.colors[name] = color ?? "#ededed"
|
||||
languages.total += size
|
||||
}
|
||||
//Compute languages stats
|
||||
Object.keys(languages.stats).map(name => languages.stats[name] /= languages.total)
|
||||
languages.favorites = Object.entries(languages.stats).sort(([an, a], [bn, b]) => b - a).slice(0, 8).map(([name, value]) => ({name, value, color:languages.colors[name], x:0}))
|
||||
for (let i = 1; i < languages.favorites.length; i++)
|
||||
languages.favorites[i].x = languages.favorites[i-1].x + languages.favorites[i-1].value
|
||||
//Save results
|
||||
computed.plugins.languages = languages
|
||||
console.debug(`metrics/compute/${login}/plugins > languages > success`)
|
||||
console.debug(JSON.stringify(computed.plugins.languages))
|
||||
solve()
|
||||
}
|
||||
catch (error) {
|
||||
//Generic error
|
||||
computed.plugins.languages = {error:`An error occured`}
|
||||
console.debug(`metrics/compute/${login}/plugins > languages > error`)
|
||||
console.debug(error)
|
||||
solve()
|
||||
}
|
||||
}))
|
||||
}
|
||||
//Compute languages stats
|
||||
Object.keys(languages.stats).map(name => languages.stats[name] /= languages.total)
|
||||
languages.favorites = Object.entries(languages.stats).sort(([an, a], [bn, b]) => b - a).slice(0, 8).map(([name, value]) => ({name, value, color:languages.colors[name], x:0}))
|
||||
for (let i = 1; i < languages.favorites.length; i++)
|
||||
languages.favorites[i].x = languages.favorites[i-1].x + languages.favorites[i-1].value
|
||||
//Results
|
||||
return languages
|
||||
}
|
||||
//Handle errors
|
||||
catch (error) {
|
||||
console.debug(error)
|
||||
throw {error:{message:`An error occured`}}
|
||||
}
|
||||
}
|
||||
@@ -1,45 +1,36 @@
|
||||
//Setup
|
||||
export default function ({login, imports, repositories = [], rest, computed, pending, q}, {enabled = false} = {}) {
|
||||
//Check if plugin is enabled and requirements are met
|
||||
if (!enabled)
|
||||
return computed.plugins.lines = null
|
||||
if (!q.lines)
|
||||
return computed.plugins.lines = null
|
||||
console.debug(`metrics/compute/${login}/plugins > lines`)
|
||||
|
||||
export default async function ({login, data, imports, rest, q}, {enabled = false} = {}) {
|
||||
//Plugin execution
|
||||
pending.push(new Promise(async solve => {
|
||||
try {
|
||||
//Get contributors stats from repositories
|
||||
const lines = {added:0, deleted:0}
|
||||
const response = await Promise.all(repositories.map(async repo => await rest.repos.getContributorsStats({owner:login, repo})))
|
||||
//Compute changed lines
|
||||
response.map(({data:repository}) => {
|
||||
//Check if data are available
|
||||
if (!Array.isArray(repository))
|
||||
return
|
||||
//Extract author
|
||||
const [contributor] = repository.filter(({author}) => author.login === login)
|
||||
//Compute editions
|
||||
if (contributor)
|
||||
contributor.weeks.forEach(({a, d}) => (lines.added += a, lines.deleted += d))
|
||||
})
|
||||
//Format values
|
||||
lines.added = imports.format(lines.added)
|
||||
lines.deleted = imports.format(lines.deleted)
|
||||
//Save results
|
||||
computed.plugins.lines = {...lines}
|
||||
console.debug(`metrics/compute/${login}/plugins > lines > success`)
|
||||
console.debug(JSON.stringify(computed.plugins.lines))
|
||||
solve()
|
||||
}
|
||||
catch (error) {
|
||||
//Generic error
|
||||
computed.plugins.lines = {error:`An error occured`}
|
||||
console.debug(`metrics/compute/${login}/plugins > lines > error`)
|
||||
console.debug(error)
|
||||
solve()
|
||||
}
|
||||
}))
|
||||
try {
|
||||
//Check if plugin is enabled and requirements are met
|
||||
if ((!enabled)||(!q.lines))
|
||||
return null
|
||||
//Repositories
|
||||
const repositories = data.user.repositories.nodes.map(({name}) => name) ?? []
|
||||
//Get contributors stats from repositories
|
||||
const lines = {added:0, deleted:0}
|
||||
const response = await Promise.all(repositories.map(async repo => await rest.repos.getContributorsStats({owner:login, repo})))
|
||||
//Compute changed lines
|
||||
response.map(({data:repository}) => {
|
||||
//Check if data are available
|
||||
if (!Array.isArray(repository))
|
||||
return
|
||||
//Extract author
|
||||
const [contributor] = repository.filter(({author}) => author.login === login)
|
||||
//Compute editions
|
||||
if (contributor)
|
||||
contributor.weeks.forEach(({a, d}) => (lines.added += a, lines.deleted += d))
|
||||
})
|
||||
//Format values
|
||||
lines.added = imports.format(lines.added)
|
||||
lines.deleted = imports.format(lines.deleted)
|
||||
//Results
|
||||
return lines
|
||||
}
|
||||
//Handle errors
|
||||
catch (error) {
|
||||
console.debug(error)
|
||||
throw {error:{message:`An error occured`}}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,196 +17,177 @@
|
||||
}
|
||||
|
||||
//Setup
|
||||
export default function ({login, imports, rest, computed, pending, q}, {enabled = false, token = ""} = {}) {
|
||||
//Check if plugin is enabled and requirements are met
|
||||
if (!enabled)
|
||||
return computed.plugins.music = null
|
||||
if (!q.music)
|
||||
return computed.plugins.music = null
|
||||
console.debug(`metrics/compute/${login}/plugins > music`)
|
||||
const raw = {
|
||||
get provider() { return providers[provider]?.name ?? "" },
|
||||
get mode() { return modes[mode] ?? "Unconfigured music plugin"},
|
||||
}
|
||||
|
||||
//Parameters override and checks
|
||||
let {"music.provider":provider = "", "music.mode":mode = "", "music.playlist":playlist = null, "music.limit":limit = 4} = q
|
||||
//Auto-guess parameters
|
||||
if ((playlist)&&(!mode))
|
||||
mode = "playlist"
|
||||
if ((playlist)&&(!provider))
|
||||
for (const [name, {embed}] of Object.entries(providers))
|
||||
if (embed.test(playlist))
|
||||
provider = name
|
||||
if (!mode)
|
||||
mode = "recent"
|
||||
//Provider
|
||||
if (!(provider in providers))
|
||||
return computed.plugins.music = {...raw, error:provider ? `Unsupported provider "${provider}"` : `Missing provider`}
|
||||
//Mode
|
||||
if (!(mode in modes))
|
||||
return computed.plugins.music = {...raw, error:`Unsupported mode "${mode}"`}
|
||||
//Playlist mode
|
||||
if (mode === "playlist") {
|
||||
if (!playlist)
|
||||
return computed.plugins.music = {...raw, error:`Missing playlist url`}
|
||||
if (!providers[provider].embed.test(playlist))
|
||||
return computed.plugins.music = {...raw, error:`Unsupported playlist url format`}
|
||||
}
|
||||
//Limit
|
||||
limit = Math.max(1, Math.min(100, Number(limit)))
|
||||
//Debug
|
||||
console.debug(`metrics/compute/${login}/plugins > habits > ${JSON.stringify({provider, mode, playlist, limit})}`)
|
||||
|
||||
export default async function ({login, imports, q}, {enabled = false, token = ""} = {}) {
|
||||
//Plugin execution
|
||||
pending.push(new Promise(async solve => {
|
||||
//Retrieve music data
|
||||
try {
|
||||
//Initialization
|
||||
let tracks = null
|
||||
//Handle mode
|
||||
switch (mode) {
|
||||
//Playlist mode
|
||||
case "playlist":{
|
||||
//Start puppeteer and navigate to playlist
|
||||
console.debug(`metrics/compute/${login}/plugins > music > starting browser`)
|
||||
const browser = await imports.puppeteer.launch({headless:true, executablePath:process.env.PUPPETEER_BROWSER_PATH, args:["--no-sandbox", "--disable-extensions", "--disable-setuid-sandbox", "--disable-dev-shm-usage"]})
|
||||
console.debug(`metrics/compute/${login}/plugins > music > loaded ${await browser.version()}`)
|
||||
const page = await browser.newPage()
|
||||
console.debug(`metrics/compute/${login}/plugins > music > loading page`)
|
||||
await page.goto(playlist)
|
||||
const frame = page.mainFrame()
|
||||
//Handle provider
|
||||
switch (provider) {
|
||||
//Apple music
|
||||
case "apple":{
|
||||
//Parse tracklist
|
||||
await frame.waitForSelector(".tracklist.playlist")
|
||||
tracks = [...await frame.evaluate(() => [...document.querySelectorAll(".tracklist li")].map(li => ({
|
||||
name:li.querySelector(".tracklist__track__name").innerText,
|
||||
artist:li.querySelector(".tracklist__track__sub").innerText,
|
||||
artwork:li.querySelector(".tracklist__track__artwork img").src
|
||||
})))]
|
||||
break
|
||||
}
|
||||
//Spotify
|
||||
case "spotify":{
|
||||
//Parse tracklist
|
||||
await frame.waitForSelector("table")
|
||||
tracks = [...await frame.evaluate(() => [...document.querySelectorAll("table tr")].map(tr => ({
|
||||
name:tr.querySelector("td:nth-child(2) div:nth-child(1)").innerText,
|
||||
artist:tr.querySelector("td:nth-child(2) 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, null).backgroundImage.match(/^url\("(https:...+)"\)$/)[1]
|
||||
})))]
|
||||
break
|
||||
}
|
||||
//Unsupported
|
||||
default:{
|
||||
throw {status:`Unsupported mode "${mode}" for provider "${provider}"`}
|
||||
}
|
||||
}
|
||||
//Close browser
|
||||
console.debug(`metrics/compute/${login}/plugins > music > closing browser`)
|
||||
await browser.close()
|
||||
//Format tracks
|
||||
if (Array.isArray(tracks)) {
|
||||
//Tracks
|
||||
console.debug(`metrics/compute/${login}/plugins > music > found ${tracks.length} tracks`)
|
||||
console.debug(JSON.stringify(tracks))
|
||||
//Shuffle tracks
|
||||
tracks = imports.shuffle(tracks)
|
||||
}
|
||||
break
|
||||
}
|
||||
//Recently played
|
||||
case "recent":{
|
||||
//Initialisation
|
||||
const timestamp = Date.now()-24*60*60*1000
|
||||
//Handle provider
|
||||
switch (provider) {
|
||||
//Spotify
|
||||
case "spotify":{
|
||||
//Prepare credentials
|
||||
const [client_id, client_secret, refresh_token] = token.split(",").map(part => part.trim())
|
||||
if ((!client_id)||(!client_secret)||(!refresh_token))
|
||||
throw {status:`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 refresh token for spotify`)
|
||||
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.log(access)
|
||||
console.debug(`metrics/compute/${login}/plugins > music > got new access token`)
|
||||
//Retriev tracks
|
||||
tracks = (await imports.axios(`https://api.spotify.com/v1/me/player/recently-played?limit=${limit}&after=${timestamp}`, {headers:{
|
||||
"Accept":"application/json",
|
||||
"Content-Type":"application/json",
|
||||
"Authorization":`Bearer ${access}`}
|
||||
})).data.items.map(({track}) => ({
|
||||
name:track.name,
|
||||
artist:track.artists[0].name,
|
||||
artwork:track.album.images[0].url,
|
||||
}))
|
||||
}
|
||||
//Handle errors
|
||||
catch (error) {
|
||||
console.debug(error)
|
||||
if ((error.response)&&(error.response.status))
|
||||
throw {status:`API call returned ${error.response.status}`}
|
||||
throw error
|
||||
}
|
||||
break
|
||||
}
|
||||
//Unsupported
|
||||
default:{
|
||||
throw {status:`Unsupported mode "${mode}" for provider "${provider}"`}
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
//Unsupported
|
||||
default:{
|
||||
throw {status:`Unsupported mode "${mode}"`}
|
||||
}
|
||||
}
|
||||
//Format tracks
|
||||
if (Array.isArray(tracks)) {
|
||||
//Limit tracklist
|
||||
if (limit > 0) {
|
||||
console.debug(`metrics/compute/${login}/plugins > music > keeping only ${limit} tracks`)
|
||||
tracks = tracks.slice(0, limit)
|
||||
}
|
||||
//Convert artworks to base64
|
||||
console.debug(`metrics/compute/${login}/plugins > music > loading artworks`)
|
||||
for (const track of tracks) {
|
||||
console.debug(`metrics/compute/${login}/plugins > music > processing ${track.name}`)
|
||||
track.artwork = await imports.imgb64(track.artwork)
|
||||
}
|
||||
//Save results
|
||||
console.debug(`metrics/compute/${login}/plugins > music > success`)
|
||||
computed.plugins.music = {...raw, tracks}
|
||||
solve()
|
||||
return
|
||||
}
|
||||
//Unhandled error
|
||||
throw {status:`An error occured (unhandled)`}
|
||||
try {
|
||||
//Check if plugin is enabled and requirements are met
|
||||
if ((!enabled)||(!q.music))
|
||||
return null
|
||||
|
||||
//Initialization
|
||||
const raw = {
|
||||
get provider() { return providers[provider]?.name ?? "" },
|
||||
get mode() { return modes[mode] ?? "Unconfigured music plugin"},
|
||||
}
|
||||
catch (error) {
|
||||
//Plugin error
|
||||
if (error.status) {
|
||||
computed.plugins.music = {...raw, error:error.status}
|
||||
console.debug(`metrics/compute/${login}/plugins > music > error > ${error.status}`)
|
||||
return solve()
|
||||
let tracks = null
|
||||
|
||||
//Parameters override
|
||||
let {"music.provider":provider = "", "music.mode":mode = "", "music.playlist":playlist = null, "music.limit":limit = 4} = q
|
||||
//Auto-guess parameters
|
||||
if ((playlist)&&(!mode))
|
||||
mode = "playlist"
|
||||
if ((playlist)&&(!provider))
|
||||
for (const [name, {embed}] of Object.entries(providers))
|
||||
if (embed.test(playlist))
|
||||
provider = name
|
||||
if (!mode)
|
||||
mode = "recent"
|
||||
//Provider
|
||||
if (!(provider in providers))
|
||||
throw {error:{message:provider ? `Unsupported provider "${provider}"` : `Missing provider`}, ...raw}
|
||||
//Mode
|
||||
if (!(mode in modes))
|
||||
throw {error:{message:`Unsupported mode "${mode}"`}, ...raw}
|
||||
//Playlist mode
|
||||
if (mode === "playlist") {
|
||||
if (!playlist)
|
||||
throw {error:{message:`Missing playlist url`}, ...raw}
|
||||
if (!providers[provider].embed.test(playlist))
|
||||
throw {error:{message:`Unsupported playlist url format`}, ...raw}
|
||||
}
|
||||
//Generic error
|
||||
computed.plugins.music = {...raw, error:`An error occured`}
|
||||
console.debug(`metrics/compute/${login}/plugins > music > error`)
|
||||
console.debug(error)
|
||||
solve()
|
||||
//Limit
|
||||
limit = Math.max(1, Math.min(100, Number(limit)))
|
||||
|
||||
//Handle mode
|
||||
switch (mode) {
|
||||
//Playlist mode
|
||||
case "playlist":{
|
||||
//Start puppeteer and navigate to playlist
|
||||
console.debug(`metrics/compute/${login}/plugins > music > starting browser`)
|
||||
const browser = await imports.puppeteer.launch({headless:true, executablePath:process.env.PUPPETEER_BROWSER_PATH, args:["--no-sandbox", "--disable-extensions", "--disable-setuid-sandbox", "--disable-dev-shm-usage"]})
|
||||
console.debug(`metrics/compute/${login}/plugins > music > loaded ${await browser.version()}`)
|
||||
const page = await browser.newPage()
|
||||
console.debug(`metrics/compute/${login}/plugins > music > loading page`)
|
||||
await page.goto(playlist)
|
||||
const frame = page.mainFrame()
|
||||
//Handle provider
|
||||
switch (provider) {
|
||||
//Apple music
|
||||
case "apple":{
|
||||
//Parse tracklist
|
||||
await frame.waitForSelector(".tracklist.playlist")
|
||||
tracks = [...await frame.evaluate(() => [...document.querySelectorAll(".tracklist li")].map(li => ({
|
||||
name:li.querySelector(".tracklist__track__name").innerText,
|
||||
artist:li.querySelector(".tracklist__track__sub").innerText,
|
||||
artwork:li.querySelector(".tracklist__track__artwork img").src
|
||||
})))]
|
||||
break
|
||||
}
|
||||
//Spotify
|
||||
case "spotify":{
|
||||
//Parse tracklist
|
||||
await frame.waitForSelector("table")
|
||||
tracks = [...await frame.evaluate(() => [...document.querySelectorAll("table tr")].map(tr => ({
|
||||
name:tr.querySelector("td:nth-child(2) div:nth-child(1)").innerText,
|
||||
artist:tr.querySelector("td:nth-child(2) 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, null).backgroundImage.match(/^url\("(https:...+)"\)$/)[1]
|
||||
})))]
|
||||
break
|
||||
}
|
||||
//Unsupported
|
||||
default:
|
||||
throw {error:{message:`Unsupported mode "${mode}" for provider "${provider}"`}, ...raw}
|
||||
}
|
||||
//Close browser
|
||||
console.debug(`metrics/compute/${login}/plugins > music > closing browser`)
|
||||
await browser.close()
|
||||
//Format tracks
|
||||
if (Array.isArray(tracks)) {
|
||||
//Tracks
|
||||
console.debug(`metrics/compute/${login}/plugins > music > found ${tracks.length} tracks`)
|
||||
console.debug(JSON.stringify(tracks))
|
||||
//Shuffle tracks
|
||||
tracks = imports.shuffle(tracks)
|
||||
}
|
||||
break
|
||||
}
|
||||
//Recently played
|
||||
case "recent":{
|
||||
//Initialisation
|
||||
const timestamp = Date.now()-24*60*60*1000
|
||||
//Handle provider
|
||||
switch (provider) {
|
||||
//Spotify
|
||||
case "spotify":{
|
||||
//Prepare credentials
|
||||
const [client_id, client_secret, refresh_token] = token.split(",").map(part => part.trim())
|
||||
if ((!client_id)||(!client_secret)||(!refresh_token))
|
||||
throw {error:`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 refresh token for spotify`)
|
||||
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.log(access)
|
||||
console.debug(`metrics/compute/${login}/plugins > music > got new access token`)
|
||||
//Retriev tracks
|
||||
tracks = (await imports.axios(`https://api.spotify.com/v1/me/player/recently-played?limit=${limit}&after=${timestamp}`, {headers:{
|
||||
"Accept":"application/json",
|
||||
"Content-Type":"application/json",
|
||||
"Authorization":`Bearer ${access}`}
|
||||
})).data.items.map(({track}) => ({
|
||||
name:track.name,
|
||||
artist:track.artists[0].name,
|
||||
artwork:track.album.images[0].url,
|
||||
}))
|
||||
}
|
||||
//Handle errors
|
||||
catch (error) {
|
||||
if ((error.response?.status))
|
||||
throw {error:{message:`API returned ${error.response.status}`}, ...raw}
|
||||
throw error
|
||||
}
|
||||
break
|
||||
}
|
||||
//Unsupported
|
||||
default:
|
||||
throw {error:{message:`Unsupported mode "${mode}" for provider "${provider}"`}, ...raw}
|
||||
}
|
||||
break
|
||||
}
|
||||
//Unsupported
|
||||
default:
|
||||
throw {error:{message:`Unsupported mode "${mode}"`}, ...raw}
|
||||
}
|
||||
}))
|
||||
}
|
||||
//Format tracks
|
||||
if (Array.isArray(tracks)) {
|
||||
//Limit tracklist
|
||||
if (limit > 0) {
|
||||
console.debug(`metrics/compute/${login}/plugins > music > keeping only ${limit} tracks`)
|
||||
tracks = tracks.slice(0, limit)
|
||||
}
|
||||
//Convert artworks to base64
|
||||
console.debug(`metrics/compute/${login}/plugins > music > loading artworks`)
|
||||
for (const track of tracks) {
|
||||
console.debug(`metrics/compute/${login}/plugins > music > processing ${track.name}`)
|
||||
track.artwork = await imports.imgb64(track.artwork)
|
||||
}
|
||||
//Save results
|
||||
console.debug(`metrics/compute/${login}/plugins > music > success`)
|
||||
return {...raw, tracks}
|
||||
}
|
||||
//Unhandled error
|
||||
throw {error:{message:`An error occured (could not retrieve tracks)`}}
|
||||
}
|
||||
//Handle errors
|
||||
catch (error) {
|
||||
if (error.error?.message)
|
||||
throw error
|
||||
console.debug(error)
|
||||
throw {error:{message:`An error occured`}}
|
||||
}
|
||||
}
|
||||
@@ -1,44 +1,27 @@
|
||||
//Setup
|
||||
export default function ({login, imports, url, computed, pending, q}, {enabled = false, token = null} = {}) {
|
||||
//Check if plugin is enabled and requirements are met
|
||||
if (!enabled)
|
||||
return computed.plugins.pagespeed = null
|
||||
if (!url)
|
||||
return computed.plugins.pagespeed = null
|
||||
if (!q.pagespeed)
|
||||
return computed.plugins.pagespeed = null
|
||||
console.debug(`metrics/compute/${login}/plugins > pagespeed`)
|
||||
|
||||
export default async function ({imports, data, q}, {enabled = false, token = null} = {}) {
|
||||
//Plugin execution
|
||||
pending.push(new Promise(async solve => {
|
||||
try {
|
||||
//Format url if needed
|
||||
if (!/^https?:[/][/]/.test(url))
|
||||
url = `https://${url}`
|
||||
//Load scores from API
|
||||
const scores = new Map()
|
||||
await Promise.all(["performance", "accessibility", "best-practices", "seo"].map(async category => {
|
||||
const {score, title} = (await imports.axios.get(`https://www.googleapis.com/pagespeedonline/v5/runPagespeed?category=${category}&url=${url}&key=${token}`)).data.lighthouseResult.categories[category]
|
||||
scores.set(category, {score, title})
|
||||
}))
|
||||
//Save results
|
||||
computed.plugins.pagespeed = {url, scores:[scores.get("performance"), scores.get("accessibility"), scores.get("best-practices"), scores.get("seo")]}
|
||||
console.debug(`metrics/compute/${login}/plugins > pagespeed > success`)
|
||||
console.debug(JSON.stringify(computed.plugins.pagespeed))
|
||||
solve()
|
||||
}
|
||||
catch (error) {
|
||||
//Thrown when token is incorrect
|
||||
if ((error.response)&&(error.response.status)) {
|
||||
computed.plugins.pagespeed = {url, error:`PageSpeed token error (code ${error.response.status})`}
|
||||
console.debug(`metrics/plugins/pagespeed/${login} > ${error.response.status}`)
|
||||
return solve()
|
||||
}
|
||||
//Generic error
|
||||
computed.plugins.pagespeed = {error:`An error occured`}
|
||||
console.debug(`metrics/compute/${login}/plugins > pagespeed > error`)
|
||||
console.debug(error)
|
||||
solve()
|
||||
}
|
||||
}))
|
||||
try {
|
||||
//Check if plugin is enabled and requirements are met
|
||||
if ((!enabled)||(!q.pagespeed)||(!data.user.websiteUrl))
|
||||
return null
|
||||
//Format url if needed
|
||||
let url = data.user.websiteUrl
|
||||
if (!/^https?:[/][/]/.test(url))
|
||||
url = `https://${url}`
|
||||
//Load scores from API
|
||||
const scores = new Map()
|
||||
await Promise.all(["performance", "accessibility", "best-practices", "seo"].map(async category => {
|
||||
const {score, title} = (await imports.axios.get(`https://www.googleapis.com/pagespeedonline/v5/runPagespeed?category=${category}&url=${url}&key=${token}`)).data.lighthouseResult.categories[category]
|
||||
scores.set(category, {score, title})
|
||||
}))
|
||||
//Results
|
||||
return {url, scores:[scores.get("performance"), scores.get("accessibility"), scores.get("best-practices"), scores.get("seo")]}
|
||||
}
|
||||
//Handle errors
|
||||
catch (error) {
|
||||
if (error.response?.status)
|
||||
throw {error:{message:`PageSpeed token error (code ${error.response.status})`}, url}
|
||||
throw {error:{message:`An error occured`}}
|
||||
}
|
||||
}
|
||||
@@ -1,36 +1,25 @@
|
||||
//Setup
|
||||
export default function ({login, imports, rest, computed, pending, q}, {enabled = false} = {}) {
|
||||
//Check if plugin is enabled and requirements are met
|
||||
if (!enabled)
|
||||
return computed.plugins.selfskip = null
|
||||
if (!q.selfskip)
|
||||
return computed.plugins.selfskip = null
|
||||
console.debug(`metrics/compute/${login}/plugins > selfskip`)
|
||||
|
||||
export default async function ({login, rest, computed, q}, {enabled = false} = {}) {
|
||||
//Plugin execution
|
||||
pending.push(new Promise(async solve => {
|
||||
try {
|
||||
//Search for auto-generated commits
|
||||
let commits = 0
|
||||
for (let page = 0;;page++) {
|
||||
const {data} = await rest.repos.listCommits({owner:login, repo:login, author:login, per_page:100, page})
|
||||
commits += data.filter(({commit}) => /\[Skip GitHub Action\]/.test(commit.message)).length
|
||||
if (!data.length)
|
||||
break
|
||||
}
|
||||
//Save results
|
||||
computed.plugins.selfskip = {commits}
|
||||
computed.commits -= commits
|
||||
console.debug(`metrics/compute/${login}/plugins > selfskip > success`)
|
||||
console.debug(JSON.stringify(computed.plugins.selfskip))
|
||||
solve()
|
||||
}
|
||||
catch (error) {
|
||||
//Generic error
|
||||
computed.plugins.selfskip = {error:`An error occured`}
|
||||
console.debug(`metrics/compute/${login}/plugins > selfskip > error`)
|
||||
console.debug(error)
|
||||
solve()
|
||||
}
|
||||
}))
|
||||
try {
|
||||
//Check if plugin is enabled and requirements are met
|
||||
if ((!enabled)||(!q.selfskip))
|
||||
return null
|
||||
//Search for auto-generated commits
|
||||
let commits = 0
|
||||
for (let page = 0;;page++) {
|
||||
const {data} = await rest.repos.listCommits({owner:login, repo:login, author:login, per_page:100, page})
|
||||
commits += data.filter(({commit}) => /\[Skip GitHub Action\]/.test(commit.message)).length
|
||||
if (!data.length)
|
||||
break
|
||||
}
|
||||
//Results
|
||||
computed.commits -= commits
|
||||
return {commits}
|
||||
}
|
||||
//Handle errors
|
||||
catch (error) {
|
||||
console.debug(error)
|
||||
throw {error:{message:`An error occured`}}
|
||||
}
|
||||
}
|
||||
@@ -1,41 +1,28 @@
|
||||
//Setup
|
||||
export default function ({login, imports, repositories = [], rest, computed, pending, q}, {enabled = false} = {}) {
|
||||
//Check if plugin is enabled and requirements are met
|
||||
if (!enabled)
|
||||
return computed.plugins.traffic = null
|
||||
if (!q.traffic)
|
||||
return computed.plugins.traffic = null
|
||||
console.debug(`metrics/compute/${login}/plugins > traffic`)
|
||||
|
||||
export default async function ({login, imports, data, rest, q}, {enabled = false} = {}) {
|
||||
//Plugin execution
|
||||
pending.push(new Promise(async solve => {
|
||||
try {
|
||||
//Get views stats from repositories
|
||||
const views = {count:0, uniques:0}
|
||||
const response = await Promise.all(repositories.map(async repo => await rest.repos.getViews({owner:login, repo})))
|
||||
//Compute views
|
||||
response.filter(({data}) => data).map(({data:{count, uniques}}) => (views.count += count, views.uniques += uniques))
|
||||
//Format values
|
||||
views.count = imports.format(views.count)
|
||||
views.uniques = imports.format(views.uniques)
|
||||
//Save results
|
||||
computed.plugins.traffic = {views}
|
||||
console.debug(`metrics/compute/${login}/plugins > traffic > success`)
|
||||
console.debug(JSON.stringify(computed.plugins.traffic))
|
||||
solve()
|
||||
}
|
||||
catch (error) {
|
||||
//Thrown when token has unsufficient permissions
|
||||
if (error.status === 403) {
|
||||
computed.plugins.traffic = {error:`Insufficient token rights`}
|
||||
console.debug(`metrics/compute/${login}/plugins > error > 403 (insufficient token rights)`)
|
||||
return solve()
|
||||
}
|
||||
//Generic error
|
||||
computed.plugins.traffic = {error:`An error occured`}
|
||||
console.debug(`metrics/compute/${login}/plugins > error`)
|
||||
console.debug(error)
|
||||
solve()
|
||||
}
|
||||
}))
|
||||
try {
|
||||
//Check if plugin is enabled and requirements are met
|
||||
if ((!enabled)||(!q.traffic))
|
||||
return null
|
||||
//Repositories
|
||||
const repositories = data.user.repositories.nodes.map(({name}) => name) ?? []
|
||||
//Get views stats from repositories
|
||||
const views = {count:0, uniques:0}
|
||||
const response = await Promise.all(repositories.map(async repo => await rest.repos.getViews({owner:login, repo})))
|
||||
//Compute views
|
||||
response.filter(({data}) => data).map(({data:{count, uniques}}) => (views.count += count, views.uniques += uniques))
|
||||
//Format values
|
||||
views.count = imports.format(views.count)
|
||||
views.uniques = imports.format(views.uniques)
|
||||
//Results
|
||||
return {views}
|
||||
}
|
||||
//Handle errors
|
||||
catch (error) {
|
||||
if (error.status === 403)
|
||||
throw {error:{message:`Insufficient token rights`}}
|
||||
console.debug(error)
|
||||
throw {error:{message:`An error occured`}}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user