AI Resource Pro / website · airesourcepro.com / scripts / migrate-images-to-cloudflare.ts
| 1 | /** |
| 2 | * Script to migrate existing images from local storage to Cloudflare Images |
| 3 | * |
| 4 | * Usage: |
| 5 | * npm run migrate-images |
| 6 | */ |
| 7 | |
| 8 | import fs from 'fs'; |
| 9 | import path from 'path'; |
| 10 | import dotenv from 'dotenv'; |
| 11 | import fetch from 'node-fetch'; |
| 12 | import FormData from 'form-data'; |
| 13 | |
| 14 | // Load environment variables |
| 15 | dotenv.config(); |
| 16 | |
| 17 | // Type definitions for Cloudflare API responses |
| 18 | interface CloudflareImage { |
| 19 | id: string; |
| 20 | filename: string; |
| 21 | uploaded: string; |
| 22 | requireSignedURLs: boolean; |
| 23 | variants: string[]; |
| 24 | meta?: Record<string, any>; |
| 25 | } |
| 26 | |
| 27 | interface CloudflareResponse { |
| 28 | result: CloudflareImage; |
| 29 | success: boolean; |
| 30 | errors: Array<{ code: number; message: string }>; |
| 31 | messages: Array<{ code: number; message: string }>; |
| 32 | } |
| 33 | |
| 34 | // Configuration |
| 35 | const CLOUDFLARE_ACCOUNT_ID = process.env.CLOUDFLARE_ACCOUNT_ID; |
| 36 | const CLOUDFLARE_IMAGE_API_KEY = process.env.CLOUDFLARE_IMAGE_API_KEY; |
| 37 | const CLOUDFLARE_API_URL = `https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/images/v1`; |
| 38 | const BASE_IMAGES_DIRECTORY = path.join(process.cwd(), 'public/images'); |
| 39 | const VALID_CATEGORIES = ['blog', 'news', 'tools', 'learning', 'misc', 'midjourney']; |
| 40 | |
| 41 | // Log configuration |
| 42 | console.log('Migration Configuration:'); |
| 43 | console.log('- Base Images Directory:', BASE_IMAGES_DIRECTORY); |
| 44 | console.log('- Valid Categories:', VALID_CATEGORIES.join(', ')); |
| 45 | console.log('- Cloudflare Account ID:', CLOUDFLARE_ACCOUNT_ID ? '✓ Set' : '✗ Not Set'); |
| 46 | console.log('- Cloudflare API Key:', CLOUDFLARE_IMAGE_API_KEY ? '✓ Set' : '✗ Not Set'); |
| 47 | console.log(); |
| 48 | |
| 49 | // Validate configuration |
| 50 | if (!CLOUDFLARE_ACCOUNT_ID || !CLOUDFLARE_IMAGE_API_KEY) { |
| 51 | console.error('Error: Cloudflare credentials not configured. Please set CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_IMAGE_API_KEY in .env'); |
| 52 | process.exit(1); |
| 53 | } |
| 54 | |
| 55 | /** |
| 56 | * Upload an image to Cloudflare Images |
| 57 | */ |
| 58 | async function uploadImageToCloudflare(filePath: string, fileName: string, category: string) { |
| 59 | try { |
| 60 | // Read file as a Buffer |
| 61 | const fileBuffer = fs.readFileSync(filePath); |
| 62 | |
| 63 | // Create FormData instance from form-data package |
| 64 | const formData = new FormData(); |
| 65 | |
| 66 | // Add the file directly as a buffer with filename |
| 67 | formData.append('file', fileBuffer, { |
| 68 | filename: fileName, |
| 69 | // Infer content type from file extension if needed |
| 70 | }); |
| 71 | |
| 72 | // Add metadata with category |
| 73 | formData.append('metadata', JSON.stringify({ category })); |
| 74 | |
| 75 | // Upload to Cloudflare |
| 76 | const response = await fetch(CLOUDFLARE_API_URL, { |
| 77 | method: 'POST', |
| 78 | headers: { |
| 79 | 'Authorization': `Bearer ${CLOUDFLARE_IMAGE_API_KEY}`, |
| 80 | ...formData.getHeaders() // Important: Include headers from FormData |
| 81 | }, |
| 82 | // @ts-ignore This should work with node-fetch |
| 83 | body: formData, |
| 84 | }); |
| 85 | |
| 86 | // Handle response |
| 87 | const data = await response.json() as CloudflareResponse; |
| 88 | |
| 89 | if (!response.ok) { |
| 90 | throw new Error(`Failed to upload image: ${data.errors?.[0]?.message || response.statusText}`); |
| 91 | } |
| 92 | |
| 93 | return { |
| 94 | id: data.result.id, |
| 95 | url: data.result.variants[0], |
| 96 | success: true, |
| 97 | }; |
| 98 | } catch (error) { |
| 99 | console.error(`Error uploading ${fileName}:`, error instanceof Error ? error.message : 'Unknown error'); |
| 100 | return { |
| 101 | id: null, |
| 102 | url: null, |
| 103 | success: false, |
| 104 | error: error instanceof Error ? error.message : 'Unknown error', |
| 105 | }; |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | /** |
| 110 | * Migrate images from a category |
| 111 | */ |
| 112 | async function migrateCategory(category: string) { |
| 113 | console.log(`\nMigrating category: ${category}`); |
| 114 | |
| 115 | const categoryDir = path.join(BASE_IMAGES_DIRECTORY, category); |
| 116 | |
| 117 | // Check if directory exists |
| 118 | if (!fs.existsSync(categoryDir)) { |
| 119 | console.log(`- Directory for category ${category} does not exist, skipping`); |
| 120 | return { |
| 121 | total: 0, |
| 122 | success: 0, |
| 123 | failed: 0, |
| 124 | }; |
| 125 | } |
| 126 | |
| 127 | // Get all image files in the directory |
| 128 | const files = fs.readdirSync(categoryDir) |
| 129 | .filter(file => { |
| 130 | const ext = path.extname(file).toLowerCase(); |
| 131 | return ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.svg'].includes(ext); |
| 132 | }); |
| 133 | |
| 134 | console.log(`- Found ${files.length} images to migrate`); |
| 135 | |
| 136 | // Migration stats |
| 137 | let successCount = 0; |
| 138 | let failCount = 0; |
| 139 | const failedFiles: string[] = []; |
| 140 | const successfulUploads: Array<{ name: string, id: string, url: string }> = []; |
| 141 | |
| 142 | // Process each file |
| 143 | for (let i = 0; i < files.length; i++) { |
| 144 | const fileName = files[i]; |
| 145 | const filePath = path.join(categoryDir, fileName); |
| 146 | |
| 147 | console.log(`- [${i+1}/${files.length}] Migrating ${fileName}...`); |
| 148 | |
| 149 | // Upload to Cloudflare |
| 150 | const result = await uploadImageToCloudflare(filePath, fileName, category); |
| 151 | |
| 152 | if (result.success) { |
| 153 | successCount++; |
| 154 | console.log(` ✓ Uploaded successfully. ID: ${result.id}`); |
| 155 | successfulUploads.push({ |
| 156 | name: fileName, |
| 157 | id: result.id!, |
| 158 | url: result.url!, |
| 159 | }); |
| 160 | } else { |
| 161 | failCount++; |
| 162 | failedFiles.push(fileName); |
| 163 | console.log(` ✗ Failed to upload: ${result.error}`); |
| 164 | } |
| 165 | |
| 166 | // Add a small delay to avoid rate limiting |
| 167 | await new Promise(resolve => setTimeout(resolve, 500)); |
| 168 | } |
| 169 | |
| 170 | // Write results to a log file |
| 171 | const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); |
| 172 | const logDir = path.join(process.cwd(), 'logs'); |
| 173 | |
| 174 | // Ensure logs directory exists |
| 175 | if (!fs.existsSync(logDir)) { |
| 176 | fs.mkdirSync(logDir, { recursive: true }); |
| 177 | } |
| 178 | |
| 179 | // Write successful uploads to a JSON file for reference |
| 180 | if (successfulUploads.length > 0) { |
| 181 | fs.writeFileSync( |
| 182 | path.join(logDir, `cloudflare-migration-${category}-${timestamp}.json`), |
| 183 | JSON.stringify(successfulUploads, null, 2) |
| 184 | ); |
| 185 | } |
| 186 | |
| 187 | // Write failed files to a log file |
| 188 | if (failedFiles.length > 0) { |
| 189 | fs.writeFileSync( |
| 190 | path.join(logDir, `cloudflare-migration-${category}-failed-${timestamp}.txt`), |
| 191 | failedFiles.join('\n') |
| 192 | ); |
| 193 | } |
| 194 | |
| 195 | return { |
| 196 | total: files.length, |
| 197 | success: successCount, |
| 198 | failed: failCount, |
| 199 | }; |
| 200 | } |
| 201 | |
| 202 | /** |
| 203 | * Run the migration |
| 204 | */ |
| 205 | async function main() { |
| 206 | console.log('Starting migration of images to Cloudflare Images...\n'); |
| 207 | |
| 208 | // Overall stats |
| 209 | let totalImages = 0; |
| 210 | let totalSuccess = 0; |
| 211 | let totalFailed = 0; |
| 212 | |
| 213 | // Create a timestamp for the start of migration |
| 214 | const startTime = new Date(); |
| 215 | |
| 216 | // Migrate each category |
| 217 | for (const category of VALID_CATEGORIES) { |
| 218 | const result = await migrateCategory(category); |
| 219 | |
| 220 | totalImages += result.total; |
| 221 | totalSuccess += result.success; |
| 222 | totalFailed += result.failed; |
| 223 | } |
| 224 | |
| 225 | // Calculate duration |
| 226 | const endTime = new Date(); |
| 227 | const durationMs = endTime.getTime() - startTime.getTime(); |
| 228 | const durationMin = Math.floor(durationMs / 60000); |
| 229 | const durationSec = Math.floor((durationMs % 60000) / 1000); |
| 230 | |
| 231 | // Log final results |
| 232 | console.log('\n=== Migration Complete ==='); |
| 233 | console.log(`Total images processed: ${totalImages}`); |
| 234 | console.log(`Successfully uploaded: ${totalSuccess}`); |
| 235 | console.log(`Failed to upload: ${totalFailed}`); |
| 236 | console.log(`Duration: ${durationMin} minutes, ${durationSec} seconds`); |
| 237 | |
| 238 | if (totalFailed > 0) { |
| 239 | console.log('\nSome images failed to upload. Check the logs directory for details.'); |
| 240 | console.log('You can run the script again to retry failed uploads.'); |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | // Run the script |
| 245 | main().catch(error => { |
| 246 | console.error('Migration failed:', error); |
| 247 | process.exit(1); |
| 248 | }); |