import { prisma } from '../lib/prisma'; async function uploadToOpeninary(buffer: Buffer, filename: string, folder: string) { const formData = new FormData(); const blob = new Blob([new Uint8Array(buffer)], { type: 'image/jpeg' }); formData.append("files", blob, filename); formData.append("folder", folder); const res = await fetch(`${process.env.OPENINARY_API_URL}/api/upload`, { method: "POST", headers: { Authorization: `Bearer ${process.env.OPENINARY_API_KEY}` }, body: formData as any, }); if (!res.ok) { const errorText = await res.text(); throw new Error("Upload failed: " + errorText); } const data = await res.json(); return data.files[0]; } async function processUrl(url: string, folder: string): Promise { if (!url) return url; if (!url.includes('cloudinary.com')) return url; console.log(`Downloading ${url}...`); try { const res = await fetch(url); if (!res.ok) throw new Error(`Failed to fetch ${url}`); const arrayBuffer = await res.arrayBuffer(); const buffer = Buffer.from(arrayBuffer); const filename = url.split('/').pop()?.split('?')[0] || 'image.jpg'; console.log(`Uploading ${filename} to Openinary...`); const result = await uploadToOpeninary(buffer, filename, folder); console.log(`Uploaded! New path: ${result.path}`); return result.path; } catch (e) { console.error(`Error processing ${url}:`, e); return url; } } async function main() { console.log('Starting migration...'); // Migrate Projects const projects = await prisma.project.findMany(); for (const project of projects) { console.log(`Processing project: ${project.title}`); let updated = false; let newImage = project.image; if (newImage && newImage.includes('cloudinary.com')) { newImage = await processUrl(newImage, 'ayristech/projects'); updated = true; } const newGallery = []; for (const img of project.gallery) { if (img.includes('cloudinary.com')) { const newImg = await processUrl(img, 'ayristech/projects'); newGallery.push(newImg); updated = true; } else { newGallery.push(img); } } if (updated) { await prisma.project.update({ where: { id: project.id }, data: { image: newImage, gallery: newGallery } }); console.log(`Updated project ${project.id}`); } } // Migrate BlogPosts const posts = await prisma.blogPost.findMany(); for (const post of posts) { console.log(`Processing blog post: ${post.slug}`); if (post.image && post.image.includes('cloudinary.com')) { const newImage = await processUrl(post.image, 'ayristech/blog'); await prisma.blogPost.update({ where: { id: post.id }, data: { image: newImage } }); console.log(`Updated blog post ${post.id}`); } } console.log('Migration completed!'); } main().catch(console.error).finally(() => prisma.$disconnect());