-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
76 lines (66 loc) · 2.8 KB
/
index.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
const puppeteer = require('puppeteer');
const fs = require('fs-extra');
const path = require('path');
module.exports = async function (userName, password, artistId, headless) {
userName = userName || process.env.SPOTIFY_USER_NAME;
if (!userName) {
throw new Error('The user name must be passed in as the first command line argument or in the SPOTIFY_USER_NAME environment variable.');
}
password = password || process.env.SPOTIFY_PASSWORD;
if (!password) {
throw new Error('The password must be passed in as the first command line argument or in the SPOTIFY_PASSWORD environment variable.');
}
artistId = artistId || process.env.SPOTIFY_ARTIST_ID;
if (!artistId) {
throw new Error('The artist ID must be passed in as the first command line argument or in the SPOTIFY_ARTIST_ID environment variable.');
}
const browser = await puppeteer.launch({ headless });
const [page] = await browser.pages();
await page.goto('https://accounts.spotify.com/en/login/');
await page.type('#login-username', userName);
await page.type('#login-password', password);
await page.click('#login-button');
await page.waitForNavigation();
await page.waitForSelector('.user-details');
await page.goto(`https://artists.spotify.com/c/artist/${artistId}/music/songs?time-filter=all`);
await page.waitForSelector('tbody > tr > td');
let data = await page.$$eval('tbody > tr', trs => trs.map(tr => [...tr.querySelectorAll('td')].slice(1, -1).map(td => td.title)));
await browser.close();
data = data.reduce((a, c) => {
a[c[0]] = Number(c[2].replace(/[^\d]/g, ''));
return a;
}, {});
let email = '<p>Black Holes Spotify performance:</p>';
const dataJsonFilePath = path.join(__dirname, 'data.json');
try {
const { data: knownData } = await fs.readJson(dataJsonFilePath);
const keys = Object.keys(data);
email += '<ul>\n';
for (const key of keys) {
switch (Math.sign(data[key] - knownData[key])) {
case -1: {
email += `<li>${key} decreased by <b>${knownData[key] - data[key]}</b> to ${data[key]}</li>\n`;
break;
}
case 0: {
email += `<li>${key} remains at ${data[key]}</li>\n`;
break;
}
case 1: {
email += `<li>${key} increased by <b>${data[key] - knownData[key]}</b> to ${data[key]}</li>\n`;
break;
}
}
}
email += '</ul>\n';
}
catch (error) {
// Ignore no data being known yet
}
await fs.writeJson(dataJsonFilePath, { stamp: new Date(), data }, { spaces: 2 });
const indexEmlFilePath = path.join(__dirname, 'index.eml');
await fs.writeFile(indexEmlFilePath, email);
};
if (process.cwd() === __dirname) {
module.exports(process.argv[2], process.argv[3], process.argv[4], false);
}