forked from madrilene/eleventy-excellent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreateSpotifyPost.js
104 lines (84 loc) · 2.98 KB
/
createSpotifyPost.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
import dotenv from 'dotenv';
import { promises as fs } from 'fs';
import path from 'path';
import axios from 'axios';
import { createInterface } from 'readline';
import { fileURLToPath } from 'url';
dotenv.config();
const clientId = process.env.SPOTIFY_CLIENT_ID;
const clientSecret = process.env.SPOTIFY_CLIENT_SECRET;
const rl = createInterface({
input: process.stdin,
output: process.stdout
});
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
async function getSpotifyToken() {
const response = await axios.post('https://accounts.spotify.com/api/token',
'grant_type=client_credentials', {
headers: {
'Authorization': 'Basic ' + Buffer.from(clientId + ':' + clientSecret).toString('base64'),
'Content-Type': 'application/x-www-form-urlencoded'
}
});
return response.data.access_token;
}
async function getTrackInfo(trackId, token) {
const response = await axios.get(`https://api.spotify.com/v1/tracks/${trackId}`, {
headers: { 'Authorization': 'Bearer ' + token }
});
return response.data;
}
async function createSpotifyPost() {
try {
const lookUpInput = await new Promise(resolve => {
rl.question('Please paste the Spotify embed code or track URL: ', resolve);
});
let trackId;
// Match patterns for different Spotify formats
const patterns = [
/spotify:track:(\w+)/, // URI format
/https:\/\/open\.spotify\.com\/track\/(\w+)/, // URL format
/https:\/\/open\.spotify\.com\/embed\/track\/(\w+)/, // Embed URL format
/src="https:\/\/open\.spotify\.com\/embed\/track\/(\w+)/ // iFrame embed format
];
for (const pattern of patterns) {
const match = lookUpInput.match(pattern);
if (match) {
trackId = match[1];
break;
}
}
if (!trackId) {
console.log("Invalid embed code or URL. Unable to extract track ID.");
return;
}
console.log(`Extracted track ID: ${trackId}`);
const embedCode = `<iframe style="border-radius:12px" src="https://open.spotify.com/embed/track/${trackId}" width="100%" height="352" frameBorder="0" allowfullscreen="" allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture" loading="lazy"></iframe>`;
const token = await getSpotifyToken();
const trackInfo = await getTrackInfo(trackId, token);
const artist = trackInfo.artists[0].name;
const title = trackInfo.name;
const today = new Date().toISOString().split('T')[0];
const filename = `${today} music.md`;
const filepath = path.join("src", 'posts', filename);
const content = `---
title: "${artist} - ${title}"
date: ${today}
description: "Today's music"
tags:
- posts
- music
---
${embedCode}
`;
await fs.mkdir('posts', { recursive: true });
await fs.writeFile(filepath, content, 'utf-8');
console.log(`Post created: ${filepath}`);
} catch (error) {
console.error('An error occurred:', error.message);
} finally {
rl.close();
}
}
createSpotifyPost();