-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
227 lines (198 loc) · 6.75 KB
/
Copy pathserver.js
File metadata and controls
227 lines (198 loc) · 6.75 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
const express = require('express');
const axios = require('axios');
const querystring = require('querystring');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
app.use(express.json());
app.use(express.static('public'));
const PORT = process.env.PORT || 8080;
const SPOTIFY_CLIENT_ID = process.env.SPOTIFY_CLIENT_ID;
const SPOTIFY_CLIENT_SECRET = process.env.SPOTIFY_CLIENT_SECRET;
const LINKEDIN_CLIENT_ID = process.env.LINKEDIN_CLIENT_ID;
const LINKEDIN_CLIENT_SECRET = process.env.LINKEDIN_CLIENT_SECRET;
const REDIRECT_URI = process.env.REDIRECT_URI || 'http://localhost:8080/callback';
const LINKEDIN_REDIRECT_URI = process.env.LINKEDIN_REDIRECT_URI || 'http://localhost:8080/linkedin/callback';
// Store tokens (in production, use a database)
let tokens = {
spotify: null,
linkedin: null
};
// Spotify Authorization
app.get('/login', (req, res) => {
const scope = 'user-read-currently-playing user-read-playback-state';
res.redirect('https://accounts.spotify.com/authorize?' +
querystring.stringify({
response_type: 'code',
client_id: SPOTIFY_CLIENT_ID,
scope: scope,
redirect_uri: REDIRECT_URI
}));
});
// Spotify Callback
app.get('/callback', async (req, res) => {
const code = req.query.code || null;
try {
const response = await axios.post('https://accounts.spotify.com/api/token',
querystring.stringify({
code: code,
redirect_uri: REDIRECT_URI,
grant_type: 'authorization_code'
}), {
headers: {
'Authorization': 'Basic ' + Buffer.from(SPOTIFY_CLIENT_ID + ':' + SPOTIFY_CLIENT_SECRET).toString('base64'),
'Content-Type': 'application/x-www-form-urlencoded'
}
});
tokens.spotify = {
access_token: response.data.access_token,
refresh_token: response.data.refresh_token,
expires_at: Date.now() + (response.data.expires_in * 1000)
};
res.redirect('/?spotify=connected');
} catch (error) {
console.error('Spotify auth error:', error.response?.data || error.message);
res.redirect('/?error=spotify_auth_failed');
}
});
// LinkedIn Authorization
app.get('/linkedin/login', (req, res) => {
const scope = 'w_member_social profile';
res.redirect('https://www.linkedin.com/oauth/v2/authorization?' +
querystring.stringify({
response_type: 'code',
client_id: LINKEDIN_CLIENT_ID,
redirect_uri: LINKEDIN_REDIRECT_URI,
scope: scope
}));
});
// LinkedIn Callback
app.get('/linkedin/callback', async (req, res) => {
const code = req.query.code || null;
try {
const response = await axios.post('https://www.linkedin.com/oauth/v2/accessToken',
querystring.stringify({
grant_type: 'authorization_code',
code: code,
redirect_uri: LINKEDIN_REDIRECT_URI,
client_id: LINKEDIN_CLIENT_ID,
client_secret: LINKEDIN_CLIENT_SECRET
}), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
tokens.linkedin = {
access_token: response.data.access_token,
expires_at: Date.now() + (response.data.expires_in * 1000)
};
res.redirect('/?linkedin=connected');
} catch (error) {
console.error('LinkedIn auth error:', error.response?.data || error.message);
res.redirect('/?error=linkedin_auth_failed');
}
});
// Refresh Spotify Token
async function refreshSpotifyToken() {
if (!tokens.spotify?.refresh_token) return false;
try {
const response = await axios.post('https://accounts.spotify.com/api/token',
querystring.stringify({
grant_type: 'refresh_token',
refresh_token: tokens.spotify.refresh_token
}), {
headers: {
'Authorization': 'Basic ' + Buffer.from(SPOTIFY_CLIENT_ID + ':' + SPOTIFY_CLIENT_SECRET).toString('base64'),
'Content-Type': 'application/x-www-form-urlencoded'
}
});
tokens.spotify.access_token = response.data.access_token;
tokens.spotify.expires_at = Date.now() + (response.data.expires_in * 1000);
return true;
} catch (error) {
console.error('Token refresh error:', error.message);
return false;
}
}
// Get Currently Playing
app.get('/api/now-playing', async (req, res) => {
if (!tokens.spotify) {
return res.status(401).json({ error: 'Not authenticated with Spotify' });
}
if (Date.now() >= tokens.spotify.expires_at) {
await refreshSpotifyToken();
}
try {
const response = await axios.get('https://api.spotify.com/v1/me/player/currently-playing', {
headers: {
'Authorization': `Bearer ${tokens.spotify.access_token}`
}
});
if (response.status === 204 || !response.data) {
return res.json({ is_playing: false });
}
const track = response.data.item;
res.json({
is_playing: response.data.is_playing,
track_name: track.name,
artist: track.artists.map(a => a.name).join(', '),
album: track.album.name,
album_art: track.album.images[0]?.url
});
} catch (error) {
console.error('Spotify API error:', error.response?.status, error.response?.data);
res.status(500).json({ error: 'Failed to fetch currently playing' });
}
});
// Post to LinkedIn
app.post('/api/post-to-linkedin', async (req, res) => {
if (!tokens.linkedin) {
return res.status(401).json({ error: 'Not authenticated with LinkedIn' });
}
const { text } = req.body;
try {
// Get LinkedIn user ID
const userResponse = await axios.get('https://api.linkedin.com/v2/userinfo', {
headers: {
'Authorization': `Bearer ${tokens.linkedin.access_token}`
}
});
const userId = userResponse.data.sub;
// Post to LinkedIn
const postResponse = await axios.post('https://api.linkedin.com/v2/ugcPosts', {
author: `urn:li:person:${userId}`,
lifecycleState: 'PUBLISHED',
specificContent: {
'com.linkedin.ugc.ShareContent': {
shareCommentary: {
text: text
},
shareMediaCategory: 'NONE'
}
},
visibility: {
'com.linkedin.ugc.MemberNetworkVisibility': 'PUBLIC'
}
}, {
headers: {
'Authorization': `Bearer ${tokens.linkedin.access_token}`,
'Content-Type': 'application/json',
'X-Restli-Protocol-Version': '2.0.0'
}
});
res.json({ success: true, post_id: postResponse.data.id });
} catch (error) {
console.error('LinkedIn post error:', error.response?.data || error.message);
res.status(500).json({ error: 'Failed to post to LinkedIn' });
}
});
// Check authentication status
app.get('/api/status', (req, res) => {
res.json({
spotify: !!tokens.spotify,
linkedin: !!tokens.linkedin
});
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});