forked from 4gray/iptvnator-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
317 lines (289 loc) · 8.99 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
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
const express = require("express");
const app = express();
const parser = require("iptv-playlist-parser");
const epgParser = require("epg-parser");
const axios = require("axios");
const cors = require("cors");
const zlib = require("zlib");
const MongoDBService = require('./mongo-db.service');
const isDev = process.env.NODE_ENV === "dev";
const originUrl = process.env.CLIENT_URL
? process.env.CLIENT_URL
: isDev
? "http://localhost:4200"
: "https://iptvnator.vercel.app";
console.log(`Development mode: ${isDev}`);
console.log(`Origin URL: ${originUrl}`);
const mongoUri = isDev ? "mongodb://localhost:27017/iptvnator" : process.env.MONGO_URI || "";
const dbName = isDev ? "iptvnator" : process.env.MONGO_DB_NAME || "iptvnator";
const collectionName = isDev ? "playlists" : process.env.MONGO_COLLECTION_NAME || "playlists";
let databaseService;
if (!mongoUri || !dbName || !collectionName) {
console.log("MongoDB not enabled: Missing configuration variables.");
} else {
console.log(`MongoDB enabled: dbName: ${dbName}, mongoUri: ${mongoUri}, collectionName: ${collectionName}`);
databaseService = new MongoDBService(mongoUri, dbName, collectionName);
}
const corsOptions = {
origin: originUrl,
optionsSuccessStatus: 200,
};
app.use(express.json());
app.use(cors(corsOptions));
const https = require("https");
const agent = new https.Agent({
rejectUnauthorized: false,
});
app.get("/", (req, res) => res.send("Hello world"));
app.get("/parse", cors(corsOptions), async (req, res) => {
const { url } = req.query;
if (isDev) console.log(url);
if (!url) return res.status(400).send("Missing url");
const result = await handlePlaylistParse(url);
if (result.status) {
return res.status(result.status).send(result.message);
}
return res.send(result);
});
app.get("/parse-xml", cors(corsOptions), async (req, res) => {
const { url } = req.query;
console.log(url);
if (!url) return res.status(400).send("Missing url");
const result = await fetchEpgDataFromUrl(url);
if (result.status === 500) {
return res.status(result.status).send(result.message);
}
return res.send(result);
});
app.get("/xtream", cors(corsOptions), async (req, res) => {
const xtreamApiPath = "/player_api.php";
axios
.get(req.query.url + xtreamApiPath, {
params: req.query ?? {},
})
.then((result) => {
return res.send({
payload: result.data,
action: req.query?.action,
});
})
.catch((err) => {
return res.send({
message: err.response?.statusText ?? "Error: not found",
status: err.response?.status ?? 404,
});
});
});
// New route to add multiple playlists
app.post("/addManyPlaylists", cors(corsOptions), async (req, res) => {
try {
const playlists = req.body;
const result = await databaseService.insertMany(playlists);
res.status(200).send(result);
} catch (error) {
res.status(500).send({ error: 'Error adding multiple playlists to MongoDB' });
}
});
// New route to insert data into MongoDB
app.post("/addPlaylist", cors(corsOptions), express.json(), async (req, res) => {
const data = req.body;
try {
const result = await databaseService.insertData(data);
let insertedData = await databaseService.readData({ _id: result.insertedId });
res.status(200).send(insertedData);
} catch (error) {
console.error('Error inserting multiple data into MongoDB:', error);
res.status(500).send({ error: 'Error inserting multiple data into MongoDB' });
}
});
app.get("/getPlaylist/:id", cors(corsOptions), async (req, res) => {
try {
const { id } = req.params;
const result = await databaseService.readData({ _id: id });
res.status(200).send(result);
} catch (error) {
res.status(500).send({ error: 'Error reading data from MongoDB' });
}
});
// Updated route to read all data from MongoDB
app.get("/getAllPlaylists", cors(corsOptions), async (req, res) => {
try {
const result = await databaseService.readDataAll(); // No query parameters passed
res.status(200).send(result);
} catch (error) {
res.status(500).send({ error: 'Error reading data from MongoDB' });
}
});
// New route to delete a playlist by ID
app.delete("/deletePlaylist/:id", cors(corsOptions), async (req, res) => {
try {
const { id } = req.params;
const result = await databaseService.deleteData({ _id: id});
res.status(200).send(result);
} catch (error) {
res.status(500).send({ error: 'Error deleting playlist from MongoDB' });
}
});
// New route to remove all playlists
app.delete("/deleteAllPlaylists", cors(corsOptions), async (req, res) => {
try {
const result = await databaseService.deleteAllPlaylists();
res.status(200).send(result);
} catch (error) {
res.status(500).send({ error: 'Error removing all playlists from MongoDB' });
}
});
// New route to update a playlist by ID
app.put("/updatePlaylist/:id", cors(corsOptions), async (req, res) => {
try {
const { id } = req.params;
const updatedPlaylist = req.body;
const result = await databaseService.updateData({ _id: id }, updatedPlaylist);
const updatedData = await databaseService.readData({ _id: id });
res.status(200).send(updatedData);
} catch (error) {
res.status(500).send({ error: 'Error updating playlist in MongoDB' });
}
});
app.get("/stalker", cors(corsOptions), async (req, res) => {
axios
.get(req.query.url, {
params: req.query ?? {},
headers: {
Cookie: `mac=${req.query.macAddress}`,
...(req.query.token
? {
Authorization: `Bearer ${req.query.token}`,
}
: {}),
},
})
.then((result) => {
console.log(result.data);
return res.send({
payload: result.data,
action: req.query?.action,
});
})
.catch((err) => {
return res.send({
message: err.response?.statusText ?? "Error: not found",
status: err.response?.status ?? 404,
});
});
});
const epgLoggerLabel = "[EPG Worker]";
/**
* Fetches the epg data from the given url
* @param epgUrl url of the epg file
*/
const fetchEpgDataFromUrl = (epgUrl) => {
try {
let axiosConfig = {};
if (epgUrl.endsWith(".gz")) {
axiosConfig = {
responseType: "arraybuffer",
};
}
return axios
.get(epgUrl.trim(), axiosConfig)
.then((response) => {
console.log(epgLoggerLabel, "url content was fetched...");
const { data } = response;
if (epgUrl.endsWith(".gz")) {
console.log(epgLoggerLabel, "start unzipping...");
const output = zlib.gunzipSync(new Buffer.from(data)).toString();
const result = getParsedEpg(output);
console.log(result);
return result;
} else {
const result = getParsedEpg(data.toString());
return result;
}
})
.catch((err) => {
console.log(epgLoggerLabel, err);
});
} catch (error) {
console.log(epgLoggerLabel, error);
}
};
/**
* Parses and sets the epg data
* @param xmlString xml file content from the fetched url as string
*/
const getParsedEpg = (xmlString) => {
console.log(epgLoggerLabel, "start parsing...");
return epgParser.parse(xmlString);
};
const handlePlaylistParse = (url) => {
try {
return axios
.get(url, { httpsAgent: agent })
.then((result) => {
const parsedPlaylist = parsePlaylist(result.data.split("\n"));
const title = getLastUrlSegment(url);
const playlistObject = createPlaylistObject(title, parsedPlaylist, url);
return playlistObject;
})
.catch((error) => {
if (error.response) {
return {
status: error.response.status,
message: error.response.statusText,
};
} else {
return { status: 500, message: "Error, something went wrong" };
}
});
} catch (error) {
return error;
}
};
/**
* Returns last segment (part after last slash "/") of the given URL
* @param value URL as string
*/
const getLastUrlSegment = (value) => {
if (value && value.length > 1) {
return value.substr(value.lastIndexOf("/") + 1);
} else {
return "Playlist without title";
}
};
/**
* Parses string based array to playlist object
* @param m3uArray m3u playlist as array with strings
*/
const parsePlaylist = (m3uArray) => {
const playlistAsString = m3uArray.join("\n");
return parser.parse(playlistAsString); //.channels[0];
};
const guid = () => {
return Math.random().toString(36).slice(2);
};
const createPlaylistObject = (name, playlist, url) => {
return {
id: guid(),
_id: guid(),
filename: name,
title: name,
count: playlist.items.length,
playlist: {
...playlist,
items: playlist.items.map((item) => ({
id: guid(),
...item,
})),
},
importDate: new Date().toISOString(),
lastUsage: new Date().toISOString(),
favorites: [],
autoRefresh: false,
url,
};
};
const port = process.env.PORT || 3000;
app.listen(port, () =>
console.log(`Server running on ${port}, http://localhost:${port}`)
);