-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
217 lines (182 loc) · 5.3 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
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
require('dotenv').config();
const axios = require('axios');
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const session = require('express-session');
const crypto = require('crypto');
const {
auth,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
updateProfile,
db,
setDoc,
doc,
getDoc
} = require('./firebaseConfig');
const generateSecretKey = () => {
return crypto.randomBytes(32).toString('hex');
};
const app = express();
const PORT = process.env.PORT || 3000;
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(session({
secret: generateSecretKey(),
resave: false,
saveUninitialized: true
}));
// Define routes
app.get('/', (req, res) => {
res.render('home');
});
app.get('/navbar', (req, res) => {
res.render('_navbar.ejs');
});
app.get('/search', (req, res) => {
res.render('search', { results: undefined });
});
app.post('/search', async (req, res) => {
const { query } = req.body;
try {
const response = await axios.get('http://ws.audioscrobbler.com/2.0/', {
params: {
method: 'track.search',
api_key: process.env.LASTFM_API_KEY,
format: 'json',
track: query
}
});
if (response.data?.results?.trackmatches?.track) {
let tracks = Array.isArray(response.data.results.trackmatches.track)
? response.data.results.trackmatches.track
: [response.data.results.trackmatches.track];
tracks = tracks.filter(track => track.name.toLowerCase().includes(query.toLowerCase()));
res.render('search', { results: tracks });
} else {
res.render('search', { results: [] });
}
} catch (error) {
console.error(error);
res.render('search', { results: [] });
}
});
app.get('/signup', (req, res) => {
res.render('signup', { error: null });
});
app.get('/login', (req, res) => {
res.render('login', { error: null });
});
app.post('/signup', async (req, res) => {
const { name, email, password, confirmPassword, terms } = req.body;
if (!terms) {
return res.render('signup', { error: 'You must agree to the terms and conditions.' });
}
if (password !== confirmPassword) {
return res.render('signup', { error: 'Passwords do not match.' });
}
try {
const userCredential = await createUserWithEmailAndPassword(auth, email, password);
await updateProfile(userCredential.user, { displayName: name });
await setDoc(doc(db, 'users', userCredential.user.uid), {
name: name,
email: email,
uid: userCredential.user.uid
});
res.redirect('/dashboard');
} catch (error) {
res.render('signup', { error: error.message });
}
});
app.get('/dashboard', async (req, res) => {
const currentUser = auth.currentUser;
if (currentUser) {
try {
const userRef = doc(db, 'users', currentUser.uid);
const userDoc = await getDoc(userRef);
if (userDoc.exists()) {
res.render('dashboard', { userName: userDoc.data().name });
} else {
res.render('dashboard', { userName: 'Guest' });
}
} catch (error) {
res.render('dashboard', { userName: 'Guest', error: error.message });
}
} else {
res.render('dashboard', { userName: 'Guest' });
}
});
app.get('/about', (req, res) => {
res.render('about'); // Renders the about.ejs view
});
app.post('/login', async (req, res) => {
const { email, password } = req.body;
try {
const userCredential = await signInWithEmailAndPassword(auth, email, password);
res.redirect('/dashboard');
} catch (error) {
res.render('login', { error: error.message });
}
});
app.post('/logout', (req, res) => {
req.session.destroy((err) => {
if (err) {
console.error('Error destroying session:', err);
return res.status(500).send('Internal Server Error');
}
res.redirect('/login');
});
});
// API routes
app.get('/api/music', async (req, res) => {
const { query } = req.query;
try {
let endpoint = 'chart.gettoptracks';
if (query) {
endpoint = 'track.search';
}
const response = await axios.get('http://ws.audioscrobbler.com/2.0/', {
params: {
method: endpoint,
api_key: process.env.LASTFM_API_KEY,
format: 'json',
...req.query
}
});
res.json(response.data);
} catch (error) {
console.error('Error fetching music data:', error);
res.status(500).json({ error: 'Error fetching music data' });
}
});
app.post('/api/music', async (req, res) => {
const { query } = req.body;
try {
let endpoint = 'chart.gettoptracks';
if (query) {
endpoint = 'track.search';
}
const response = await axios.get('http://ws.audioscrobbler.com/2.0/', {
params: {
method: endpoint,
api_key: process.env.LASTFM_API_KEY,
format: 'json',
...req.body
}
});
res.json(response.data);
} catch (error) {
console.error('Error fetching music data:', error);
res.status(500).json({ error: 'Error fetching music data' });
}
});
if (process.env.NODE_ENV !== 'production') {
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
}
module.exports = app;