111 lines
2.6 KiB
JavaScript
111 lines
2.6 KiB
JavaScript
import express from "express";
|
|
import multer from "multer";
|
|
import axios from "axios";
|
|
import fs from "fs";
|
|
import path from "path";
|
|
import Link from "../models/Link.js";
|
|
import { authMiddleware } from "../middleware/auth.js";
|
|
|
|
const router = express.Router();
|
|
|
|
const storage = multer.diskStorage({
|
|
destination: "uploads/",
|
|
filename: (req, file, cb) => {
|
|
const unique = Date.now() + "-" + file.originalname;
|
|
cb(null, unique);
|
|
}
|
|
});
|
|
const upload = multer({ storage });
|
|
|
|
router.use(authMiddleware);
|
|
|
|
async function downloadImage(url) {
|
|
const filename = Date.now() + ".png";
|
|
const filepath = path.join("uploads", filename);
|
|
|
|
const response = await axios({
|
|
url,
|
|
method: "GET",
|
|
responseType: "stream",
|
|
headers: { "User-Agent": "Mozilla/5.0" }
|
|
});
|
|
|
|
await new Promise((resolve, reject) => {
|
|
const stream = response.data.pipe(fs.createWriteStream(filepath));
|
|
stream.on("finish", resolve);
|
|
stream.on("error", reject);
|
|
});
|
|
|
|
return "/uploads/" + filename;
|
|
}
|
|
|
|
function deleteOldIcon(iconPath) {
|
|
if (!iconPath) return;
|
|
const full = path.join(process.cwd(), iconPath.replace("/", ""));
|
|
fs.unlink(full, () => {});
|
|
}
|
|
|
|
router.get("/", async (req, res) => {
|
|
const links = await Link.find({ owner: req.userId });
|
|
res.json(links);
|
|
});
|
|
|
|
router.post("/", upload.single("icon"), async (req, res) => {
|
|
const { url, name, iconURL } = req.body;
|
|
|
|
let iconPath = null;
|
|
|
|
if (req.file) iconPath = `/uploads/${req.file.filename}`;
|
|
else if (iconURL) iconPath = await downloadImage(iconURL);
|
|
|
|
const link = await Link.create({
|
|
url,
|
|
name,
|
|
icon: iconPath,
|
|
owner: req.userId
|
|
});
|
|
|
|
res.json(link);
|
|
});
|
|
|
|
router.put("/:id", upload.single("icon"), async (req, res) => {
|
|
const { id } = req.params;
|
|
const { name, url, iconURL } = req.body;
|
|
|
|
const link = await Link.findOne({ _id: id, owner: req.userId });
|
|
if (!link) return res.status(404).json({ error: "Link non trovato" });
|
|
|
|
const update = { name, url };
|
|
let newIcon = null;
|
|
|
|
if (req.file) newIcon = `/uploads/${req.file.filename}`;
|
|
else if (iconURL) newIcon = await downloadImage(iconURL);
|
|
|
|
if (newIcon) {
|
|
deleteOldIcon(link.icon);
|
|
update.icon = newIcon;
|
|
}
|
|
|
|
const updated = await Link.findOneAndUpdate(
|
|
{ _id: id, owner: req.userId },
|
|
update,
|
|
{ new: true }
|
|
);
|
|
|
|
res.json(updated);
|
|
});
|
|
|
|
router.delete("/:id", async (req, res) => {
|
|
const link = await Link.findOneAndDelete({
|
|
_id: req.params.id,
|
|
owner: req.userId
|
|
});
|
|
|
|
if (!link) return res.status(404).json({ error: "Link non trovato" });
|
|
|
|
deleteOldIcon(link.icon);
|
|
|
|
res.json({ success: true });
|
|
});
|
|
|
|
export default router;
|