|
| 1 | +import { NextApiRequest, NextApiResponse } from 'next'; |
| 2 | +import fs from 'fs'; |
| 3 | +import path from 'path'; |
| 4 | + |
| 5 | +interface Problem { |
| 6 | + id: string; |
| 7 | + title: { en: string; zh: string }; |
| 8 | + difficulty: string; |
| 9 | + tags?: string[]; |
| 10 | + description: { en: string; zh: string }; |
| 11 | + examples?: Array<{ input: string; output: string }>; |
| 12 | + template: Record<string, string>; |
| 13 | + tests: Array<{ input: string; output: string }>; |
| 14 | + solution?: Record<string, string>; |
| 15 | + solutions?: Array<{ |
| 16 | + title: { en: string; zh: string }; |
| 17 | + content: { en: string; zh: string }; |
| 18 | + }>; |
| 19 | +} |
| 20 | + |
| 21 | +function validateProblem(problem: any): problem is Problem { |
| 22 | + if (!problem || typeof problem !== 'object') return false; |
| 23 | + if (typeof problem.id !== 'string' || !problem.id) return false; |
| 24 | + if (!problem.title || typeof problem.title.en !== 'string') return false; |
| 25 | + if (!['Easy', 'Medium', 'Hard'].includes(problem.difficulty)) return false; |
| 26 | + if (!problem.description || typeof problem.description.en !== 'string') return false; |
| 27 | + if (!problem.template || typeof problem.template !== 'object') return false; |
| 28 | + if (!Array.isArray(problem.tests) || problem.tests.length === 0) return false; |
| 29 | + if (!/^[a-z0-9-]+$/.test(problem.id)) return false; |
| 30 | + return true; |
| 31 | +} |
| 32 | + |
| 33 | +function normalizeProblem(problem: any): Problem { |
| 34 | + return { |
| 35 | + id: problem.id, |
| 36 | + title: { |
| 37 | + en: problem.title.en || problem.title.zh || 'Untitled', |
| 38 | + zh: problem.title.zh || problem.title.en || '无标题', |
| 39 | + }, |
| 40 | + difficulty: problem.difficulty, |
| 41 | + tags: Array.isArray(problem.tags) ? problem.tags : [], |
| 42 | + description: { |
| 43 | + en: problem.description.en || problem.description.zh || '', |
| 44 | + zh: problem.description.zh || problem.description.en || '', |
| 45 | + }, |
| 46 | + examples: Array.isArray(problem.examples) ? problem.examples : [], |
| 47 | + template: problem.template, |
| 48 | + tests: problem.tests, |
| 49 | + ...(problem.solution && { solution: problem.solution }), |
| 50 | + ...(problem.solutions && { solutions: problem.solutions }), |
| 51 | + }; |
| 52 | +} |
| 53 | + |
| 54 | +function findJsonFiles(dir: string): string[] { |
| 55 | + const jsonFiles: string[] = []; |
| 56 | + |
| 57 | + try { |
| 58 | + const entries = fs.readdirSync(dir, { withFileTypes: true }); |
| 59 | + |
| 60 | + for (const entry of entries) { |
| 61 | + const fullPath = path.join(dir, entry.name); |
| 62 | + |
| 63 | + if (entry.isFile() && entry.name.endsWith('.json')) { |
| 64 | + jsonFiles.push(fullPath); |
| 65 | + } else if (entry.isDirectory()) { |
| 66 | + // Recursively search subdirectories |
| 67 | + jsonFiles.push(...findJsonFiles(fullPath)); |
| 68 | + } |
| 69 | + } |
| 70 | + } catch (error) { |
| 71 | + console.error(`Error reading directory ${dir}:`, error); |
| 72 | + } |
| 73 | + |
| 74 | + return jsonFiles; |
| 75 | +} |
| 76 | + |
| 77 | +function loadProblemsFromJsonFile(filePath: string): { problems: any[]; error?: string } { |
| 78 | + try { |
| 79 | + const content = fs.readFileSync(filePath, 'utf8'); |
| 80 | + const data = JSON.parse(content); |
| 81 | + |
| 82 | + // Handle both array and single object |
| 83 | + if (Array.isArray(data)) { |
| 84 | + return { problems: data }; |
| 85 | + } else if (data && typeof data === 'object' && data.id) { |
| 86 | + return { problems: [data] }; |
| 87 | + } else { |
| 88 | + return { problems: [], error: 'Invalid JSON structure' }; |
| 89 | + } |
| 90 | + } catch (error) { |
| 91 | + return { problems: [], error: error instanceof Error ? error.message : 'Failed to parse JSON' }; |
| 92 | + } |
| 93 | +} |
| 94 | + |
| 95 | +export default async function handler(req: NextApiRequest, res: NextApiResponse) { |
| 96 | + if (req.method !== 'POST') { |
| 97 | + return res.status(405).json({ error: 'Method not allowed' }); |
| 98 | + } |
| 99 | + |
| 100 | + try { |
| 101 | + const { folderPath, useProblemsFolder } = req.body; |
| 102 | + const appRoot = process.env.APP_ROOT || process.cwd(); |
| 103 | + |
| 104 | + let targetFolder: string; |
| 105 | + |
| 106 | + if (useProblemsFolder) { |
| 107 | + // Use the default problems folder |
| 108 | + targetFolder = path.join(appRoot, 'problems'); |
| 109 | + } else if (folderPath && typeof folderPath === 'string') { |
| 110 | + // Use user-specified folder |
| 111 | + targetFolder = folderPath; |
| 112 | + |
| 113 | + // Security check: ensure the path exists and is a directory |
| 114 | + if (!fs.existsSync(targetFolder)) { |
| 115 | + return res.status(400).json({ error: 'Folder does not exist' }); |
| 116 | + } |
| 117 | + |
| 118 | + const stats = fs.statSync(targetFolder); |
| 119 | + if (!stats.isDirectory()) { |
| 120 | + return res.status(400).json({ error: 'Path is not a directory' }); |
| 121 | + } |
| 122 | + } else { |
| 123 | + return res.status(400).json({ error: 'Either folderPath or useProblemsFolder is required' }); |
| 124 | + } |
| 125 | + |
| 126 | + // Find all JSON files in the folder |
| 127 | + const jsonFiles = findJsonFiles(targetFolder); |
| 128 | + |
| 129 | + if (jsonFiles.length === 0) { |
| 130 | + return res.status(200).json({ |
| 131 | + success: 0, |
| 132 | + failed: 0, |
| 133 | + skipped: 0, |
| 134 | + total: 0, |
| 135 | + message: 'No JSON files found in the folder', |
| 136 | + fileResults: [], |
| 137 | + }); |
| 138 | + } |
| 139 | + |
| 140 | + // Read current problems |
| 141 | + const problemsPath = path.join(appRoot, 'public', 'problems.json'); |
| 142 | + let currentProblems: Problem[] = []; |
| 143 | + |
| 144 | + try { |
| 145 | + const problemsData = fs.readFileSync(problemsPath, 'utf8'); |
| 146 | + currentProblems = JSON.parse(problemsData); |
| 147 | + } catch { |
| 148 | + // If file doesn't exist or is invalid, start with empty array |
| 149 | + currentProblems = []; |
| 150 | + } |
| 151 | + |
| 152 | + const existingIds = new Set(currentProblems.map(p => p.id)); |
| 153 | + |
| 154 | + // Process each JSON file |
| 155 | + let totalSuccess = 0; |
| 156 | + let totalFailed = 0; |
| 157 | + let totalSkipped = 0; |
| 158 | + const fileResults: Array<{ file: string; success: number; failed: number; skipped: number; error?: string }> = []; |
| 159 | + |
| 160 | + for (const jsonFile of jsonFiles) { |
| 161 | + const relativePath = path.relative(targetFolder, jsonFile); |
| 162 | + const { problems, error } = loadProblemsFromJsonFile(jsonFile); |
| 163 | + |
| 164 | + if (error) { |
| 165 | + fileResults.push({ file: relativePath, success: 0, failed: 0, skipped: 0, error }); |
| 166 | + continue; |
| 167 | + } |
| 168 | + |
| 169 | + let fileSuccess = 0; |
| 170 | + let fileFailed = 0; |
| 171 | + let fileSkipped = 0; |
| 172 | + |
| 173 | + for (const problem of problems) { |
| 174 | + if (existingIds.has(problem.id)) { |
| 175 | + fileSkipped++; |
| 176 | + totalSkipped++; |
| 177 | + continue; |
| 178 | + } |
| 179 | + |
| 180 | + if (!validateProblem(problem)) { |
| 181 | + fileFailed++; |
| 182 | + totalFailed++; |
| 183 | + continue; |
| 184 | + } |
| 185 | + |
| 186 | + const normalizedProblem = normalizeProblem(problem); |
| 187 | + currentProblems.push(normalizedProblem); |
| 188 | + existingIds.add(problem.id); |
| 189 | + fileSuccess++; |
| 190 | + totalSuccess++; |
| 191 | + } |
| 192 | + |
| 193 | + fileResults.push({ file: relativePath, success: fileSuccess, failed: fileFailed, skipped: fileSkipped }); |
| 194 | + } |
| 195 | + |
| 196 | + // Save updated problems |
| 197 | + if (totalSuccess > 0) { |
| 198 | + fs.writeFileSync(problemsPath, JSON.stringify(currentProblems, null, 2)); |
| 199 | + |
| 200 | + // Also sync to problems/problems.json |
| 201 | + const sourceProblemsPath = path.join(appRoot, 'problems', 'problems.json'); |
| 202 | + try { |
| 203 | + fs.writeFileSync(sourceProblemsPath, JSON.stringify(currentProblems, null, 2)); |
| 204 | + } catch { |
| 205 | + // Ignore if problems folder doesn't exist |
| 206 | + } |
| 207 | + } |
| 208 | + |
| 209 | + return res.status(200).json({ |
| 210 | + success: totalSuccess, |
| 211 | + failed: totalFailed, |
| 212 | + skipped: totalSkipped, |
| 213 | + total: jsonFiles.length, |
| 214 | + fileResults, |
| 215 | + }); |
| 216 | + } catch (error) { |
| 217 | + console.error('Error importing from folder:', error); |
| 218 | + return res.status(500).json({ |
| 219 | + error: error instanceof Error ? error.message : 'Failed to import from folder' |
| 220 | + }); |
| 221 | + } |
| 222 | +} |
| 223 | + |
0 commit comments