first commit

This commit is contained in:
bluebamus committed 2025-12-15 13:51:13 +09:00
commit 086d898b68
154 files changed
+68619

No files matched your search

@@ -0,0 +1,311 @@
/**
* Auto Upload Service
*
* Beginner/Intermediate 레벨 사용자의 영상 자동 업로드를 처리합니다.
* - YouTube, Instagram, TikTok에 자동 업로드
* - SEO 데이터 자동 생성 (Gemini 사용)
*/
const db = require('../db');
const path = require('path');
/**
* 사용자 레벨에 따른 자동 업로드 설정 확인
*/
const shouldAutoUpload = async (userId) => {
return new Promise((resolve, reject) => {
const query = `
SELECT u.experience_level, ags.auto_youtube, ags.auto_instagram, ags.auto_tiktok
FROM users u
LEFT JOIN auto_generation_settings ags ON u.id = ags.user_id
WHERE u.id = ?
`;
db.get(query, [userId], (err, row) => {
if (err) {
console.error('자동 업로드 설정 조회 실패:', err);
return resolve({ shouldUpload: false, platforms: {} });
}
if (!row) {
return resolve({ shouldUpload: false, platforms: {} });
}
const level = row.experience_level || 'beginner';
// Beginner/Intermediate는 기본 자동 업로드
if (level === 'beginner' || level === 'intermediate') {
return resolve({
shouldUpload: true,
platforms: {
youtube: true,
instagram: true,
tiktok: true
},
level
});
}
// Pro는 사용자 설정에 따름
if (level === 'pro') {
return resolve({
shouldUpload: row.auto_youtube || row.auto_instagram || row.auto_tiktok,
platforms: {
youtube: Boolean(row.auto_youtube),
instagram: Boolean(row.auto_instagram),
tiktok: Boolean(row.auto_tiktok)
},
level
});
}
resolve({ shouldUpload: false, platforms: {} });
});
});
};
/**
* SEO 데이터 자동 생성 (Gemini 사용)
*/
const generateAutoSeo = async (businessInfo, language = 'KO') => {
const { GoogleGenerativeAI } = require('@google/generative-ai');
const genAI = new GoogleGenerativeAI(process.env.VITE_GEMINI_API_KEY);
const langPrompts = {
KO: {
title: '한국어로',
tags: '한국어 해시태그',
},
EN: {
title: 'in English',
tags: 'English hashtags',
},
JA: {
title: '日本語で',
tags: '日本語ハッシュタグ',
},
ZH: {
title: '用中文',
tags: '中文标签',
},
TH: {
title: 'ในภาษาไทย',
tags: 'แฮชแท็กภาษาไทย',
},
VI: {
title: 'bằng tiếng Việt',
tags: 'hashtag tiếng Việt',
}
};
const langConfig = langPrompts[language] || langPrompts.KO;
const prompt = `
당신은 펜션/숙소 홍보 영상의 SEO 전문가입니다.
아래 정보를 바탕으로 YouTube, Instagram, TikTok용 SEO 데이터를 생성하세요.
펜션 정보:
- 이름: ${businessInfo.name || '펜션'}
- 설명: ${businessInfo.description || ''}
- 주소: ${businessInfo.address || ''}
- 카테고리: ${businessInfo.categories?.join(', ') || ''}
요구사항:
1. title: 매력적인 제목 (${langConfig.title}, 60자 이내)
2. description: 상세 설명 (${langConfig.title}, 200자 이내)
3. tags: 검색용 태그 10개 (${langConfig.tags}, 쉼표로 구분)
4. hashtags: 소셜미디어용 해시태그 15개 (${langConfig.tags}, #포함)
JSON 형식으로 응답하세요:
{
"title": "제목",
"description": "설명",
"tags": ["태그1", "태그2", ...],
"hashtags": "#태그1 #태그2 ..."
}
`;
try {
const model = genAI.getGenerativeModel({ model: 'gemini-1.5-flash' });
const result = await model.generateContent(prompt);
const text = result.response.text();
// JSON 추출
const jsonMatch = text.match(/\{[\s\S]*\}/);
if (jsonMatch) {
return JSON.parse(jsonMatch[0]);
}
// 기본값 반환
return {
title: `${businessInfo.name || '펜션'} - 힐링 여행`,
description: businessInfo.description || '아름다운 펜션에서 특별한 휴식을 경험하세요.',
tags: ['펜션', '여행', '힐링', '휴식', '숙소'],
hashtags: '#펜션 #여행 #힐링 #휴식 #숙소 #vacation #travel'
};
} catch (error) {
console.error('SEO 자동 생성 실패:', error);
return {
title: `${businessInfo.name || '펜션'} - 힐링 여행`,
description: businessInfo.description || '아름다운 펜션에서 특별한 휴식을 경험하세요.',
tags: ['펜션', '여행', '힐링', '휴식', '숙소'],
hashtags: '#펜션 #여행 #힐링 #휴식 #숙소 #vacation #travel'
};
}
};
/**
* 자동 업로드 실행
*/
const executeAutoUpload = async (userId, videoPath, businessInfo, language = 'KO') => {
const results = {
youtube: { success: false, error: null },
instagram: { success: false, error: null },
tiktok: { success: false, error: null }
};
try {
// 자동 업로드 설정 확인
const uploadConfig = await shouldAutoUpload(userId);
if (!uploadConfig.shouldUpload) {
console.log('자동 업로드 비활성화 - 사용자 설정에 따름');
return { skipped: true, reason: '자동 업로드 비활성화됨', results };
}
// SEO 데이터 자동 생성
const seoData = await generateAutoSeo(businessInfo, language);
console.log('SEO 데이터 생성 완료:', seoData.title);
// YouTube 업로드
if (uploadConfig.platforms.youtube) {
try {
const youtubeService = require('../youtubeService');
const youtubeResult = await youtubeService.uploadVideo(
userId,
videoPath,
seoData.title,
seoData.description + '\n\n' + seoData.hashtags,
seoData.tags
);
results.youtube = { success: true, videoId: youtubeResult.videoId };
console.log('YouTube 업로드 성공:', youtubeResult.videoId);
} catch (ytError) {
console.error('YouTube 업로드 실패:', ytError.message);
results.youtube = { success: false, error: ytError.message };
}
}
// Instagram 업로드
if (uploadConfig.platforms.instagram) {
try {
// Instagram은 비디오를 릴스로 업로드
const response = await fetch('http://localhost:5001/upload-reel', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username: await getInstagramUsername(userId),
video_path: videoPath,
caption: seoData.description + '\n\n' + seoData.hashtags
})
});
if (response.ok) {
const result = await response.json();
results.instagram = { success: true, mediaId: result.media_id };
console.log('Instagram 업로드 성공');
} else {
const errorData = await response.json();
results.instagram = { success: false, error: errorData.detail || '업로드 실패' };
}
} catch (igError) {
console.error('Instagram 업로드 실패:', igError.message);
results.instagram = { success: false, error: igError.message };
}
}
// TikTok 업로드
if (uploadConfig.platforms.tiktok) {
try {
const tiktokService = require('../tiktokService');
const tiktokResult = await tiktokService.uploadVideo(
userId,
videoPath,
seoData.description + ' ' + seoData.hashtags
);
results.tiktok = { success: true, videoId: tiktokResult.videoId };
console.log('TikTok 업로드 성공');
} catch (ttError) {
console.error('TikTok 업로드 실패:', ttError.message);
results.tiktok = { success: false, error: ttError.message };
}
}
return {
skipped: false,
level: uploadConfig.level,
seoData,
results
};
} catch (error) {
console.error('자동 업로드 실행 중 오류:', error);
return {
skipped: false,
error: error.message,
results
};
}
};
/**
* 사용자의 Instagram 계정명 가져오기
*/
const getInstagramUsername = async (userId) => {
return new Promise((resolve, reject) => {
db.get(
'SELECT instagram_username FROM social_connections WHERE user_id = ?',
[userId],
(err, row) => {
if (err || !row) {
resolve(null);
} else {
resolve(row.instagram_username);
}
}
);
});
};
/**
* 업로드 이력 저장
*/
const saveUploadHistory = async (userId, historyId, platform, result) => {
return new Promise((resolve, reject) => {
const query = `
INSERT INTO upload_history (user_id, history_id, platform, status, external_id, error_message, uploaded_at)
VALUES (?, ?, ?, ?, ?, ?, datetime('now'))
`;
db.run(query, [
userId,
historyId,
platform,
result.success ? 'success' : 'failed',
result.videoId || result.mediaId || null,
result.error || null
], (err) => {
if (err) {
console.error('업로드 이력 저장 실패:', err);
}
resolve();
});
});
};
module.exports = {
shouldAutoUpload,
generateAutoSeo,
executeAutoUpload,
saveUploadHistory
};
@@ -0,0 +1,445 @@
/**
* 축제 서비스
* TourAPI 축제 데이터 동기화 및 관리
*/
const { tourApiClient, AREA_CODE, AREA_NAME } = require('./tourApiClient');
class FestivalService {
constructor(db) {
this.db = db;
}
// ============================================
// 축제 데이터 동기화
// ============================================
/**
* 전체 축제 동기화 (향후 6개월)
*/
async syncAllFestivals() {
console.log('=== 축제 데이터 동기화 시작 ===');
const today = tourApiClient.getTodayString();
const endDate = tourApiClient.getDateAfterMonths(6);
let totalSynced = 0;
let pageNo = 1;
while (true) {
try {
const result = await tourApiClient.searchFestival({
eventStartDate: today,
eventEndDate: endDate,
numOfRows: 100,
pageNo,
arrange: 'A',
});
if (!result.items || result.items.length === 0) break;
// 배열로 변환 (단일 아이템일 경우)
const items = Array.isArray(result.items) ? result.items : [result.items];
for (const item of items) {
await this.upsertFestival(item);
totalSynced++;
}
console.log(` - 페이지 ${pageNo}: ${items.length}건 처리`);
if (items.length < 100) break;
pageNo++;
// API 호출 제한 대응
await this.sleep(100);
} catch (error) {
console.error(` - 페이지 ${pageNo} 에러:`, error.message);
break;
}
}
console.log(`=== 축제 동기화 완료: ${totalSynced}건 ===`);
return totalSynced;
}
/**
* 특정 지역 축제 동기화
*/
async syncFestivalsByArea(areaCode) {
console.log(`=== ${AREA_NAME[areaCode] || areaCode} 축제 동기화 ===`);
const today = tourApiClient.getTodayString();
const endDate = tourApiClient.getDateAfterMonths(6);
let totalSynced = 0;
let pageNo = 1;
while (true) {
const result = await tourApiClient.searchFestival({
eventStartDate: today,
eventEndDate: endDate,
areaCode,
numOfRows: 100,
pageNo,
});
if (!result.items || result.items.length === 0) break;
const items = Array.isArray(result.items) ? result.items : [result.items];
for (const item of items) {
await this.upsertFestival(item);
totalSynced++;
}
if (items.length < 100) break;
pageNo++;
await this.sleep(100);
}
return totalSynced;
}
/**
* 축제 데이터 저장/업데이트
*/
async upsertFestival(item) {
const exists = await this.db.get(
'SELECT id FROM festivals WHERE content_id = ?',
[item.contentid]
);
const data = {
content_id: item.contentid,
content_type_id: item.contenttypeid || '15',
title: item.title,
addr1: item.addr1,
addr2: item.addr2,
area_code: item.areacode,
sigungu_code: item.sigungucode,
sido: AREA_NAME[item.areacode] || null,
mapx: item.mapx ? parseFloat(item.mapx) : null,
mapy: item.mapy ? parseFloat(item.mapy) : null,
event_start_date: item.eventstartdate,
event_end_date: item.eventenddate,
first_image: item.firstimage,
first_image2: item.firstimage2,
tel: item.tel,
last_synced_at: new Date().toISOString(),
};
if (exists) {
await this.db.run(`
UPDATE festivals SET
title = ?, addr1 = ?, addr2 = ?, area_code = ?, sigungu_code = ?, sido = ?,
mapx = ?, mapy = ?, event_start_date = ?, event_end_date = ?,
first_image = ?, first_image2 = ?, tel = ?, last_synced_at = ?,
updated_at = CURRENT_TIMESTAMP
WHERE content_id = ?
`, [
data.title, data.addr1, data.addr2, data.area_code, data.sigungu_code, data.sido,
data.mapx, data.mapy, data.event_start_date, data.event_end_date,
data.first_image, data.first_image2, data.tel, data.last_synced_at,
data.content_id
]);
return { action: 'updated', id: exists.id };
} else {
const result = await this.db.run(`
INSERT INTO festivals (
content_id, content_type_id, title, addr1, addr2, area_code, sigungu_code, sido,
mapx, mapy, event_start_date, event_end_date, first_image, first_image2,
tel, last_synced_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`, [
data.content_id, data.content_type_id, data.title, data.addr1, data.addr2,
data.area_code, data.sigungu_code, data.sido, data.mapx, data.mapy,
data.event_start_date, data.event_end_date, data.first_image, data.first_image2,
data.tel, data.last_synced_at
]);
return { action: 'inserted', id: result.lastID };
}
}
/**
* 축제 상세 정보 업데이트
*/
async fetchAndUpdateDetail(contentId) {
try {
const detail = await tourApiClient.getFestivalDetail(contentId);
const { common, intro } = detail;
await this.db.run(`
UPDATE festivals SET
overview = ?,
homepage = ?,
place = ?,
place_info = ?,
play_time = ?,
program = ?,
use_fee = ?,
age_limit = ?,
sponsor1 = ?,
sponsor1_tel = ?,
sponsor2 = ?,
sponsor2_tel = ?,
sub_event = ?,
booking_place = ?,
updated_at = CURRENT_TIMESTAMP
WHERE content_id = ?
`, [
common.overview,
common.homepage,
intro.eventplace,
intro.placeinfo,
intro.playtime,
intro.program,
intro.usetimefestival,
intro.agelimit,
intro.sponsor1,
intro.sponsor1tel,
intro.sponsor2,
intro.sponsor2tel,
intro.subevent,
intro.bookingplace,
contentId
]);
return detail;
} catch (error) {
console.error(`축제 상세 조회 실패 (${contentId}):`, error.message);
return null;
}
}
// ============================================
// 축제 조회
// ============================================
/**
* 활성 축제 목록 (종료되지 않은)
*/
async getActiveFestivals(options = {}) {
const {
areaCode = null,
limit = 20,
offset = 0,
} = options;
const today = tourApiClient.getTodayString();
let query = `
SELECT * FROM festivals
WHERE is_active = 1
AND event_end_date >= ?
`;
const params = [today];
if (areaCode) {
query += ' AND area_code = ?';
params.push(areaCode);
}
query += ' ORDER BY event_start_date ASC LIMIT ? OFFSET ?';
params.push(limit, offset);
return this.db.all(query, params);
}
/**
* 진행중인 축제
*/
async getOngoingFestivals(areaCode = null, limit = 20) {
const today = tourApiClient.getTodayString();
let query = `
SELECT * FROM festivals
WHERE is_active = 1
AND event_start_date <= ?
AND event_end_date >= ?
`;
const params = [today, today];
if (areaCode) {
query += ' AND area_code = ?';
params.push(areaCode);
}
query += ' ORDER BY event_end_date ASC LIMIT ?';
params.push(limit);
return this.db.all(query, params);
}
/**
* 예정 축제
*/
async getUpcomingFestivals(areaCode = null, limit = 20) {
const today = tourApiClient.getTodayString();
let query = `
SELECT * FROM festivals
WHERE is_active = 1
AND event_start_date > ?
`;
const params = [today];
if (areaCode) {
query += ' AND area_code = ?';
params.push(areaCode);
}
query += ' ORDER BY event_start_date ASC LIMIT ?';
params.push(limit);
return this.db.all(query, params);
}
/**
* 축제 상세 조회
*/
async getFestivalById(id) {
const festival = await this.db.get('SELECT * FROM festivals WHERE id = ?', [id]);
if (festival && !festival.overview) {
// 상세 정보가 없으면 API에서 가져오기
await this.fetchAndUpdateDetail(festival.content_id);
return this.db.get('SELECT * FROM festivals WHERE id = ?', [id]);
}
return festival;
}
/**
* content_id로 축제 조회
*/
async getFestivalByContentId(contentId) {
return this.db.get('SELECT * FROM festivals WHERE content_id = ?', [contentId]);
}
/**
* 축제 검색
*/
async searchFestivals(keyword, limit = 20) {
return this.db.all(`
SELECT * FROM festivals
WHERE is_active = 1
AND (title LIKE ? OR addr1 LIKE ?)
AND event_end_date >= ?
ORDER BY event_start_date ASC
LIMIT ?
`, [`%${keyword}%`, `%${keyword}%`, tourApiClient.getTodayString(), limit]);
}
/**
* 월별 축제 조회
*/
async getFestivalsByMonth(year, month) {
const startDate = `${year}${String(month).padStart(2, '0')}01`;
const endDate = `${year}${String(month).padStart(2, '0')}31`;
return this.db.all(`
SELECT * FROM festivals
WHERE is_active = 1
AND event_start_date <= ?
AND event_end_date >= ?
ORDER BY event_start_date ASC
`, [endDate, startDate]);
}
/**
* 지역별 축제 통계
*/
async getFestivalStatsByRegion() {
const today = tourApiClient.getTodayString();
return this.db.all(`
SELECT
area_code,
sido,
COUNT(*) as total,
SUM(CASE WHEN event_start_date <= ? AND event_end_date >= ? THEN 1 ELSE 0 END) as ongoing,
SUM(CASE WHEN event_start_date > ? THEN 1 ELSE 0 END) as upcoming
FROM festivals
WHERE is_active = 1 AND event_end_date >= ?
GROUP BY area_code
ORDER BY total DESC
`, [today, today, today, today]);
}
// ============================================
// 좌표 기반 조회
// ============================================
/**
* 좌표 근처 축제 조회 (DB에서)
*/
async getNearbyFestivals(mapX, mapY, radiusKm = 50) {
const today = tourApiClient.getTodayString();
// 대략적인 위경도 범위 계산 (1도 ≈ 111km)
const latRange = radiusKm / 111;
const lngRange = radiusKm / 88; // 한국 위도 기준
const festivals = await this.db.all(`
SELECT * FROM festivals
WHERE is_active = 1
AND event_end_date >= ?
AND mapx IS NOT NULL AND mapy IS NOT NULL
AND mapy BETWEEN ? AND ?
AND mapx BETWEEN ? AND ?
`, [
today,
mapY - latRange, mapY + latRange,
mapX - lngRange, mapX + lngRange,
]);
// 정확한 거리 계산 및 필터링
return festivals
.map(f => ({
...f,
distance_km: this.calculateDistance(mapY, mapX, f.mapy, f.mapx),
}))
.filter(f => f.distance_km <= radiusKm)
.sort((a, b) => a.distance_km - b.distance_km);
}
/**
* 좌표 근처 축제 조회 (API 직접)
*/
async getNearbyFestivalsFromApi(mapX, mapY, radius = 20000) {
return tourApiClient.getNearbyFestivals(mapX, mapY, radius);
}
// ============================================
// 유틸리티
// ============================================
/**
* Haversine 공식으로 거리 계산 (km)
*/
calculateDistance(lat1, lon1, lat2, lon2) {
const R = 6371; // 지구 반경 (km)
const dLat = this.toRad(lat2 - lat1);
const dLon = this.toRad(lon2 - lon1);
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(this.toRad(lat1)) * Math.cos(this.toRad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return Math.round(R * c * 100) / 100; // 소수점 2자리
}
toRad(deg) {
return deg * (Math.PI / 180);
}
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
module.exports = FestivalService;
@@ -0,0 +1,355 @@
/**
* Geocoding 서비스
* 카카오 Local API를 사용한 주소 ↔ 좌표 변환
*
* 문서: https://developers.kakao.com/docs/latest/ko/local/dev-guide
*/
const axios = require('axios');
class GeocodingService {
constructor() {
this.baseUrl = 'https://dapi.kakao.com/v2/local';
this.apiKey = process.env.KAKAO_REST_KEY;
this.client = axios.create({
baseURL: this.baseUrl,
timeout: 10000,
headers: {
Authorization: `KakaoAK ${this.apiKey}`,
},
});
}
// ============================================
// 주소 → 좌표 변환 (Geocoding)
// ============================================
/**
* 주소를 좌표로 변환
* @param {string} address - 주소 문자열
* @returns {Object|null} { mapx, mapy, address, sido, sigungu, ... }
*/
async geocode(address) {
try {
const response = await this.client.get('/search/address.json', {
params: { query: address },
});
const documents = response.data.documents;
if (!documents || documents.length === 0) {
console.log(`Geocoding: 결과 없음 - "${address}"`);
return null;
}
const result = documents[0];
const addr = result.address || {};
return {
mapx: parseFloat(result.x), // 경도 (longitude)
mapy: parseFloat(result.y), // 위도 (latitude)
address: result.address_name, // 전체 주소
addressType: result.address_type, // REGION, ROAD, ROAD_ADDR
sido: addr.region_1depth_name || null, // 시도
sigungu: addr.region_2depth_name || null, // 시군구
eupmyeondong: addr.region_3depth_name || null, // 읍면동
bCode: addr.b_code || null, // 법정동 코드
hCode: addr.h_code || null, // 행정동 코드
roadAddress: result.road_address?.address_name || null,
};
} catch (error) {
console.error('Geocoding 실패:', address, error.message);
return null;
}
}
/**
* 도로명 주소 검색
*/
async geocodeRoad(address) {
try {
const response = await this.client.get('/search/address.json', {
params: {
query: address,
analyze_type: 'exact', // 정확히 일치
},
});
const documents = response.data.documents;
if (!documents || documents.length === 0) {
return null;
}
// 도로명 주소 결과 우선
const roadResult = documents.find(d => d.road_address);
if (roadResult) {
const road = roadResult.road_address;
return {
mapx: parseFloat(roadResult.x),
mapy: parseFloat(roadResult.y),
address: road.address_name,
roadAddress: road.address_name,
sido: road.region_1depth_name,
sigungu: road.region_2depth_name,
eupmyeondong: road.region_3depth_name,
roadName: road.road_name,
buildingName: road.building_name,
zoneNo: road.zone_no, // 우편번호
};
}
return this.geocode(address);
} catch (error) {
console.error('도로명 Geocoding 실패:', error.message);
return null;
}
}
// ============================================
// 좌표 → 주소 변환 (역지오코딩)
// ============================================
/**
* 좌표를 주소로 변환
* @param {number} mapx - 경도 (longitude)
* @param {number} mapy - 위도 (latitude)
*/
async reverseGeocode(mapx, mapy) {
try {
const response = await this.client.get('/geo/coord2address.json', {
params: {
x: mapx,
y: mapy,
},
});
const documents = response.data.documents;
if (!documents || documents.length === 0) {
return null;
}
const result = documents[0];
const addr = result.address || {};
const road = result.road_address;
return {
address: addr.address_name,
roadAddress: road?.address_name || null,
sido: addr.region_1depth_name, // 시도
sigungu: addr.region_2depth_name, // 시군구
eupmyeondong: addr.region_3depth_name, // 읍면동
hCode: addr.h_code, // 행정동 코드
bCode: addr.b_code, // 법정동 코드
};
} catch (error) {
console.error('역지오코딩 실패:', mapx, mapy, error.message);
return null;
}
}
/**
* 좌표로 행정구역 정보만 조회
*/
async getRegionByCoord(mapx, mapy) {
try {
const response = await this.client.get('/geo/coord2regioncode.json', {
params: {
x: mapx,
y: mapy,
},
});
const documents = response.data.documents;
if (!documents || documents.length === 0) {
return null;
}
// B: 법정동, H: 행정동
const bDong = documents.find(d => d.region_type === 'B');
const hDong = documents.find(d => d.region_type === 'H');
return {
sido: bDong?.region_1depth_name || hDong?.region_1depth_name,
sigungu: bDong?.region_2depth_name || hDong?.region_2depth_name,
eupmyeondong: bDong?.region_3depth_name || hDong?.region_3depth_name,
bCode: bDong?.code,
hCode: hDong?.code,
};
} catch (error) {
console.error('행정구역 조회 실패:', error.message);
return null;
}
}
// ============================================
// 키워드 검색
// ============================================
/**
* 키워드로 장소 검색
* @param {string} keyword - 검색어 (예: "가평 펜션")
* @param {Object} options - { x, y, radius, page, size }
*/
async searchKeyword(keyword, options = {}) {
try {
const params = {
query: keyword,
page: options.page || 1,
size: options.size || 15,
};
// 중심 좌표가 있으면 거리순 정렬
if (options.x && options.y) {
params.x = options.x;
params.y = options.y;
params.sort = 'distance';
if (options.radius) {
params.radius = Math.min(options.radius, 20000); // 최대 20km
}
}
const response = await this.client.get('/search/keyword.json', params);
return {
places: response.data.documents.map(place => ({
id: place.id,
name: place.place_name,
category: place.category_name,
phone: place.phone,
address: place.address_name,
roadAddress: place.road_address_name,
mapx: parseFloat(place.x),
mapy: parseFloat(place.y),
placeUrl: place.place_url,
distance: place.distance ? parseInt(place.distance) : null,
})),
meta: response.data.meta,
};
} catch (error) {
console.error('키워드 검색 실패:', error.message);
return { places: [], meta: {} };
}
}
/**
* 펜션 검색 (지역 + 펜션 키워드)
*/
async searchPensions(region, options = {}) {
return this.searchKeyword(`${region} 펜션`, options);
}
// ============================================
// 지역코드 매핑
// ============================================
/**
* 시도명 → TourAPI 지역코드 변환
*/
getAreaCode(sido) {
const areaCodeMap = {
'서울': '1', '서울특별시': '1',
'인천': '2', '인천광역시': '2',
'대전': '3', '대전광역시': '3',
'대구': '4', '대구광역시': '4',
'광주': '5', '광주광역시': '5',
'부산': '6', '부산광역시': '6',
'울산': '7', '울산광역시': '7',
'세종': '8', '세종특별자치시': '8',
'경기': '31', '경기도': '31',
'강원': '32', '강원도': '32', '강원특별자치도': '32',
'충북': '33', '충청북도': '33',
'충남': '34', '충청남도': '34',
'경북': '35', '경상북도': '35',
'경남': '36', '경상남도': '36',
'전북': '37', '전라북도': '37', '전북특별자치도': '37',
'전남': '38', '전라남도': '38',
'제주': '39', '제주특별자치도': '39',
};
return areaCodeMap[sido] || null;
}
/**
* 좌표에서 TourAPI 지역코드 조회
*/
async getAreaCodeFromCoords(mapx, mapy) {
const region = await this.getRegionByCoord(mapx, mapy);
if (!region) return null;
return {
areaCode: this.getAreaCode(region.sido),
sido: region.sido,
sigungu: region.sigungu,
};
}
// ============================================
// 주소 파싱 유틸리티
// ============================================
/**
* 주소 문자열에서 시도/시군구 추출
*/
parseAddress(address) {
if (!address) return { sido: null, sigungu: null };
const sidoPatterns = [
{ pattern: /^(서울특별시|서울)/, name: '서울' },
{ pattern: /^(부산광역시|부산)/, name: '부산' },
{ pattern: /^(대구광역시|대구)/, name: '대구' },
{ pattern: /^(인천광역시|인천)/, name: '인천' },
{ pattern: /^(광주광역시|광주)/, name: '광주' },
{ pattern: /^(대전광역시|대전)/, name: '대전' },
{ pattern: /^(울산광역시|울산)/, name: '울산' },
{ pattern: /^(세종특별자치시|세종)/, name: '세종' },
{ pattern: /^(경기도|경기)/, name: '경기' },
{ pattern: /^(강원특별자치도|강원도|강원)/, name: '강원' },
{ pattern: /^(충청북도|충북)/, name: '충북' },
{ pattern: /^(충청남도|충남)/, name: '충남' },
{ pattern: /^(전북특별자치도|전라북도|전북)/, name: '전북' },
{ pattern: /^(전라남도|전남)/, name: '전남' },
{ pattern: /^(경상북도|경북)/, name: '경북' },
{ pattern: /^(경상남도|경남)/, name: '경남' },
{ pattern: /^(제주특별자치도|제주)/, name: '제주' },
];
let sido = null;
let sigungu = null;
for (const { pattern, name } of sidoPatterns) {
const match = address.match(pattern);
if (match) {
sido = name;
// 시군구 추출
const remaining = address.slice(match[0].length).trim();
const sigunguMatch = remaining.match(/^([가-힣]+[시군구])/);
if (sigunguMatch) {
sigungu = sigunguMatch[1];
}
break;
}
}
return { sido, sigungu, areaCode: this.getAreaCode(sido) };
}
/**
* 주소 정규화 (검색용)
*/
normalizeAddress(address) {
if (!address) return '';
return address
.replace(/특별시|광역시|특별자치시|특별자치도/g, '')
.replace(/\s+/g, ' ')
.trim();
}
}
// 싱글톤 인스턴스
const geocodingService = new GeocodingService();
module.exports = {
geocodingService,
GeocodingService,
};
@@ -0,0 +1,249 @@
/**
* Scheduler Service
*
* 주간 자동 영상 생성을 위한 cron job 스케줄러
* - 매 시간마다 예약된 작업 확인
* - generation_queue에 작업 추가
* - 워커가 순차적으로 처리
*/
const cron = require('node-cron');
const db = require('../db');
const path = require('path');
/**
* 예약된 자동 생성 작업 확인
*/
const getPendingGenerationJobs = () => {
return new Promise((resolve, reject) => {
const now = new Date().toISOString();
db.all(`
SELECT ags.*, u.username, u.email, pp.brand_name, pp.description, pp.address, pp.pension_types
FROM auto_generation_settings ags
JOIN users u ON ags.user_id = u.id
LEFT JOIN pension_profiles pp ON ags.pension_id = pp.id
WHERE ags.enabled = 1
AND ags.next_scheduled_at <= ?
AND NOT EXISTS (
SELECT 1 FROM generation_queue gq
WHERE gq.user_id = ags.user_id
AND gq.status IN ('pending', 'processing')
)
`, [now], (err, rows) => {
if (err) {
console.error('예약 작업 조회 실패:', err);
return resolve([]);
}
resolve(rows || []);
});
});
};
/**
* 작업 큐에 추가
*/
const addToQueue = (userId, pensionId) => {
return new Promise((resolve, reject) => {
db.run(`
INSERT INTO generation_queue (user_id, pension_id, status, scheduled_at)
VALUES (?, ?, 'pending', datetime('now'))
`, [userId, pensionId], function(err) {
if (err) {
console.error('큐 추가 실패:', err);
return resolve(null);
}
resolve(this.lastID);
});
});
};
/**
* 다음 예약 시간 업데이트
*/
const updateNextScheduledTime = (userId, dayOfWeek, timeOfDay) => {
return new Promise((resolve, reject) => {
const now = new Date();
const [hours, minutes] = (timeOfDay || '09:00').split(':').map(Number);
let next = new Date(now);
next.setHours(hours, minutes, 0, 0);
// 다음 주 같은 요일로 설정
const daysUntilNext = (dayOfWeek - now.getDay() + 7) % 7 || 7;
next.setDate(next.getDate() + daysUntilNext);
const nextIso = next.toISOString();
db.run(`
UPDATE auto_generation_settings
SET next_scheduled_at = ?, last_generated_at = datetime('now')
WHERE user_id = ?
`, [nextIso, userId], (err) => {
if (err) console.error('다음 예약 시간 업데이트 실패:', err);
resolve(nextIso);
});
});
};
/**
* 큐에서 대기 중인 작업 처리
*/
const processPendingQueue = async () => {
return new Promise((resolve, reject) => {
db.get(`
SELECT gq.*, pp.brand_name, pp.description, pp.address, pp.pension_types, pp.user_id
FROM generation_queue gq
LEFT JOIN pension_profiles pp ON gq.pension_id = pp.id
WHERE gq.status = 'pending'
ORDER BY gq.scheduled_at ASC
LIMIT 1
`, async (err, job) => {
if (err || !job) {
return resolve(null);
}
console.log(`[Scheduler] 작업 처리 시작: 사용자 ${job.user_id}, 펜션 ${job.pension_id}`);
// 상태를 processing으로 변경
db.run(`
UPDATE generation_queue
SET status = 'processing', started_at = datetime('now')
WHERE id = ?
`, [job.id]);
try {
// 영상 생성 로직 실행
const result = await generateVideoForJob(job);
// 성공 시 상태 업데이트
db.run(`
UPDATE generation_queue
SET status = 'completed', completed_at = datetime('now'),
result_video_path = ?, result_history_id = ?
WHERE id = ?
`, [result.videoPath, result.historyId, job.id]);
console.log(`[Scheduler] 작업 완료: ${job.id}`);
resolve(result);
} catch (error) {
console.error(`[Scheduler] 작업 실패: ${job.id}`, error);
// 실패 시 상태 업데이트
db.run(`
UPDATE generation_queue
SET status = 'failed', completed_at = datetime('now'),
error_message = ?
WHERE id = ?
`, [error.message, job.id]);
resolve(null);
}
});
});
};
/**
* 실제 영상 생성 실행
* TODO: 실제 영상 생성 로직과 연동 필요
*/
const generateVideoForJob = async (job) => {
// 펜션 정보 기반으로 영상 생성
const businessInfo = {
name: job.brand_name || '펜션',
description: job.description || '',
address: job.address || '',
pensionCategories: job.pension_types ? JSON.parse(job.pension_types) : []
};
// 실제 영상 생성 API 호출 (내부 API 사용)
// 현재는 placeholder - 실제 구현 시 render API 호출 필요
console.log('[Scheduler] 영상 생성 요청:', businessInfo.name);
// TODO: 실제 영상 생성 로직 구현
// const response = await fetch('http://localhost:3001/render', { ... });
return {
videoPath: null, // 실제 생성된 비디오 경로
historyId: null // 히스토리 ID
};
};
/**
* 스케줄러 시작
*/
const startScheduler = () => {
console.log('[Scheduler] 자동 생성 스케줄러 시작');
// 매 시간 정각에 실행 (0분)
cron.schedule('0 * * * *', async () => {
console.log(`[Scheduler] 예약 작업 확인 중... ${new Date().toISOString()}`);
try {
// 예약된 작업 확인
const pendingJobs = await getPendingGenerationJobs();
console.log(`[Scheduler] ${pendingJobs.length}개의 예약 작업 발견`);
for (const job of pendingJobs) {
// 큐에 작업 추가
await addToQueue(job.user_id, job.pension_id);
// 다음 예약 시간 업데이트
await updateNextScheduledTime(job.user_id, job.day_of_week, job.time_of_day);
console.log(`[Scheduler] 작업 예약됨: 사용자 ${job.user_id}`);
}
// 대기 중인 작업 처리
await processPendingQueue();
} catch (error) {
console.error('[Scheduler] 스케줄러 오류:', error);
}
});
// 10분마다 큐 처리 (백업)
cron.schedule('*/10 * * * *', async () => {
try {
await processPendingQueue();
} catch (error) {
console.error('[Scheduler] 큐 처리 오류:', error);
}
});
console.log('[Scheduler] 스케줄러 등록 완료 - 매 시간 정각에 실행');
};
/**
* 수동으로 특정 사용자의 자동 생성 실행
*/
const triggerManualGeneration = async (userId) => {
return new Promise((resolve, reject) => {
db.get(`
SELECT ags.*, pp.id as pension_id
FROM auto_generation_settings ags
LEFT JOIN pension_profiles pp ON ags.pension_id = pp.id OR (pp.user_id = ags.user_id AND pp.is_default = 1)
WHERE ags.user_id = ?
`, [userId], async (err, settings) => {
if (err || !settings) {
return reject(new Error('자동 생성 설정을 찾을 수 없습니다.'));
}
const queueId = await addToQueue(userId, settings.pension_id);
if (!queueId) {
return reject(new Error('큐 추가 실패'));
}
// 즉시 처리
const result = await processPendingQueue();
resolve(result);
});
});
};
module.exports = {
startScheduler,
getPendingGenerationJobs,
processPendingQueue,
triggerManualGeneration
};
@@ -0,0 +1,439 @@
/**
* TourAPI 4.0 클라이언트
* 한국관광공사 국문 관광정보 서비스 (KorService2)
*
* 문서: https://www.data.go.kr/data/15101578/openapi.do
* Base URL: https://apis.data.go.kr/B551011/KorService2
*/
const axios = require('axios');
// 관광타입 ID
const CONTENT_TYPE = {
TOURIST_SPOT: '12', // 관광지
CULTURAL: '14', // 문화시설
FESTIVAL: '15', // 행사/공연/축제
TRAVEL_COURSE: '25', // 여행코스
LEISURE: '28', // 레포츠
STAY: '32', // 숙박 (펜션)
SHOPPING: '38', // 쇼핑
RESTAURANT: '39', // 음식점
};
// 지역코드
const AREA_CODE = {
SEOUL: '1',
INCHEON: '2',
DAEJEON: '3',
DAEGU: '4',
GWANGJU: '5',
BUSAN: '6',
ULSAN: '7',
SEJONG: '8',
GYEONGGI: '31',
GANGWON: '32',
CHUNGBUK: '33',
CHUNGNAM: '34',
GYEONGBUK: '35',
GYEONGNAM: '36',
JEONBUK: '37',
JEONNAM: '38',
JEJU: '39',
};
// 지역코드 이름 매핑
const AREA_NAME = {
'1': '서울',
'2': '인천',
'3': '대전',
'4': '대구',
'5': '광주',
'6': '부산',
'7': '울산',
'8': '세종',
'31': '경기',
'32': '강원',
'33': '충북',
'34': '충남',
'35': '경북',
'36': '경남',
'37': '전북',
'38': '전남',
'39': '제주',
};
class TourApiClient {
constructor() {
this.baseUrl = process.env.TOURAPI_ENDPOINT || 'https://apis.data.go.kr/B551011/KorService2';
this.serviceKey = process.env.TOURAPI_KEY;
this.client = axios.create({
baseURL: this.baseUrl,
timeout: 30000,
});
}
/**
* API 요청 공통 메서드
*/
async request(operation, params = {}) {
try {
const response = await this.client.get(`/${operation}`, {
params: {
serviceKey: this.serviceKey,
MobileOS: 'ETC',
MobileApp: 'CastAD',
_type: 'json',
...params,
},
});
const data = response.data;
// 에러 체크
if (data.response?.header?.resultCode !== '0000') {
const errorMsg = data.response?.header?.resultMsg || 'Unknown error';
throw new Error(`TourAPI Error: ${errorMsg}`);
}
const body = data.response?.body;
return {
items: body?.items?.item || [],
totalCount: body?.totalCount || 0,
pageNo: body?.pageNo || 1,
numOfRows: body?.numOfRows || 10,
};
} catch (error) {
if (error.response?.status === 401) {
throw new Error('TourAPI 인증 실패: 서비스키를 확인하세요');
}
throw error;
}
}
// ============================================
// 지역/분류 코드 조회
// ============================================
/**
* 지역코드 조회
* @param {string} areaCode - 시도 코드 (없으면 전체 시도 조회)
*/
async getAreaCodes(areaCode = null) {
const params = { numOfRows: 100, pageNo: 1 };
if (areaCode) params.areaCode = areaCode;
return this.request('areaCode2', params);
}
/**
* 서비스 분류코드 조회
*/
async getCategoryCodes(contentTypeId = null, cat1 = null, cat2 = null) {
const params = { numOfRows: 100, pageNo: 1 };
if (contentTypeId) params.contentTypeId = contentTypeId;
if (cat1) params.cat1 = cat1;
if (cat2) params.cat2 = cat2;
return this.request('categoryCode2', params);
}
// ============================================
// 축제/행사 조회 (핵심!)
// ============================================
/**
* 행사정보 조회 (축제)
* @param {Object} options
* @param {string} options.eventStartDate - 행사 시작일 (YYYYMMDD) - 필수!
* @param {string} options.eventEndDate - 행사 종료일 (YYYYMMDD)
* @param {string} options.areaCode - 지역코드
* @param {string} options.sigunguCode - 시군구코드
* @param {number} options.numOfRows - 한 페이지 결과 수
* @param {number} options.pageNo - 페이지 번호
* @param {string} options.arrange - 정렬 (A=제목순, C=수정일순, D=생성일순)
*/
async searchFestival(options = {}) {
const {
eventStartDate = this.getTodayString(),
eventEndDate,
areaCode,
sigunguCode,
numOfRows = 100,
pageNo = 1,
arrange = 'A',
} = options;
const params = {
numOfRows,
pageNo,
arrange,
eventStartDate,
};
if (eventEndDate) params.eventEndDate = eventEndDate;
if (areaCode) params.areaCode = areaCode;
if (sigunguCode) params.sigunguCode = sigunguCode;
return this.request('searchFestival2', params);
}
/**
* 진행중인 축제 조회
*/
async getOngoingFestivals(areaCode = null) {
const today = this.getTodayString();
return this.searchFestival({
eventStartDate: '20240101', // 과거부터
eventEndDate: today, // 오늘까지 종료되지 않은
areaCode,
arrange: 'C', // 수정일순
});
}
/**
* 예정 축제 조회 (향후 6개월)
*/
async getUpcomingFestivals(areaCode = null, months = 6) {
const today = this.getTodayString();
const endDate = this.getDateAfterMonths(months);
return this.searchFestival({
eventStartDate: today,
eventEndDate: endDate,
areaCode,
arrange: 'A', // 제목순
});
}
// ============================================
// 숙박 조회 (펜션)
// ============================================
/**
* 숙박정보 조회
* @param {Object} options
* @param {string} options.areaCode - 지역코드
* @param {string} options.sigunguCode - 시군구코드
* @param {number} options.numOfRows - 한 페이지 결과 수
* @param {number} options.pageNo - 페이지 번호
* @param {string} options.arrange - 정렬
*/
async searchStay(options = {}) {
const {
areaCode,
sigunguCode,
numOfRows = 100,
pageNo = 1,
arrange = 'A',
} = options;
const params = { numOfRows, pageNo, arrange };
if (areaCode) params.areaCode = areaCode;
if (sigunguCode) params.sigunguCode = sigunguCode;
return this.request('searchStay2', params);
}
// ============================================
// 지역/위치 기반 조회
// ============================================
/**
* 지역기반 관광정보 조회
*/
async getAreaBasedList(options = {}) {
const {
contentTypeId,
areaCode,
sigunguCode,
cat1, cat2, cat3,
numOfRows = 100,
pageNo = 1,
arrange = 'C',
} = options;
const params = { numOfRows, pageNo, arrange };
if (contentTypeId) params.contentTypeId = contentTypeId;
if (areaCode) params.areaCode = areaCode;
if (sigunguCode) params.sigunguCode = sigunguCode;
if (cat1) params.cat1 = cat1;
if (cat2) params.cat2 = cat2;
if (cat3) params.cat3 = cat3;
return this.request('areaBasedList2', params);
}
/**
* 위치기반 관광정보 조회 (근처 검색)
* @param {number} mapX - 경도 (longitude)
* @param {number} mapY - 위도 (latitude)
* @param {number} radius - 반경 (미터, 최대 20000)
* @param {string} contentTypeId - 관광타입
*/
async getLocationBasedList(mapX, mapY, radius = 10000, contentTypeId = null) {
const params = {
mapX: mapX.toString(),
mapY: mapY.toString(),
radius: Math.min(radius, 20000), // 최대 20km
numOfRows: 100,
pageNo: 1,
arrange: 'E', // 거리순
};
if (contentTypeId) params.contentTypeId = contentTypeId;
return this.request('locationBasedList2', params);
}
/**
* 근처 축제 검색
*/
async getNearbyFestivals(mapX, mapY, radius = 20000) {
return this.getLocationBasedList(mapX, mapY, radius, CONTENT_TYPE.FESTIVAL);
}
/**
* 근처 숙박시설 검색
*/
async getNearbyStay(mapX, mapY, radius = 20000) {
return this.getLocationBasedList(mapX, mapY, radius, CONTENT_TYPE.STAY);
}
// ============================================
// 상세 정보 조회
// ============================================
/**
* 공통정보 조회 (상세정보1)
*/
async getDetailCommon(contentId) {
return this.request('detailCommon2', { contentId });
}
/**
* 소개정보 조회 (상세정보2) - 타입별 상세
*/
async getDetailIntro(contentId, contentTypeId) {
return this.request('detailIntro2', { contentId, contentTypeId });
}
/**
* 반복정보 조회 (상세정보3) - 객실정보 등
*/
async getDetailInfo(contentId, contentTypeId) {
return this.request('detailInfo2', { contentId, contentTypeId });
}
/**
* 이미지정보 조회 (상세정보4)
*/
async getDetailImage(contentId) {
return this.request('detailImage2', { contentId });
}
/**
* 축제 전체 상세정보 조회
*/
async getFestivalDetail(contentId) {
const [common, intro, images] = await Promise.all([
this.getDetailCommon(contentId),
this.getDetailIntro(contentId, CONTENT_TYPE.FESTIVAL),
this.getDetailImage(contentId),
]);
return {
common: common.items[0] || {},
intro: intro.items[0] || {},
images: images.items || [],
};
}
/**
* 숙박 전체 상세정보 조회
*/
async getStayDetail(contentId) {
const [common, intro, rooms, images] = await Promise.all([
this.getDetailCommon(contentId),
this.getDetailIntro(contentId, CONTENT_TYPE.STAY),
this.getDetailInfo(contentId, CONTENT_TYPE.STAY),
this.getDetailImage(contentId),
]);
return {
common: common.items[0] || {},
intro: intro.items[0] || {},
rooms: rooms.items || [],
images: images.items || [],
};
}
// ============================================
// 동기화
// ============================================
/**
* 관광정보 동기화 목록 조회 (변경된 데이터)
*/
async getSyncList(options = {}) {
const {
contentTypeId,
modifiedTime, // YYYYMMDD 형식
numOfRows = 100,
pageNo = 1,
} = options;
const params = { numOfRows, pageNo };
if (contentTypeId) params.contentTypeId = contentTypeId;
if (modifiedTime) params.modifiedtime = modifiedTime;
return this.request('areaBasedSyncList2', params);
}
// ============================================
// 유틸리티
// ============================================
/**
* 오늘 날짜 문자열 (YYYYMMDD)
*/
getTodayString() {
return new Date().toISOString().slice(0, 10).replace(/-/g, '');
}
/**
* N개월 후 날짜 문자열
*/
getDateAfterMonths(months) {
const date = new Date();
date.setMonth(date.getMonth() + months);
return date.toISOString().slice(0, 10).replace(/-/g, '');
}
/**
* 날짜 파싱 (YYYYMMDD -> Date)
*/
parseDate(dateStr) {
if (!dateStr || dateStr.length < 8) return null;
const year = dateStr.slice(0, 4);
const month = dateStr.slice(4, 6);
const day = dateStr.slice(6, 8);
return new Date(`${year}-${month}-${day}`);
}
/**
* 날짜 포맷팅 (YYYYMMDD -> YYYY.MM.DD)
*/
formatDate(dateStr) {
if (!dateStr || dateStr.length < 8) return '';
return `${dateStr.slice(0, 4)}.${dateStr.slice(4, 6)}.${dateStr.slice(6, 8)}`;
}
}
// 싱글톤 인스턴스
const tourApiClient = new TourApiClient();
module.exports = {
tourApiClient,
TourApiClient,
CONTENT_TYPE,
AREA_CODE,
AREA_NAME,
};