-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdropsonic.js
287 lines (249 loc) · 8.32 KB
/
dropsonic.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
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
require('dotenv').config();
const fastify = require('fastify')({ logger: false });
fastify.register(require('@fastify/jwt'), { secret: 'superbbq' });
fastify.register(require('@fastify/leveldb'), { name: 'authdb' });
fastify.register(require('@fastify/auth'));
// fastify.register(require('@fastify/cors'));
// fastify.register(require('@fastify/autoload'), {
// dir: path.join(__dirname, 'routes'),
// });
fastify.after(() => {
fastify.route({
method: 'POST',
url: '/register',
schema: {
body: {
type: 'object',
properties: {
user: { type: 'string' },
password: { type: 'string' },
},
required: ['user', 'password'],
},
},
handler: (req, reply) => {
req.log.info('Creating new user');
fastify.level.authdb.put(req.body.user, req.body.password, onPut);
function onPut(err) {
if (err) return reply.send(err);
fastify.jwt.sign(req.body, onToken);
}
function onToken(err, token) {
if (err) return reply.send(err);
req.log.info('User created');
reply.send({ token });
}
},
});
fastify.route({
method: 'GET',
url: '/auth',
preHandler: fastify.auth([fastify.verifyJWTandLevelDB]),
handler: (req, reply) => {
req.log.info('Auth route');
reply.send({ hello: 'world' });
},
});
fastify.route({
method: 'POST',
url: '/auth-multiple',
preHandler: fastify.auth([
// Only one of these has to pass
fastify.verifyJWTandLevelDB,
fastify.verifyUserAndPassword,
]),
handler: (req, reply) => {
fastify.level.authdb.get(req.body.user, req.body.password, onGet);
function onGet(err) {
if (err) return reply.send(err);
fastify.jwt.sign(req.body, onToken);
}
function onToken(err, token) {
if (err) return reply.send(err);
req.log.info('User created');
reply.send({ token });
}
// req.log.info('Auth route');
// reply.send({ hello: 'world' });
},
});
fastify.get('/artist', async (request, reply) => {
reply.send({ artist_list: cachedInformation.artist_list });
});
fastify.get('/refresh-artist', async (request, reply) => {
return getFolders()
.then((response) => {
cachedInformation.artist_list = response;
reply.send({ artist_list: response });
})
.catch((error) => {
reply.send({ error: error });
});
});
fastify.get('/album', async (request, reply) => {
return getFolders(request.headers.artist)
.then((response) => {
reply.send({ album_list: response });
})
.catch((error) => {
reply.send({ error: error });
});
});
fastify.get('/tracklist', async (request, reply) => {
return getFolders(request.headers.artist, request.headers.album, true)
.then((response) => {
reply.send({ tracklist: response });
})
.catch((error) => {
reply.send({ error: error });
});
});
fastify.get('/track', async (request, reply) => {
return getFile(request.headers.path)
.then((response) => {
reply.type('application/octet-stream');
reply.send(response);
})
.catch((error) => {
reply.send({ error: error });
});
});
fastify.get('/track-info', async (request, reply) => {
getFileInfo(request.headers.path)
.then((fileInfo) => {
reply.header('Content-Type', 'application/json; charset=utf-8');
reply.send({ file_info: fileInfo });
})
.catch((error) => {
reply.send({ error: error });
});
});
});
const { Dropbox } = require('dropbox');
const dropbox = new Dropbox({
clientId: process.env.client_id,
clientSecret: process.env.client_secret,
refreshToken: process.env.refresh_token,
});
const cachedInformation = {};
fastify.decorate('verifyJWTandLevelDB', verifyJWTandLevelDB);
fastify.decorate('verifyUserAndPassword', verifyUserAndPassword);
function verifyJWTandLevelDB(request, reply, done) {
const jwt = this.jwt;
const level = this.level.authdb;
if (request.body && request.body.failureWithReply) {
reply.code(401).send({ error: 'Unauthorized' });
return done(new Error());
}
if (!request.raw.headers.auth) {
return done(new Error('Missing token header'));
}
jwt.verify(request.raw.headers.auth, onVerify);
function onVerify(err, decoded) {
if (err || !decoded.user || !decoded.password) {
return done(new Error('Token not valid'));
}
level.get(decoded.user, onUser);
function onUser(err, password) {
if (err) {
if (err.notFound) {
return done(new Error('Token not valid'));
}
return done(err);
}
if (!password || password !== decoded.password) {
return done(new Error('Token not valid'));
}
done();
}
}
}
function verifyUserAndPassword(request, reply, done) {
const level = this.level.authdb;
if (!request.body || !request.body.user) {
return done(new Error('Missing user in request body'));
}
level.get(request.body.user, onUser);
function onUser(err, password) {
if (err) {
if (err.notFound) {
return done(new Error('Password not valid'));
}
return done(err);
}
if (!password || password !== request.body.password) {
return done(new Error('Password not valid'));
}
done();
}
}
function getFolders(artist, album) {
let fileList = [];
let searchPath = `${artist ? `${album ? `/music/${artist}/${album}` : `/music/${artist}`}` : '/music'}`;
function getMoreFolders(cursor) {
return dropbox
.filesListFolderContinue({ cursor: cursor })
.then((response) => {
if (response.result.entries) fileList = fileList.concat(response.result.entries);
if (response.result.has_more) {
return getMoreFolders(response.result.cursor);
} else {
return fileList;
}
})
.catch((err) => {
console.log(err);
});
}
return dropbox
.filesListFolder({ path: searchPath })
.then((response) => {
if (response.result.entries) fileList = fileList.concat(response.result.entries);
if (response.result.has_more) {
return getMoreFolders(response.result.cursor);
} else {
return fileList;
}
})
.catch((err) => {
console.log(err);
});
}
function getFile(searchPath) {
return dropbox
.filesDownload({ path: searchPath })
.then((response) => {
return response.result.fileBinary;
})
.catch((err) => {
console.log(err);
});
}
function getFileHeader(searchPath) {
return dropbox
.filesDownload({ path: searchPath })
.then((response) => {
return response;
})
.catch((err) => {
console.log(err);
});
}
getFolders()
.then((response) => {
cachedInformation.artist_list = response;
console.log('artists loaded!');
fastify.listen(
{ port: process.env.SERVER_PORT || 3000, host: process.env.SERVER_HOST || '0.0.0.0' },
(err, address) => {
if (err) {
console.log(err);
process.exit(1);
}
console.info(`Server listening on ${address}`);
}
);
})
.catch((error) => {
reply.send({ error: error });
});