takeSnap
Suvodip 2025-03-11 18:37:19 +05:30
parent dc6194f7e7
commit cdee582951
1 changed files with 41 additions and 27 deletions

View File

@ -1,38 +1,52 @@
const puppeteer = require('puppeteer');
const puppeteer = require("puppeteer");
const axios = require("axios");
const fs = require("fs");
const FormData = require("form-data");
const path = require("path");
const takeSnap = async (req, res) => {
// Set CORS headers
res.setHeader('Access-Control-Allow-Origin', '*'); // Allow all origins
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS'); // Allow POST and OPTIONS
res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); // Allow Content-Type header
// Handle preflight request (OPTIONS)
if (req.method === 'OPTIONS') {
res.status(200).end(); // Respond to preflight request
return;
}
try {
const url = req.body.url;
const browser = await puppeteer.launch();
const { url, itemId } = req.body;
if (!url || !itemId) {
return res.status(400).json({ error: "URL and itemId are required" });
}
// 1⃣ Take Screenshot
const browser = await puppeteer.launch({ headless: "new" });
const page = await browser.newPage();
await page.goto(url, { waitUntil: 'networkidle2' });
// Take screenshot and convert to base64
const screenshot = await page.screenshot({ encoding: 'base64', fullPage: true });
await page.goto(url, { waitUntil: "networkidle2" });
const screenshotPath = path.join(__dirname, "screenshot.png");
await page.screenshot({ path: screenshotPath, fullPage: true });
await browser.close();
console.log('Screenshot taken');
// Send the base64-encoded image in the response
res.status(200).json({ image: screenshot });
// 2⃣ Upload Screenshot to Directus (No Authorization Required)
const formData = new FormData();
formData.append("file", fs.createReadStream(screenshotPath));
const uploadResponse = await axios.post(
"https://game-du.teachertrainingkolkata.in/files",
formData,
{ headers: { ...formData.getHeaders() } } // No Authorization needed
);
const fileId = uploadResponse.data.data.id;
console.log("File uploaded to Directus with ID:", fileId);
// 3⃣ Update Directus Collection (No Authorization Required)
await axios.patch(
`https://game-du.teachertrainingkolkata.in/items/game_drawing_v3/${itemId}`,
{ thumbnail: fileId }
);
// Delete local file after upload
fs.unlinkSync(screenshotPath);
res.json({ success: true, fileId, message: "Screenshot taken and uploaded successfully!" });
} catch (error) {
console.error('Error taking screenshot:', error);
res.status(500).json({ error: 'Failed to take screenshot' });
console.error("Error taking screenshot:", error);
res.status(500).json({ error: "Failed to take screenshot" });
}
};
module.exports = takeSnap;
module.exports = takeSnap;