-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
236 lines (183 loc) · 6.04 KB
/
server.js
File metadata and controls
236 lines (183 loc) · 6.04 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
const express = require("express");
const path = require("path");
const fs = require("fs");
const app = express();
const PORT = process.env.PORT || 3000;
const TMDB_TOKEN = process.env.TMDB_TOKEN;
/* ================= MIDDLEWARE ================= */
app.use(express.json());
app.use(express.static(path.join(__dirname, "public")));
/* ================= CACHE ================= */
const cache = new Map();
/* ================= TMDB ================= */
async function tmdbEnrich(films, lang = "pt-BR") {
const enriched = [];
for (const f of films) {
const url =
`https://api.themoviedb.org/3/search/movie` +
`?query=${encodeURIComponent(f.title)}` +
`&language=${lang}`;
const r = await fetch(url, {
headers: {
Authorization: `Bearer ${TMDB_TOKEN}`,
Accept: "application/json"
}
});
const j = await r.json();
if (!j.results) continue;
const match = j.results.find(r => {
if (!r.poster_path || !r.release_date) return false;
const y = parseInt(r.release_date.slice(0, 4));
return f.year ? Math.abs(y - f.year) <= 1 : true;
});
if (!match) continue;
enriched.push({
title: match.title,
year: match.release_date.slice(0, 4),
poster: `https://image.tmdb.org/t/p/w500${match.poster_path}`
});
}
return enriched;
}
/* ================= USER (LETTERBOXD) ================= */
app.get("/api/user/:user", async (req, res) => {
const user = req.params.user.toLowerCase();
const key = `user:${user}`;
if (cache.has(key)) return res.json(cache.get(key));
const films = [];
let page = 1;
while (page <= 20) {
const url = `https://letterboxd.com/${user}/films/page/${page}/`;
const html = await fetch(url).then(r => r.text());
const items = html.match(/data-item-full-display-name="([^"]+)"/g);
if (!items) break;
for (const raw of items) {
const m = raw.match(/="(.+?)"/)[1];
const y = m.match(/\((\d{4})\)/);
films.push({
title: m.replace(/\s*\(\d{4}\)/, "").trim(),
year: y ? parseInt(y[1]) : null
});
}
page++;
}
const enriched = await tmdbEnrich(films);
cache.set(key, enriched);
res.json(enriched);
});
/* ================= LISTAS LOCAIS (FILMES) ================= */
app.get("/api/list/:key", (req, res) => {
try {
const file = path.join(__dirname, "data", `${req.params.key}.json`);
const json = JSON.parse(fs.readFileSync(file, "utf8"));
res.json(json.films);
} catch {
res.status(404).json({ error: "Lista não encontrada" });
}
});
/* ================= SCRAPER MANUAL (ADMIN FILMES) ================= */
app.get("/api/list", async (req, res) => {
const listUrl = req.query.url;
if (!listUrl) return res.status(400).json([]);
try {
const films = [];
let page = 1;
const MAX_PAGES = 20;
while (page <= MAX_PAGES) {
const url = `${listUrl}page/${page}/`;
const html = await fetch(url).then(r => r.text());
const items = html.match(/data-item-full-display-name="([^"]+)"/g);
if (!items) break;
for (const raw of items) {
const m = raw.match(/="(.+?)"/)[1];
const y = m.match(/\((\d{4})\)/);
films.push({
title: m.replace(/\s*\(\d{4}\)/, "").trim(),
year: y ? parseInt(y[1]) : null
});
}
page++;
}
const enriched = await tmdbEnrich(films);
res.json(enriched);
} catch {
res.status(500).json([]);
}
});
/* ================= MUSIC API ================= */
app.get("/api/music/artist", async (req, res) => {
const name = req.query.name;
if (!name) return res.status(400).json({ error: "missing name" });
try {
const url =
"https://musicbrainz.org/ws/2/artist" +
`?query=${encodeURIComponent(name)}` +
"&fmt=json&limit=1";
const r = await fetch(url, {
headers: {
"User-Agent": "MusicDuel/1.0 ( contact@example.com )"
}
});
const j = await r.json();
const a = j.artists?.[0];
if (!a) return res.json(null);
res.json({
name: a.name,
country: a.country || null,
type: a.type || null,
id: a.id
});
} catch {
res.status(500).json(null);
}
});
app.get("/api/music/artist-with-album", async (req, res) => {
const name = req.query.name;
if (!name) return res.json(null);
try {
const artistRes = await fetch(
`https://musicbrainz.org/ws/2/artist?query=${encodeURIComponent(name)}&fmt=json&limit=1`,
{ headers: { "User-Agent": "MusicDuel/1.0" } }
);
const artistJson = await artistRes.json();
const artist = artistJson.artists?.[0];
if (!artist) return res.json(null);
const relRes = await fetch(
`https://musicbrainz.org/ws/2/release-group?artist=${artist.id}&type=album&limit=5&fmt=json`,
{ headers: { "User-Agent": "MusicDuel/1.0" } }
);
const relJson = await relRes.json();
const album = relJson["release-groups"]?.[0];
const cover = album
? `https://coverartarchive.org/release-group/${album.id}/front-250`
: null;
res.json({
name: artist.name,
id: artist.id,
country: artist.country || null,
type: artist.type || null,
album: album
? {
title: album.title,
year: album["first-release-date"]?.slice(0, 4) || null,
cover
}
: null
});
} catch {
res.json(null);
}
});
/* ================= MUSIC LISTAS LOCAIS ================= */
app.get("/api/music/list/:key", (req, res) => {
try {
const file = path.join(__dirname, "data/music", `${req.params.key}.json`);
res.json(JSON.parse(fs.readFileSync(file, "utf8")));
} catch {
res.status(404).json({ error: "Lista não encontrada" });
}
});
/* ================= START ================= */
app.listen(PORT, "0.0.0.0", () => {
console.log("FilmDuel rodando na porta", PORT);
});