Skip to content

Commit

Permalink
Merge pull request #1 from ashishraj09/feature/move-to-master
Browse files Browse the repository at this point in the history
Feature/move to master
  • Loading branch information
ashishraj09 authored Nov 10, 2024
2 parents 2f4207b + fb4075a commit b2b3de3
Show file tree
Hide file tree
Showing 4 changed files with 534 additions and 1 deletion.
109 changes: 109 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ 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
Expand All @@ -16,11 +17,24 @@ const originUrl = process.env.CLIENT_URL
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 || "";
const collectionName = isDev ? "playlists" : process.env.MONGO_COLLECTION_NAME || "";

console.log(`dbName: ${dbName}`);
console.log(`mongoUri: ${mongoUri}`);
console.log(`collectionName: ${collectionName}`);

const mongoDBService = new MongoDBService(mongoUri, dbName, collectionName);


const corsOptions = {
origin: originUrl,
optionsSuccessStatus: 200,
};

app.use(express.json());

const https = require("https");
const agent = new https.Agent({
rejectUnauthorized: false,
Expand Down Expand Up @@ -70,6 +84,101 @@ app.get("/xtream", cors(corsOptions), async (req, res) => {
});
});

// New route to check the database connection status
app.get("/check-db-connection", cors(corsOptions), async (req, res) => {

if (!mongoUri || !dbName || !collectionName) {
return res.status(200).send({ status: "error", message: "Database is not enabled" });
}

try {
await dbService.connect();
res.status(200).send({ status: "success", message: "Database is enabled" });
} catch (error) {
console.error('Error connecting to MongoDB:', error);
res.status(200).send({ status: "error", message: "Database is not enabled", error: error.message });
}
});

// New route to add multiple playlists
app.post("/addManyPlaylists", cors(corsOptions), async (req, res) => {
try {
const playlists = req.body;
const result = await mongoDBService.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 mongoDBService.insertData(data);
let insertedData;
insertedData = await mongoDBService.readData({ _id: result.insertedId });
res.status(200).send(insertedData);
} catch (error) {
console.error('Error inserting data into MongoDB:', error);
res.status(500).send({ error: 'Error inserting data into MongoDB' });
}
});

app.get("/getPlaylist/:id", cors(corsOptions), async (req, res) => {
try {
const { id } = req.params;
const result = await mongoDBService.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 mongoDBService.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 mongoDBService.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("/removeAllPlaylists", cors(corsOptions), async (req, res) => {
try {
const result = await mongoDBService.removeAllPlaylists();
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 mongoDBService.updateData({ _id: id }, updatedPlaylist);
const updatedData = await mongoDBService.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, {
Expand Down
119 changes: 119 additions & 0 deletions mongo-db.service.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
const { MongoClient } = require('mongodb');

class MongoDBService {
constructor(uri, dbName, collectionName) {
this.uri = uri;
this.dbName = dbName;
this.collectionName = collectionName;
this.client = new MongoClient(this.uri, { useNewUrlParser: true, useUnifiedTopology: true });
this.isConnected = false;
}

async connect() {
if (!this.isConnected) {
try {
await this.client.connect();
this.database = this.client.db(this.dbName);
this.collection = this.database.collection(this.collectionName);
this.isConnected = true;
console.log(`[${new Date().toISOString()}] Connected to MongoDB`);
console.log(`URI: ${this.uri}`);
console.log(`Database: ${this.dbName}`);
console.log(`Collection: ${this.collectionName}`);
} catch (error) {
console.error(`[${new Date().toISOString()}] Error connecting to MongoDB:`, error);
}
}
}

async insertData(data) {
try {
await this.connect();
const result = await this.collection.insertOne(data);
console.log(`[${new Date().toISOString()}] Data inserted with _id: ${result.insertedId}`);
return result;
} catch (error) {
console.error(`[${new Date().toISOString()}] Error inserting data into MongoDB:`, error);
}
}

async insertMany(data) {
try {
await this.connect();
const result = await this.collection.insertMany(data);
console.log(`[${new Date().toISOString()}] Data inserted:`, result.insertedIds);
return result;
} catch (error) {
console.error(`[${new Date().toISOString()}] Error inserting data into MongoDB:`, error);
}
}

async readDataAll(query = {}) {
try {
await this.connect();
const foundData = await this.collection.find(query).toArray();
console.log(`[${new Date().toISOString()}] Found data:`, foundData);
return foundData;
} catch (error) {
console.error(`[${new Date().toISOString()}] Error reading data from MongoDB:`, error);
}
}

async readData(query) {
try {
await this.connect();
const foundData = await this.collection.findOne(query);
console.log(`[${new Date().toISOString()}] Found data:`, foundData);
return foundData;
} catch (error) {
console.error(`[${new Date().toISOString()}] Error reading data from MongoDB:`, error);
}
}

async deleteData(query) {
try {
await this.connect();
const result = await this.collection.deleteOne(query);
console.log(`[${new Date().toISOString()}] Data deleted with query:`, query);
return result;
} catch (error) {
console.error(`[${new Date().toISOString()}] Error deleting data from MongoDB:`, error);
}
}

async removeAllPlaylists() {
try {
await this.connect();
const result = await this.collection.deleteMany({});
console.log(`[${new Date().toISOString()}] All playlists removed`);
return result;
} catch (error) {
console.error(`[${new Date().toISOString()}] Error removing all playlists from MongoDB:`, error);
}
}

async updateData(query, update) {
try {
await this.connect();
const result = await this.collection.updateOne(query, { $set: update });
console.log(`[${new Date().toISOString()}] Data updated with query:`, query, 'and update:', update);
return result;
} catch (error) {
console.error(`[${new Date().toISOString()}] Error updating data in MongoDB:`, error);
}
}

async close() {
if (this.isConnected) {
try {
await this.client.close();
this.isConnected = false;
console.log(`[${new Date().toISOString()}] MongoDB connection closed`);
} catch (error) {
console.error(`[${new Date().toISOString()}] Error closing MongoDB connection:`, error);
}
}
}
}

module.exports = MongoDBService;
Loading

0 comments on commit b2b3de3

Please sign in to comment.