-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.js
More file actions
368 lines (344 loc) · 11.3 KB
/
database.js
File metadata and controls
368 lines (344 loc) · 11.3 KB
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
import * as firebase from 'firebase';
import axios from 'axios';
export default class Database {
static savePlaylistToDatabase(playlists, providerId) { // OB/TL: naming here
// OB/TL: be wary when you're not returning anything
const currentUser = firebase.auth().currentUser;
playlists.forEach(playlist => {
let newSong = {};
playlist.songs.forEach((song, index) => {
this.findOrCreateSong(song, providerId); // <= OB/TL non-blocking
newSong[index] = {};
newSong[index].artist = song.artist;
newSong[index].title = song.title;
// newSong[index].image = song.image;
});
const newPlaylistId = firebase.database().ref('playlists').push().key;
this.addPlaylistToUser(newPlaylistId);
firebase.database().ref(`playlists/${newPlaylistId}`).set({
title: playlist.name,
creator: currentUser.uid,
songs: newSong,
displayName: currentUser.displayName,
type: providerId
});
});
}
static getAllUsers() {
return firebase.database().ref('/users').once('value');
}
static getAllFriends() {
let user = firebase.auth().currentUser;
return firebase.database().ref(`/users/${user.uid}/friends`).once('value');
// OB/TL: consider using `.on` for realtime updates!
// OB/TL: consider chaining off this promise to resolve to the snapshot value
}
static getPendingFriends() {
let user = firebase.auth().currentUser;
return firebase.database().ref(`/users/${user.uid}/pending`).once('value');
}
static requestFriend(recievingUser, sendBack) {
// OB/TL: watch out, no return value
let user = firebase.auth().currentUser;
firebase
.database()
.ref(`/users/${recievingUser}/pending/${user.uid}`)
.set(true);
if (!sendBack)
firebase
.database()
.ref(`/users/${user.uid}/sent/${recievingUser}`)
.set(true);
}
static getUserFromId(uid) {
return firebase.database().ref(`/users/${uid}`).once('value');
}
static addPlaylistToUser(playlistId) {
let user = firebase.auth().currentUser;
firebase
.database()
.ref(`/users/${user.uid}/playlists/${playlistId}`)
.set('original'); // <= OB/TL: might want to set to true/false for performance
}
//get playlist from id
static getPlaylistFromId(pid) {
return Promise.resolve( // OB/TL: `Promise.resolve` unecessary her
firebase.database().ref(`/playlists/${pid}`).once('value')
);
}
//get pending playlists
static getSharedPlaylists() {
let user = firebase.auth().currentUser;
return firebase
.database()
.ref(`/users/${user.uid}/sharedPlaylists`)
.once('value');
}
//the pending folder
static sharePlaylistWithFriend(playlistId, friendId) {
firebase
.database()
.ref(`/playlists/${playlistId}/sharedWith/${friendId}`)
.set(true);
firebase
.database()
.ref(`/users/${friendId}/sharedPlaylists/${playlistId}`)
.set(true);
}
//add playlist from pending folder to playlists folder and remove it from the pending folder
static addPlaylistFromPending(playlistId) {
let user = firebase.auth().currentUser;
firebase
.database()
.ref(`/users/${user.uid}/sharedPlaylists/${playlistId}`)
.remove();
firebase
.database()
.ref(`/users/${user.uid}/playlists/${playlistId}`)
.set('shared');
}
static unfollowPlaylist(playlistId) {
let user = firebase.auth().currentUser;
firebase
.database()
.ref(`/users/${user.uid}/sharedPlaylists/${playlistId}`)
.remove();
firebase
.database()
.ref(`/playlists/${playlistId}/sharedWith/${user.uid}`)
.remove();
}
static addFriendFromPending(friend) {
let user = firebase.auth().currentUser;
firebase.database().ref(`/users/${user.uid}/pending/${friend}`).remove();
firebase
.database()
.ref(`/users/${friend}/username`)
.once('value', function(snap) {
firebase
.database()
.ref(`/users/${user.uid}/friends/${friend}`)
.set(snap.val());
});
this.requestFriend(friend, true);
}
static rejectFriendFromPending(friend) {
let user = firebase.auth().currentUser;
firebase.database().ref(`/users/${user.uid}/pending/${friend}`).remove();
}
static deleteFriend(friend) {
let user = firebase.auth().currentUser;
firebase.database().ref(`/users/${user.uid}/friends/${friend}`).remove();
firebase.database().ref(`/users/${friend}/friends/${user.uid}`).remove();
}
static ignoreMe() { // OB/TL: dead code!
let user = firebase.auth().currentUser;
firebase
.database()
.ref(`/users/${user.uid}/pending`)
.on('child_added')
.then(snapshot => {
let pending = snapshot.val();
// OB/TL: nested promise chains
firebase
.database()
.ref(`/users/${user.uid}/sent`)
.once('value', function(sentSnap) {
let matches = _.intersection(sentSnap.val(), pending);
if (matches) {
matches.forEach(match => {
firebase
.database()
.ref(`/users/${user.uid}/friends/${match}`)
.set(true);
firebase
.database()
.ref(`/users/${user.uid}/pending/${match}`)
.remove();
firebase
.database()
.ref(`/users/${user.uid}/sent/${match}`)
.remove();
});
}
});
});
}
// OB/TL: dead code
static saveApplePlaylists(playlists, providerId) {
playlists.forEach(playlist => {
let newSong = {};
playlist.songs.forEach((song, index) => {
this.findOrCreateSong(song, providerId);
newSong[index] = {};
newSong[index].artist = song.artist;
newSong[index].title = song.title;
});
const newPlaylistId = firebase.database().ref('playlists').push().key;
firebase.database().ref(`playlists/${newPlaylistId}`).set({
title: playlist.name,
creator: 'Olivia',
songs: newSong
});
});
}
static deleteAllUserPlaylists(userId, type) {
firebase
.database()
.ref(`playlists`)
.orderByChild('creator')
.equalTo(userId)
.once('value')
.then(playlists => {
playlists.forEach(playlist => {
let key = playlist.key
if(playlist.val().type == type) {
firebase.database().ref(`playlists/${key}`).remove();
firebase.database().ref(`users/${userId}/playlists/${key}`).remove();
}
});
});
}
static getPlaylist(playlist, userId) {
return firebase.database().ref(`playlists/`).on();
}
static saveMultiPlaylists(playlists, providerId) {
// OB/TL: global? use let or const (or var)
for (playlistName in playlists) {
if (playlists.hasOwnProperty(playlistName)) {
const playlist = playlists[playlistName];
this.savePlaylist(playlist, playlistName, providerId);
}
}
}
static savePlaylist(playlist, playlistName, providerId) {
let newSong = {};
playlist.forEach((fetchSong, idx) => {
this.findOrCreateSong(fetchSong, providerId);
newSong[idx] = {};
newSong[idx].artist = fetchSong.artist;
newSong[idx].title = fetchSong.title;
});
const newPlaylistId = firebase.database().ref('playlists').push().key;
firebase
.database()
.ref(`users/${this.getCurrentUser()}/playlists`)
.once('value')
.set({
[newPlaylistId]: true
});
firebase.database().ref(`playlists/${newPlaylistId}`).set({
title: playlistName,
creator: this.getCurrentUser(),
songs: newSong
});
}
static async findOrCreateSong(fetchSong, providerId) {
try {
const address = firebase
.database()
.ref(
`songs/${this.getUrlPath(fetchSong.title)}/${this.getUrlPath(
fetchSong.artist
)}`
);
const dataSnapshot = await address.once('value');
if (!dataSnapshot.val()) {
await address.set({
[providerId]: fetchSong.id
});
} else {
if (!dataSnapshot.hasChild(providerId)) {
await address.set({
[providerId]: fetchSong.id
});
}
}
} catch (err) {
console.log(err);
alert(err);
// OB/TL: maybe toast
}
}
static getUrlPath(str) {
return encodeURIComponent(str).replace(/\./g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
static getNameFromUrlPath(url) {
return decodeURIComponent(url);
}
static databasePlaylistToSpotify(databasePlaylistId) {
firebase.auth().onAuthStateChanged(user => {
if (user) {
let id = user.id;
let userToken = user.accessToken;
let firedata = firebase
.database()
.ref(`playlists/${databasePlaylistId}`);
let external = [];
// OB/TL: possible control flow / async issues in this function
// OB/TL: flatten promise chains, consider splitting into multiple functions
firedata.on('value', function(snapshot) {
const playlist = snapshot.val();
console.log('Importing: ', playlist);
playlist.songs.forEach(song => external.push(song));
let promises = external.map(song =>
axios.post(
'https://us-central1-hum-app.cloudfunctions.net/getSongId/',
{
title: `${song.title}`,
artist: `${song.artist}`,
service: 'spotifyId',
userToken: `${userToken}`
},
{
headers: {
'Content-Type': 'application/json'
}
}
)
);
Promise.all(promises).then(values => {
let final = values.map(value => value.data);
console.log('URIs: ', final);
axios
.post(
`https://api.spotify.com/v1/users/${id}/playlists`,
`{\"name\":\"A New Hum Playlist\", \"public\":false, \"description\":\"A Hum playlist created by Apple Music\"}`,
{
headers: {
Authorization: `Bearer ${userToken}`,
'Content-Type': 'application/json'
}
}
)
.then(response => {
let playlistID = response.data.id;
axios
.post(
`https://api.spotify.com/v1/users/${id}/playlists/${playlistID}/tracks`,
{ uris: final },
{
headers: {
Authorization: `Bearer ${userToken}`,
'Content-Type': 'application/json'
}
}
)
.then(response => console.log('Import successful'))
.catch(error =>
console.log('Error while importing playlist: ', error)
);
})
.catch(error =>
console.log('Error while creating new playlist: ', error)
);
});
});
} else {
console.log('No user is signed in');
}
});
}
}