-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.ts
189 lines (160 loc) · 5.37 KB
/
server.ts
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
178
179
180
181
182
183
184
185
186
187
188
189
import express from 'express';
import compression from 'compression';
import sslifyEnforce from 'express-sslify';
import path from 'path';
import axios from 'axios';
import url from 'url';
import process from 'process';
import KeyV from 'keyv';
const app = express();
app.use(compression());
const env = process.env.NODE_ENV || 'development';
if (env === 'production') {
app.use(sslifyEnforce.HTTPS({ trustProtoHeader: true }));
}
const publicDir = process.env.DIST_DIR || __dirname + '/public';
app.use(express.static(publicDir));
app.get('*', (_req, res) => {
res.sendFile(path.resolve(publicDir, 'static', 'index.html'));
});
const soundcloudClientId = process.env.SOUNDCLOUD_CLIENT_ID + '';
const soundcloudClientSecret = process.env.SOUNDCLOUD_CLIENT_SECRET + '';
app.use(express.json());
app.post('/api/resolve', async (req, res) => {
try {
if (req.body.constructor !== Object || Object.keys(req.body).length === 0) {
return res.status(400).json({ error: 'Invalid JSON' });
}
if (
req.body.url === undefined ||
req.body.url === null ||
!(typeof req.body.url === 'string' || req.body.url instanceof String)
) {
return res.status(400).json({ error: 'Missing url parameter' });
}
const urlToResolve = req.body.url + '';
const resolved = await new SoundcloudApi(
soundcloudClientId,
soundcloudClientSecret
).resolve(urlToResolve);
res.json({
stream_url: resolved.streamUrl,
url: resolved.url,
title: resolved.title,
artwork: resolved.artwork,
user: resolved.user,
});
} catch (e: unknown) {
if (e instanceof SoundcloudApiHttpError) {
res.sendStatus(e.status);
} else {
res.sendStatus(500);
}
}
});
const keyv = new KeyV({ namespace: 'vizl' });
const port = process.env.PORT || 8081;
const server = app.listen(port, () => {
console.log('Express: listening on port ' + port);
});
const shutdown = (signal: NodeJS.Signals) => {
console.log(`${signal} received. Starting shutdown...`);
server.close(() => {
console.log('Express: HTTP server closed');
console.log('Shutdown complete. Exiting...');
process.exit(0);
});
};
process.on('SIGINT', (signal) => shutdown(signal));
process.on('SIGTERM', (signal) => shutdown(signal));
const SOUNDCLOUD_API_BASE_URL = 'https://api.soundcloud.com';
const SOUNDCLOUD_OAUTH_TOKEN_API_URL = `${SOUNDCLOUD_API_BASE_URL}/oauth2/token`;
const SOUNDCLOUD_RESOLVE_API_URL = `${SOUNDCLOUD_API_BASE_URL}/resolve`;
const SOUNDCLOUD_ACCESS_TOKEN_KEY = 'soundcloud-access-token';
class SoundcloudApiHttpError extends Error {
constructor(public status: number) {
super('Soundcloud API error');
// Set the prototype explicitly.
Object.setPrototypeOf(this, SoundcloudApiHttpError.prototype);
}
}
class SoundcloudApi {
accessToken: string | null = null;
constructor(private clientId: string, private clientSecret: string) {}
// Get the resolved streaming URL for the link provided
public async resolve(trackUrl: string): Promise<{
streamUrl: string;
url: string;
title: string;
artwork: string | null;
user: { name: string; profile: string };
}> {
await this.auth();
const resolveUrl = new URL(SOUNDCLOUD_RESOLVE_API_URL);
resolveUrl.searchParams.append('url', trackUrl);
const resolvedRes = await axios.get(resolveUrl.toString(), {
headers: { Authorization: `OAuth ${this.accessToken}` },
validateStatus: (_s) => true,
});
if (resolvedRes.status !== 200) {
throw new SoundcloudApiHttpError(resolvedRes.status);
}
const trackData = resolvedRes.data;
const redirectRes = await axios.get(trackData.stream_url, {
headers: { Authorization: `OAuth ${this.accessToken}` },
validateStatus: (_s) => true,
maxRedirects: 0,
});
if (
redirectRes.status !== 302 ||
!redirectRes.data.location ||
(redirectRes.data.location + '').length === 0
) {
throw new SoundcloudApiHttpError(redirectRes.status);
}
return {
streamUrl: redirectRes.data.location,
url: trackData.permalink_url,
title: trackData.title,
artwork: trackData.artwork_url ?? null,
user: {
name: trackData.user.username,
profile: trackData.user.permalink_url,
},
};
}
// Returns access token from client credentials flow
private async auth() {
if (this.accessToken !== null) {
return;
}
let accessToken = await keyv.get(SOUNDCLOUD_ACCESS_TOKEN_KEY);
if (accessToken === null || accessToken === undefined) {
const res = await axios.post(
SOUNDCLOUD_OAUTH_TOKEN_API_URL,
new url.URLSearchParams({
client_id: this.clientId,
client_secret: this.clientSecret,
grant_type: 'client_credentials',
}),
{ validateStatus: (_s) => true }
);
if (res.status !== 200) {
throw new SoundcloudApiHttpError(res.status);
}
accessToken = res.data.access_token + '';
const expireSeconds = parseInt(res.data.expires_in);
if (!isNaN(expireSeconds)) {
await keyv.set(
SOUNDCLOUD_ACCESS_TOKEN_KEY,
accessToken,
Math.floor(expireSeconds / 2) * 1000
);
}
console.log('SoundcloudApi: set new access token in cache');
} else {
console.log('SoundcloudApi: found existing access token in cache');
}
this.accessToken = accessToken;
}
}