import { URLS } from '../api/apiConfig'; import { TAxios } from '../api/TAxios'; import { types } from './actionTypes'; /** * PDF를 이미지로 변환 * @param {string} pdfUrl - 변환할 PDF URL * @param {function} callback - 성공/실패 후 실행할 콜백 (error, imageUrl) */ export const convertPdfToImage = (pdfUrl, callback) => (dispatch, getState) => { dispatch({ type: types.CONVERT_PDF_TO_IMAGE, payload: pdfUrl, }); const onSuccess = (response) => { // retCode 체크 (프로젝트 API 규약: 200이어도 retCode로 성공/실패 구분) const retCode = response.headers?.retcode || response.headers?.retCode; if (retCode !== undefined && retCode !== 0 && retCode !== '0') { const error = new Error(`API Error: retCode=${retCode}`); dispatch({ type: types.CONVERT_PDF_TO_IMAGE_FAILURE, payload: { pdfUrl, error }, }); callback && callback(error, null); return; } let imageUrl; try { if (response.data instanceof Blob) { if (response.data.size < 100) { throw new Error('Invalid image data (size too small)'); } imageUrl = URL.createObjectURL(response.data); } else if (response.data instanceof ArrayBuffer) { if (response.data.byteLength < 100) { throw new Error('Invalid image data (size too small)'); } const blob = new Blob([response.data], { type: 'image/png' }); imageUrl = URL.createObjectURL(blob); } else { const blob = new Blob([response.data], { type: 'image/png' }); imageUrl = URL.createObjectURL(blob); } dispatch({ type: types.CONVERT_PDF_TO_IMAGE_SUCCESS, payload: { pdfUrl, imageUrl }, }); callback && callback(null, imageUrl); } catch (error) { dispatch({ type: types.CONVERT_PDF_TO_IMAGE_FAILURE, payload: { pdfUrl, error }, }); callback && callback(error, null); } }; const onFail = (error) => { dispatch({ type: types.CONVERT_PDF_TO_IMAGE_FAILURE, payload: { pdfUrl, error }, }); callback && callback(error, null); }; TAxios( dispatch, getState, 'post', URLS.CONVERT_IMG, {}, { pdfUrl }, onSuccess, onFail, false, 'blob' ); }; /** * 여러 PDF를 순차적으로 변환 (백그라운드) * @param {Array} pdfUrls - 변환할 PDF URL 배열 * @param {function} callback - 완료 후 실행할 콜백 (errors, results) */ export const convertMultiplePdfs = (pdfUrls, callback) => async (dispatch, getState) => { if (!pdfUrls || pdfUrls.length === 0) { callback && callback(null, []); return; } const results = []; const errors = []; for (let i = 0; i < pdfUrls.length; i++) { const pdfUrl = pdfUrls[i]; await new Promise((resolve) => { dispatch( convertPdfToImage(pdfUrl, (error, imageUrl) => { if (error) { errors.push({ pdfUrl, error }); } else { results.push({ pdfUrl, imageUrl }); } resolve(); }) ); }); if (i < pdfUrls.length - 1) { await new Promise((resolve) => setTimeout(resolve, 100)); } } callback && callback(errors.length > 0 ? errors : null, results); }; /** * 변환된 이미지 데이터 초기화 (전체) */ export const clearConvertedImage = () => ({ type: types.CLEAR_CONVERTED_IMAGE, }); /** * 특정 PDF의 변환된 이미지 데이터 제거 * @param {string} pdfUrl - 제거할 PDF URL */ export const clearConvertedImageByUrl = (pdfUrl) => ({ type: types.CLEAR_CONVERTED_IMAGE_BY_URL, payload: pdfUrl, });