init commit from ado4
This commit is contained in:
commit
d820394ccc
126 files changed
+51929
No files matched your search
@@ -0,0 +1 @@
|
||||
{"web":{"client_id":"671727489621-v119rtes771fnrifpmu2pjepja63j4sn.apps.googleusercontent.com","project_id":"grand-solstice-477822-s9","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"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","redirect_uris":["http://localhost:3001/oauth2callback"]}}
|
||||
Binary file not shown.
+506
@@ -0,0 +1,506 @@
|
||||
const sqlite3 = require('sqlite3').verbose();
|
||||
const path = require('path');
|
||||
const bcrypt = require('bcrypt');
|
||||
|
||||
const DB_PATH = path.join(__dirname, 'database.sqlite');
|
||||
|
||||
const db = new sqlite3.Database(DB_PATH, (err) => {
|
||||
if (err) {
|
||||
console.error('데이터베이스 연결 실패:', err.message);
|
||||
} else {
|
||||
console.log('SQLite 데이터베이스에 연결되었습니다.');
|
||||
}
|
||||
});
|
||||
|
||||
// 테이블 초기화
|
||||
db.serialize(() => {
|
||||
// Users 테이블
|
||||
db.run(`CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT UNIQUE NOT NULL,
|
||||
email TEXT UNIQUE,
|
||||
password TEXT NOT NULL,
|
||||
name TEXT,
|
||||
phone TEXT,
|
||||
role TEXT DEFAULT 'user',
|
||||
approved INTEGER DEFAULT 0,
|
||||
email_verified INTEGER DEFAULT 0,
|
||||
verification_token TEXT,
|
||||
reset_token TEXT,
|
||||
reset_token_expiry DATETIME,
|
||||
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)`);
|
||||
|
||||
// 기존 테이블에 새 컬럼 추가 (이미 존재하면 무시)
|
||||
db.run("ALTER TABLE users ADD COLUMN email TEXT UNIQUE", (err) => {});
|
||||
db.run("ALTER TABLE users ADD COLUMN email_verified INTEGER DEFAULT 0", (err) => {});
|
||||
db.run("ALTER TABLE users ADD COLUMN verification_token TEXT", (err) => {});
|
||||
db.run("ALTER TABLE users ADD COLUMN reset_token TEXT", (err) => {});
|
||||
db.run("ALTER TABLE users ADD COLUMN reset_token_expiry DATETIME", (err) => {});
|
||||
// OAuth 컬럼 추가
|
||||
db.run("ALTER TABLE users ADD COLUMN oauth_provider TEXT", (err) => {});
|
||||
db.run("ALTER TABLE users ADD COLUMN oauth_provider_id TEXT", (err) => {});
|
||||
db.run("ALTER TABLE users ADD COLUMN profile_image TEXT", (err) => {});
|
||||
// 크레딧 컬럼 추가 (무료 플랜 기본값 10)
|
||||
db.run("ALTER TABLE users ADD COLUMN credits INTEGER DEFAULT 10", (err) => {});
|
||||
|
||||
// 구독 플랜 컬럼 추가 (free, basic, pro, business)
|
||||
db.run("ALTER TABLE users ADD COLUMN plan_type TEXT DEFAULT 'free'", (err) => {});
|
||||
// 최대 펜션 수 (free/basic: 1, pro: 5, business: unlimited)
|
||||
db.run("ALTER TABLE users ADD COLUMN max_pensions INTEGER DEFAULT 1", (err) => {});
|
||||
// 월간 크레딧 한도 (플랜별 다름, 무료=10)
|
||||
db.run("ALTER TABLE users ADD COLUMN monthly_credits INTEGER DEFAULT 10", (err) => {});
|
||||
// 구독 시작일
|
||||
db.run("ALTER TABLE users ADD COLUMN subscription_started_at DATETIME", (err) => {});
|
||||
// 구독 만료일
|
||||
db.run("ALTER TABLE users ADD COLUMN subscription_expires_at DATETIME", (err) => {});
|
||||
|
||||
// ============================================
|
||||
// 펜션/브랜드 프로필 테이블 (다중 펜션 지원)
|
||||
// ============================================
|
||||
db.run(`CREATE TABLE IF NOT EXISTS pension_profiles (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
is_default INTEGER DEFAULT 0,
|
||||
brand_name TEXT,
|
||||
brand_name_en TEXT,
|
||||
region TEXT,
|
||||
address TEXT,
|
||||
pension_types TEXT,
|
||||
target_customers TEXT,
|
||||
key_features TEXT,
|
||||
nearby_attractions TEXT,
|
||||
booking_url TEXT,
|
||||
homepage_url TEXT,
|
||||
kakao_channel TEXT,
|
||||
instagram_handle TEXT,
|
||||
languages TEXT DEFAULT 'KO',
|
||||
price_range TEXT,
|
||||
description TEXT,
|
||||
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
)`);
|
||||
|
||||
// 펜션별 is_default 컬럼 추가 (기존 테이블용)
|
||||
db.run("ALTER TABLE pension_profiles ADD COLUMN is_default INTEGER DEFAULT 0", (err) => {
|
||||
// 이미 존재하면 에러가 발생하므로 무시
|
||||
});
|
||||
|
||||
// 펜션별 YouTube 플레이리스트 ID 직접 연결
|
||||
db.run("ALTER TABLE pension_profiles ADD COLUMN youtube_playlist_id TEXT", (err) => {});
|
||||
db.run("ALTER TABLE pension_profiles ADD COLUMN youtube_playlist_title TEXT", (err) => {});
|
||||
|
||||
// ============================================
|
||||
// YouTube 분석 데이터 캐시 테이블 (펜션별)
|
||||
// ============================================
|
||||
db.run(`CREATE TABLE IF NOT EXISTS youtube_analytics (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
pension_id INTEGER NOT NULL,
|
||||
playlist_id TEXT NOT NULL,
|
||||
date DATE NOT NULL,
|
||||
views INTEGER DEFAULT 0,
|
||||
playlist_starts INTEGER DEFAULT 0,
|
||||
average_time_in_playlist REAL DEFAULT 0,
|
||||
estimated_minutes_watched REAL DEFAULT 0,
|
||||
subscribers_gained INTEGER DEFAULT 0,
|
||||
likes INTEGER DEFAULT 0,
|
||||
comments INTEGER DEFAULT 0,
|
||||
shares INTEGER DEFAULT 0,
|
||||
cached_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(pension_id) REFERENCES pension_profiles(id) ON DELETE CASCADE,
|
||||
UNIQUE(pension_id, date)
|
||||
)`);
|
||||
|
||||
// 펜션별 월간 요약 통계 테이블
|
||||
db.run(`CREATE TABLE IF NOT EXISTS pension_monthly_stats (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
pension_id INTEGER NOT NULL,
|
||||
year_month TEXT NOT NULL,
|
||||
total_views INTEGER DEFAULT 0,
|
||||
total_videos INTEGER DEFAULT 0,
|
||||
total_watch_time REAL DEFAULT 0,
|
||||
avg_view_duration REAL DEFAULT 0,
|
||||
top_video_id TEXT,
|
||||
growth_rate REAL DEFAULT 0,
|
||||
cached_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(pension_id) REFERENCES pension_profiles(id) ON DELETE CASCADE,
|
||||
UNIQUE(pension_id, year_month)
|
||||
)`);
|
||||
|
||||
|
||||
// ============================================
|
||||
// YouTube OAuth 토큰 테이블
|
||||
// ============================================
|
||||
db.run(`CREATE TABLE IF NOT EXISTS youtube_connections (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER UNIQUE NOT NULL,
|
||||
google_user_id TEXT,
|
||||
google_email TEXT,
|
||||
youtube_channel_id TEXT,
|
||||
youtube_channel_title TEXT,
|
||||
access_token TEXT,
|
||||
refresh_token TEXT,
|
||||
token_expiry DATETIME,
|
||||
scopes TEXT,
|
||||
connected_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
)`);
|
||||
|
||||
// ============================================
|
||||
// YouTube 업로드 설정 테이블
|
||||
// ============================================
|
||||
db.run(`CREATE TABLE IF NOT EXISTS youtube_settings (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER UNIQUE NOT NULL,
|
||||
default_privacy TEXT DEFAULT 'private',
|
||||
default_category_id TEXT DEFAULT '19',
|
||||
default_tags TEXT,
|
||||
default_hashtags TEXT,
|
||||
auto_upload INTEGER DEFAULT 0,
|
||||
upload_timing TEXT DEFAULT 'manual',
|
||||
scheduled_day TEXT,
|
||||
scheduled_time TEXT,
|
||||
default_playlist_id TEXT,
|
||||
notify_on_upload INTEGER DEFAULT 1,
|
||||
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
)`);
|
||||
|
||||
// ============================================
|
||||
// YouTube 플레이리스트 캐시 테이블 (펜션별 연결 지원)
|
||||
// ============================================
|
||||
db.run(`CREATE TABLE IF NOT EXISTS youtube_playlists (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
pension_id INTEGER,
|
||||
playlist_id TEXT NOT NULL,
|
||||
title TEXT,
|
||||
item_count INTEGER DEFAULT 0,
|
||||
cached_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(pension_id) REFERENCES pension_profiles(id) ON DELETE SET NULL,
|
||||
UNIQUE(user_id, playlist_id)
|
||||
)`);
|
||||
|
||||
// 플레이리스트에 pension_id 컬럼 추가 (기존 테이블용)
|
||||
db.run("ALTER TABLE youtube_playlists ADD COLUMN pension_id INTEGER", (err) => {
|
||||
// 이미 존재하면 에러가 발생하므로 무시
|
||||
});
|
||||
|
||||
// ============================================
|
||||
// 업로드 히스토리 테이블 (펜션별 연결 지원)
|
||||
// ============================================
|
||||
db.run(`CREATE TABLE IF NOT EXISTS upload_history (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
pension_id INTEGER,
|
||||
history_id INTEGER,
|
||||
youtube_video_id TEXT,
|
||||
youtube_url TEXT,
|
||||
title TEXT,
|
||||
privacy_status TEXT,
|
||||
playlist_id TEXT,
|
||||
uploaded_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
status TEXT DEFAULT 'completed',
|
||||
error_message TEXT,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(pension_id) REFERENCES pension_profiles(id) ON DELETE SET NULL,
|
||||
FOREIGN KEY(history_id) REFERENCES history(id) ON DELETE SET NULL
|
||||
)`);
|
||||
|
||||
// 업로드 히스토리에 pension_id 컬럼 추가 (기존 테이블용)
|
||||
db.run("ALTER TABLE upload_history ADD COLUMN pension_id INTEGER", (err) => {
|
||||
// 이미 존재하면 에러가 발생하므로 무시
|
||||
});
|
||||
|
||||
// ============================================
|
||||
// Instagram 연결 정보 테이블
|
||||
// ============================================
|
||||
db.run(`CREATE TABLE IF NOT EXISTS instagram_connections (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER UNIQUE NOT NULL,
|
||||
instagram_username TEXT NOT NULL,
|
||||
encrypted_password TEXT NOT NULL,
|
||||
encrypted_session TEXT,
|
||||
is_active INTEGER DEFAULT 1,
|
||||
last_login_at DATETIME,
|
||||
two_factor_required INTEGER DEFAULT 0,
|
||||
connected_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
)`);
|
||||
|
||||
// ============================================
|
||||
// Instagram 업로드 설정 테이블
|
||||
// ============================================
|
||||
db.run(`CREATE TABLE IF NOT EXISTS instagram_settings (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER UNIQUE NOT NULL,
|
||||
auto_upload INTEGER DEFAULT 0,
|
||||
upload_as_reel INTEGER DEFAULT 1,
|
||||
default_caption_template TEXT,
|
||||
default_hashtags TEXT,
|
||||
max_uploads_per_week INTEGER DEFAULT 1,
|
||||
notify_on_upload INTEGER DEFAULT 1,
|
||||
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
)`);
|
||||
|
||||
// ============================================
|
||||
// Instagram 업로드 히스토리 테이블
|
||||
// ============================================
|
||||
db.run(`CREATE TABLE IF NOT EXISTS instagram_upload_history (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
pension_id INTEGER,
|
||||
history_id INTEGER,
|
||||
instagram_media_id TEXT,
|
||||
instagram_post_code TEXT,
|
||||
permalink TEXT,
|
||||
caption TEXT,
|
||||
upload_type TEXT DEFAULT 'reel',
|
||||
status TEXT DEFAULT 'pending',
|
||||
error_message TEXT,
|
||||
retry_count INTEGER DEFAULT 0,
|
||||
uploaded_at DATETIME,
|
||||
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(pension_id) REFERENCES pension_profiles(id) ON DELETE SET NULL,
|
||||
FOREIGN KEY(history_id) REFERENCES history(id) ON DELETE SET NULL
|
||||
)`);
|
||||
|
||||
// ============================================
|
||||
// TikTok 연결 정보 테이블
|
||||
// ============================================
|
||||
db.run(`CREATE TABLE IF NOT EXISTS tiktok_connections (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER UNIQUE NOT NULL,
|
||||
open_id TEXT NOT NULL,
|
||||
display_name TEXT,
|
||||
avatar_url TEXT,
|
||||
follower_count INTEGER DEFAULT 0,
|
||||
following_count INTEGER DEFAULT 0,
|
||||
access_token TEXT NOT NULL,
|
||||
refresh_token TEXT,
|
||||
token_expiry DATETIME,
|
||||
scopes TEXT,
|
||||
connected_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
)`);
|
||||
|
||||
// ============================================
|
||||
// TikTok 업로드 설정 테이블
|
||||
// ============================================
|
||||
db.run(`CREATE TABLE IF NOT EXISTS tiktok_settings (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER UNIQUE NOT NULL,
|
||||
default_privacy TEXT DEFAULT 'SELF_ONLY',
|
||||
disable_duet INTEGER DEFAULT 0,
|
||||
disable_comment INTEGER DEFAULT 0,
|
||||
disable_stitch INTEGER DEFAULT 0,
|
||||
auto_upload INTEGER DEFAULT 0,
|
||||
upload_to_inbox INTEGER DEFAULT 1,
|
||||
default_hashtags TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
)`);
|
||||
|
||||
// ============================================
|
||||
// TikTok 업로드 히스토리 테이블
|
||||
// ============================================
|
||||
db.run(`CREATE TABLE IF NOT EXISTS tiktok_upload_history (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
pension_id INTEGER,
|
||||
history_id INTEGER,
|
||||
publish_id TEXT,
|
||||
video_id TEXT,
|
||||
title TEXT,
|
||||
privacy_level TEXT DEFAULT 'SELF_ONLY',
|
||||
status TEXT DEFAULT 'pending',
|
||||
error_message TEXT,
|
||||
uploaded_at DATETIME,
|
||||
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(pension_id) REFERENCES pension_profiles(id) ON DELETE SET NULL,
|
||||
FOREIGN KEY(history_id) REFERENCES history(id) ON DELETE SET NULL
|
||||
)`);
|
||||
|
||||
// ============================================
|
||||
// 플랫폼 통합 통계 테이블 (YouTube, Instagram, TikTok)
|
||||
// ============================================
|
||||
db.run(`CREATE TABLE IF NOT EXISTS platform_stats (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
pension_id INTEGER,
|
||||
platform TEXT NOT NULL,
|
||||
date DATE NOT NULL,
|
||||
views INTEGER DEFAULT 0,
|
||||
likes INTEGER DEFAULT 0,
|
||||
comments INTEGER DEFAULT 0,
|
||||
shares INTEGER DEFAULT 0,
|
||||
followers_gained INTEGER DEFAULT 0,
|
||||
impressions INTEGER DEFAULT 0,
|
||||
reach INTEGER DEFAULT 0,
|
||||
engagement_rate REAL DEFAULT 0,
|
||||
cached_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(pension_id) REFERENCES pension_profiles(id) ON DELETE SET NULL,
|
||||
UNIQUE(user_id, pension_id, platform, date)
|
||||
)`);
|
||||
|
||||
// ============================================
|
||||
// 시스템 활동 로그 테이블 (어드민 분석용)
|
||||
// ============================================
|
||||
db.run(`CREATE TABLE IF NOT EXISTS activity_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER,
|
||||
action_type TEXT NOT NULL,
|
||||
action_detail TEXT,
|
||||
ip_address TEXT,
|
||||
user_agent TEXT,
|
||||
metadata TEXT,
|
||||
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE SET NULL
|
||||
)`);
|
||||
|
||||
// ============================================
|
||||
// 시스템 통계 스냅샷 테이블 (일별 집계)
|
||||
// ============================================
|
||||
db.run(`CREATE TABLE IF NOT EXISTS system_stats_daily (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
date DATE UNIQUE NOT NULL,
|
||||
total_users INTEGER DEFAULT 0,
|
||||
new_users INTEGER DEFAULT 0,
|
||||
active_users INTEGER DEFAULT 0,
|
||||
total_videos_generated INTEGER DEFAULT 0,
|
||||
total_uploads INTEGER DEFAULT 0,
|
||||
youtube_uploads INTEGER DEFAULT 0,
|
||||
instagram_uploads INTEGER DEFAULT 0,
|
||||
tiktok_uploads INTEGER DEFAULT 0,
|
||||
total_credits_used INTEGER DEFAULT 0,
|
||||
avg_generation_time REAL DEFAULT 0,
|
||||
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)`);
|
||||
|
||||
// ============================================
|
||||
// 사용자 에셋 테이블 (이미지, 오디오, 비디오)
|
||||
// ============================================
|
||||
db.run(`CREATE TABLE IF NOT EXISTS user_assets (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
pension_id INTEGER,
|
||||
history_id INTEGER,
|
||||
asset_type TEXT NOT NULL,
|
||||
source_type TEXT NOT NULL,
|
||||
file_name TEXT NOT NULL,
|
||||
file_path TEXT NOT NULL,
|
||||
file_size INTEGER DEFAULT 0,
|
||||
mime_type TEXT,
|
||||
thumbnail_path TEXT,
|
||||
duration REAL,
|
||||
width INTEGER,
|
||||
height INTEGER,
|
||||
metadata TEXT,
|
||||
is_deleted INTEGER DEFAULT 0,
|
||||
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(pension_id) REFERENCES pension_profiles(id) ON DELETE SET NULL,
|
||||
FOREIGN KEY(history_id) REFERENCES history(id) ON DELETE SET NULL
|
||||
)`);
|
||||
|
||||
// 사용자별 스토리지 한도 컬럼 추가 (MB 단위, 기본 500MB)
|
||||
db.run("ALTER TABLE users ADD COLUMN storage_limit INTEGER DEFAULT 500", (err) => {});
|
||||
// 현재 사용 용량 (캐시)
|
||||
db.run("ALTER TABLE users ADD COLUMN storage_used INTEGER DEFAULT 0", (err) => {});
|
||||
|
||||
// ============================================
|
||||
// 크레딧 요청 테이블
|
||||
// ============================================
|
||||
db.run(`CREATE TABLE IF NOT EXISTS credit_requests (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
requested_credits INTEGER DEFAULT 10,
|
||||
status TEXT DEFAULT 'pending',
|
||||
reason TEXT,
|
||||
admin_note TEXT,
|
||||
processed_by INTEGER,
|
||||
processed_at DATETIME,
|
||||
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(processed_by) REFERENCES users(id) ON DELETE SET NULL
|
||||
)`);
|
||||
|
||||
// ============================================
|
||||
// 크레딧 히스토리 테이블 (변동 내역 추적)
|
||||
// ============================================
|
||||
db.run(`CREATE TABLE IF NOT EXISTS credit_history (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
amount INTEGER NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
description TEXT,
|
||||
balance_after INTEGER,
|
||||
related_request_id INTEGER,
|
||||
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(related_request_id) REFERENCES credit_requests(id) ON DELETE SET NULL
|
||||
)`);
|
||||
|
||||
// 기존 테이블에 business_name 컬럼 추가 (존재하지 않을 경우를 대비해 try-catch 대신 별도 실행)
|
||||
// SQLite는 IF NOT EXISTS 컬럼 추가를 지원하지 않으므로, 에러를 무시하는 방식으로 처리하거나 스키마 버전을 관리해야 함.
|
||||
// 여기서는 간단히 컬럼 추가 시도 후 에러 무시 패턴을 사용.
|
||||
db.run("ALTER TABLE users ADD COLUMN business_name TEXT", (err) => {
|
||||
// 이미 존재하면 에러가 발생하므로 무시
|
||||
});
|
||||
|
||||
db.run("ALTER TABLE history ADD COLUMN final_video_path TEXT", (err) => {
|
||||
// 이미 존재하면 에러가 발생하므로 무시
|
||||
});
|
||||
|
||||
db.run("ALTER TABLE history ADD COLUMN poster_path TEXT", (err) => {
|
||||
// 이미 존재하면 에러가 발생하므로 무시
|
||||
});
|
||||
|
||||
db.run("ALTER TABLE history ADD COLUMN pension_id INTEGER", (err) => {
|
||||
// 이미 존재하면 에러가 발생하므로 무시
|
||||
});
|
||||
|
||||
// History 테이블
|
||||
db.run(`CREATE TABLE IF NOT EXISTS history (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER,
|
||||
business_name TEXT,
|
||||
details TEXT,
|
||||
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id)
|
||||
)`);
|
||||
|
||||
// 기본 관리자 계정 생성 (존재하지 않을 경우)
|
||||
const adminUsername = 'admin';
|
||||
const adminPassword = 'admin123'; // 초기 비밀번호
|
||||
|
||||
db.get("SELECT * FROM users WHERE username = ?", [adminUsername], (err, row) => {
|
||||
if (!row) {
|
||||
const salt = bcrypt.genSaltSync(10);
|
||||
const hash = bcrypt.hashSync(adminPassword, salt);
|
||||
|
||||
db.run(`INSERT INTO users (username, password, name, phone, role, approved, credits)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
[adminUsername, hash, 'Super Admin', '000-0000-0000', 'admin', 1, 999999],
|
||||
(err) => {
|
||||
if (err) console.error("초기 관리자 생성 실패:", err);
|
||||
else console.log(`초기 관리자 계정 생성 완료. (ID: ${adminUsername}, PW: ${adminPassword})`);
|
||||
});
|
||||
} else if (row.role === 'admin' && (row.credits === null || row.credits < 999999)) {
|
||||
// 기존 관리자에게 무제한 크레딧 부여
|
||||
db.run("UPDATE users SET credits = 999999 WHERE id = ?", [row.id]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
module.exports = db;
|
||||
@@ -0,0 +1,237 @@
|
||||
/**
|
||||
* Email Service using Resend
|
||||
*
|
||||
* 환경변수 필요:
|
||||
* - RESEND_API_KEY: Resend API 키 (https://resend.com에서 발급)
|
||||
* - RESEND_FROM_EMAIL: 발신 이메일 (도메인 인증 전에는 'onboarding@resend.dev' 사용)
|
||||
* - FRONTEND_URL: 프론트엔드 URL (인증 링크용)
|
||||
*/
|
||||
|
||||
const { Resend } = require('resend');
|
||||
|
||||
// Resend 인스턴스 - API 키가 없으면 null (이메일 기능 비활성화)
|
||||
let resend = null;
|
||||
const RESEND_API_KEY = process.env.RESEND_API_KEY;
|
||||
|
||||
if (RESEND_API_KEY && RESEND_API_KEY !== 'your-resend-api-key') {
|
||||
resend = new Resend(RESEND_API_KEY);
|
||||
console.log('📧 이메일 서비스 활성화됨 (Resend)');
|
||||
} else {
|
||||
console.warn('⚠️ 이메일 서비스 비활성화됨: RESEND_API_KEY가 설정되지 않았습니다.');
|
||||
console.warn(' 이메일 인증 기능을 사용하려면 .env에 RESEND_API_KEY를 설정하세요.');
|
||||
}
|
||||
|
||||
// 기본 발신 이메일 (도메인 미인증 시 Resend 기본 도메인 사용)
|
||||
const FROM_EMAIL = process.env.RESEND_FROM_EMAIL || 'CastAD <onboarding@resend.dev>';
|
||||
const FRONTEND_URL = process.env.FRONTEND_URL || 'http://localhost:3000';
|
||||
|
||||
/**
|
||||
* 이메일 인증 메일 발송
|
||||
*/
|
||||
async function sendVerificationEmail(to, name, verificationToken) {
|
||||
if (!resend) {
|
||||
console.warn('이메일 발송 건너뜀 (서비스 비활성화):', to);
|
||||
return { success: false, error: '이메일 서비스가 설정되지 않았습니다', disabled: true };
|
||||
}
|
||||
|
||||
const verifyUrl = `${FRONTEND_URL}/verify-email?token=${verificationToken}`;
|
||||
|
||||
try {
|
||||
const { data, error } = await resend.emails.send({
|
||||
from: FROM_EMAIL,
|
||||
to: [to],
|
||||
subject: '[CastAD] 이메일 인증을 완료해주세요',
|
||||
html: `
|
||||
<div style="font-family: 'Apple SD Gothic Neo', 'Malgun Gothic', sans-serif; max-width: 600px; margin: 0 auto; padding: 40px 20px;">
|
||||
<div style="text-align: center; margin-bottom: 40px;">
|
||||
<h1 style="color: #6366f1; margin: 0;">CastAD</h1>
|
||||
<p style="color: #64748b; margin-top: 8px;">AI 펜션 마케팅 영상 제작</p>
|
||||
</div>
|
||||
|
||||
<div style="background: #f8fafc; border-radius: 12px; padding: 32px;">
|
||||
<h2 style="margin: 0 0 16px 0; color: #1e293b;">안녕하세요, ${name || '고객'}님!</h2>
|
||||
<p style="color: #475569; line-height: 1.6; margin: 0 0 24px 0;">
|
||||
CastAD 회원가입을 환영합니다. 아래 버튼을 클릭하여 이메일 인증을 완료해주세요.
|
||||
</p>
|
||||
|
||||
<div style="text-align: center; margin: 32px 0;">
|
||||
<a href="${verifyUrl}"
|
||||
style="display: inline-block; background: #6366f1; color: white; padding: 14px 32px; border-radius: 8px; text-decoration: none; font-weight: 600;">
|
||||
이메일 인증하기
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<p style="color: #64748b; font-size: 14px; margin: 24px 0 0 0;">
|
||||
버튼이 작동하지 않으면 아래 링크를 브라우저에 복사해주세요:<br>
|
||||
<a href="${verifyUrl}" style="color: #6366f1; word-break: break-all;">${verifyUrl}</a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div style="text-align: center; margin-top: 32px; color: #94a3b8; font-size: 12px;">
|
||||
<p>이 이메일은 CastAD 회원가입 요청으로 발송되었습니다.</p>
|
||||
<p>본인이 요청하지 않았다면 이 이메일을 무시해주세요.</p>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
});
|
||||
|
||||
if (error) {
|
||||
console.error('이메일 발송 실패:', error);
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
|
||||
console.log('인증 이메일 발송 완료:', data.id);
|
||||
return { success: true, id: data.id };
|
||||
} catch (err) {
|
||||
console.error('이메일 발송 예외:', err);
|
||||
return { success: false, error: err.message };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 비밀번호 재설정 이메일 발송
|
||||
*/
|
||||
async function sendPasswordResetEmail(to, name, resetToken) {
|
||||
if (!resend) {
|
||||
console.warn('이메일 발송 건너뜀 (서비스 비활성화):', to);
|
||||
return { success: false, error: '이메일 서비스가 설정되지 않았습니다', disabled: true };
|
||||
}
|
||||
|
||||
const resetUrl = `${FRONTEND_URL}/reset-password?token=${resetToken}`;
|
||||
|
||||
try {
|
||||
const { data, error } = await resend.emails.send({
|
||||
from: FROM_EMAIL,
|
||||
to: [to],
|
||||
subject: '[CastAD] 비밀번호 재설정 안내',
|
||||
html: `
|
||||
<div style="font-family: 'Apple SD Gothic Neo', 'Malgun Gothic', sans-serif; max-width: 600px; margin: 0 auto; padding: 40px 20px;">
|
||||
<div style="text-align: center; margin-bottom: 40px;">
|
||||
<h1 style="color: #6366f1; margin: 0;">CastAD</h1>
|
||||
<p style="color: #64748b; margin-top: 8px;">AI 펜션 마케팅 영상 제작</p>
|
||||
</div>
|
||||
|
||||
<div style="background: #f8fafc; border-radius: 12px; padding: 32px;">
|
||||
<h2 style="margin: 0 0 16px 0; color: #1e293b;">비밀번호 재설정</h2>
|
||||
<p style="color: #475569; line-height: 1.6; margin: 0 0 24px 0;">
|
||||
${name || '고객'}님, 비밀번호 재설정을 요청하셨습니다.<br>
|
||||
아래 버튼을 클릭하여 새 비밀번호를 설정해주세요.
|
||||
</p>
|
||||
|
||||
<div style="text-align: center; margin: 32px 0;">
|
||||
<a href="${resetUrl}"
|
||||
style="display: inline-block; background: #6366f1; color: white; padding: 14px 32px; border-radius: 8px; text-decoration: none; font-weight: 600;">
|
||||
비밀번호 재설정하기
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div style="background: #fef3c7; border-radius: 8px; padding: 16px; margin: 24px 0;">
|
||||
<p style="color: #92400e; font-size: 14px; margin: 0;">
|
||||
⚠️ 이 링크는 1시간 동안만 유효합니다.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<p style="color: #64748b; font-size: 14px; margin: 0;">
|
||||
버튼이 작동하지 않으면 아래 링크를 브라우저에 복사해주세요:<br>
|
||||
<a href="${resetUrl}" style="color: #6366f1; word-break: break-all;">${resetUrl}</a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div style="text-align: center; margin-top: 32px; color: #94a3b8; font-size: 12px;">
|
||||
<p>본인이 비밀번호 재설정을 요청하지 않았다면 이 이메일을 무시해주세요.</p>
|
||||
<p>계정은 안전하게 보호됩니다.</p>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
});
|
||||
|
||||
if (error) {
|
||||
console.error('비밀번호 재설정 이메일 발송 실패:', error);
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
|
||||
console.log('비밀번호 재설정 이메일 발송 완료:', data.id);
|
||||
return { success: true, id: data.id };
|
||||
} catch (err) {
|
||||
console.error('이메일 발송 예외:', err);
|
||||
return { success: false, error: err.message };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 환영 이메일 발송 (인증 완료 후)
|
||||
*/
|
||||
async function sendWelcomeEmail(to, name) {
|
||||
if (!resend) {
|
||||
console.warn('이메일 발송 건너뜀 (서비스 비활성화):', to);
|
||||
return { success: false, error: '이메일 서비스가 설정되지 않았습니다', disabled: true };
|
||||
}
|
||||
|
||||
try {
|
||||
const { data, error } = await resend.emails.send({
|
||||
from: FROM_EMAIL,
|
||||
to: [to],
|
||||
subject: '[CastAD] 가입을 환영합니다! 🎉',
|
||||
html: `
|
||||
<div style="font-family: 'Apple SD Gothic Neo', 'Malgun Gothic', sans-serif; max-width: 600px; margin: 0 auto; padding: 40px 20px;">
|
||||
<div style="text-align: center; margin-bottom: 40px;">
|
||||
<h1 style="color: #6366f1; margin: 0;">CastAD</h1>
|
||||
<p style="color: #64748b; margin-top: 8px;">AI 펜션 마케팅 영상 제작</p>
|
||||
</div>
|
||||
|
||||
<div style="background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%); border-radius: 12px; padding: 32px; color: white;">
|
||||
<h2 style="margin: 0 0 16px 0;">🎉 환영합니다, ${name || '고객'}님!</h2>
|
||||
<p style="line-height: 1.6; margin: 0; opacity: 0.9;">
|
||||
CastAD 가입이 완료되었습니다.<br>
|
||||
이제 AI가 만드는 펜션 마케팅 영상을 경험해보세요!
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div style="margin-top: 32px; padding: 24px; background: #f8fafc; border-radius: 12px;">
|
||||
<h3 style="margin: 0 0 16px 0; color: #1e293b;">시작하기</h3>
|
||||
<ul style="color: #475569; line-height: 2; padding-left: 20px; margin: 0;">
|
||||
<li>펜션 정보를 등록하세요</li>
|
||||
<li>사진을 업로드하고 AI 영상을 생성하세요</li>
|
||||
<li>YouTube에 바로 업로드하세요</li>
|
||||
</ul>
|
||||
|
||||
<div style="text-align: center; margin-top: 24px;">
|
||||
<a href="${FRONTEND_URL}/app"
|
||||
style="display: inline-block; background: #6366f1; color: white; padding: 14px 32px; border-radius: 8px; text-decoration: none; font-weight: 600;">
|
||||
CastAD 시작하기
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="text-align: center; margin-top: 32px; color: #94a3b8; font-size: 12px;">
|
||||
<p>문의사항이 있으시면 언제든 연락주세요.</p>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
});
|
||||
|
||||
if (error) {
|
||||
console.error('환영 이메일 발송 실패:', error);
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
|
||||
return { success: true, id: data.id };
|
||||
} catch (err) {
|
||||
console.error('이메일 발송 예외:', err);
|
||||
return { success: false, error: err.message };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 이메일 서비스 활성화 여부 확인
|
||||
*/
|
||||
function isEmailServiceEnabled() {
|
||||
return resend !== null;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
sendVerificationEmail,
|
||||
sendPasswordResetEmail,
|
||||
sendWelcomeEmail,
|
||||
isEmailServiceEnabled
|
||||
};
|
||||
@@ -0,0 +1,805 @@
|
||||
const { GoogleGenAI, Type, Modality } = require('@google/genai');
|
||||
|
||||
const GEMINI_API_KEY = process.env.VITE_GEMINI_API_KEY; // .env에서 API 키 로드
|
||||
|
||||
const getVoiceName = (config) => {
|
||||
if (config.gender === 'Female') {
|
||||
if (config.tone === 'Bright' || config.tone === 'Energetic') return 'Zephyr';
|
||||
return 'Kore';
|
||||
} else {
|
||||
if (config.tone === 'Professional' || config.tone === 'Calm') return 'Charon';
|
||||
if (config.tone === 'Energetic') return 'Fenrir';
|
||||
return 'Puck';
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 서버 사이드에서 창의적 콘텐츠 생성 (광고 카피 & 가사/스크립트) - Gemini 2.0 Flash
|
||||
* 업체의 이미지와 정보를 분석하여 마케팅에 최적화된 문구를 생성합니다.
|
||||
*
|
||||
* @param {object} info - 비즈니스 정보 객체 (BusinessInfo와 유사)
|
||||
* @param {Array<object>} info.images - Base64 인코딩된 이미지 데이터 배열 ({ mimeType, base64 })
|
||||
* @param {string} info.name - 브랜드 이름
|
||||
* @param {string} info.description - 브랜드 설명
|
||||
* @param {string} info.audioMode - 오디오 모드
|
||||
* @param {string} info.musicGenre - 음악 장르
|
||||
* @param {string} info.musicDuration - 음악 길이
|
||||
* @param {object} info.ttsConfig - TTS 설정
|
||||
* @param {string} info.language - 콘텐츠 생성 언어
|
||||
* @param {Array<string>} info.pensionCategories - 펜션 카테고리 배열
|
||||
* @returns {Promise<{adCopy: string[], lyrics: string}>}
|
||||
*/
|
||||
const generateCreativeContent = async (info) => {
|
||||
if (!GEMINI_API_KEY) {
|
||||
throw new Error("Gemini API Key가 서버에 설정되지 않았습니다.");
|
||||
}
|
||||
const ai = new GoogleGenAI({ apiKey: GEMINI_API_KEY });
|
||||
|
||||
const imageParts = info.images.map((imageData) => ({
|
||||
inlineData: { mimeType: imageData.mimeType, data: imageData.base64 }
|
||||
}));
|
||||
|
||||
const lyricStructureInstruction = info.musicDuration === 'Short'
|
||||
? `
|
||||
- **길이 제약사항**: 노래는 반드시 30초 이내여야 함.
|
||||
- **구조**: [Verse 1] -> [Chorus] -> [Outro] 만 포함할 것.
|
||||
- **줄 수**: 총 8줄 이내. 짧고 리듬감 있게 작성.
|
||||
`
|
||||
: `
|
||||
- **길이**: 전체 길이 곡 (약 2분).
|
||||
- **구조**: [Verse 1] -> [Chorus] -> [Verse 2] -> [Chorus] -> [Outro].
|
||||
`;
|
||||
|
||||
const langMap = {
|
||||
'KO': '한국어 (Korean)',
|
||||
'EN': '영어 (English)',
|
||||
'JA': '일본어 (Japanese)',
|
||||
'ZH': '중국어 (Chinese, Simplified)',
|
||||
'TH': '태국어 (Thai)',
|
||||
'VI': '베트남어 (Vietnamese)'
|
||||
};
|
||||
const targetLang = langMap[info.language] || '한국어 (Korean)';
|
||||
|
||||
// 펜션 카테고리 매핑 (한국어 설명)
|
||||
const categoryMap = {
|
||||
'PoolVilla': '풀빌라 (프라이빗 수영장)',
|
||||
'OceanView': '오션뷰 (바다 전망)',
|
||||
'Mountain': '산장/계곡 (자연 속 힐링)',
|
||||
'Private': '독채 (프라이빗 공간)',
|
||||
'Couple': '커플펜션 (로맨틱)',
|
||||
'Family': '가족펜션 (단체 숙박)',
|
||||
'Pet': '애견동반 (반려동물 환영)',
|
||||
'Glamping': '글램핑 (캠핑+럭셔리)',
|
||||
'Traditional': '한옥펜션 (전통미)'
|
||||
};
|
||||
|
||||
// 선택된 카테고리를 텍스트로 변환
|
||||
const pensionTypesText = info.pensionCategories && info.pensionCategories.length > 0
|
||||
? info.pensionCategories.map(cat => categoryMap[cat] || cat).join(', ')
|
||||
: '일반 펜션';
|
||||
|
||||
const prompt = `
|
||||
역할: 전문 ${targetLang} 카피라이터 및 작사가.
|
||||
클라이언트: ${info.name}
|
||||
컨텍스트: ${info.description}
|
||||
펜션 유형: ${pensionTypesText} - 이 특성을 마케팅 콘텐츠에 반영하세요.
|
||||
모드: ${info.audioMode} (Song=노래, Narration=내레이션)
|
||||
스타일: ${info.audioMode === 'Song' ? info.musicGenre : info.ttsConfig.tone}
|
||||
언어: **${targetLang}** 로 작성 필수.
|
||||
|
||||
과제 1: 임팩트 있는 **${targetLang}** 광고 헤드라인 4개를 작성하라.
|
||||
- **완벽한 ${targetLang} 사용**: 자연스럽고 세련된 현지 마케팅 표현 사용.
|
||||
- **펜션 유형 반영**: ${pensionTypesText}의 특징(프라이빗, 로맨틱, 자연, 럭셔리 등)을 강조하라.
|
||||
- **형식**: 짧고 강렬한 "빌보드" 스타일.
|
||||
- **줄바꿈**: 시각적 균형을 위해 문장의 중간에 적절한 줄바꿈(\n)을 반드시 넣어라.
|
||||
|
||||
과제 2: ${info.audioMode === 'Song' ? '노래 가사' : '내레이션 스크립트'} 작성.
|
||||
- 언어: **${targetLang}**.
|
||||
- **펜션 컨셉 활용**: ${pensionTypesText}의 매력(예: 풀빌라면 프라이빗한 휴식, 오션뷰면 파도소리와 일몰)을 자연스럽게 녹여내라.
|
||||
${info.audioMode === 'Song'
|
||||
? `- **필수 포맷**: 반드시 다음 헤더를 사용해야 함: "[Verse 1]", "[Chorus]", 등.
|
||||
${lyricStructureInstruction}
|
||||
- 내용: ${info.musicGenre} 장르에 맞는 감성적이고 스토리텔링이 있는 가사.
|
||||
`
|
||||
: `- 구조: 상업 광고용 30초 분량의 매력적인 내레이션 스크립트.
|
||||
- 톤앤매너: ${info.ttsConfig.tone}. 자연스러운 구어체 ${targetLang}.`}
|
||||
|
||||
출력 형식 (JSON):
|
||||
{
|
||||
"adCopy": ["헤드라인 1\n(줄바꿈포함)", "헤드라인 2\n(줄바꿈포함)", ...],
|
||||
"lyrics": "Verse/Chorus 헤더가 포함된 전체 가사 또는 스크립트 텍스트..."
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await ai.models.generateContent({
|
||||
model: 'gemini-2.0-flash',
|
||||
contents: {
|
||||
parts: [
|
||||
{ text: prompt },
|
||||
...imageParts
|
||||
]
|
||||
},
|
||||
config: {
|
||||
temperature: 0.7,
|
||||
responseMimeType: 'application/json',
|
||||
responseSchema: {
|
||||
type: Type.OBJECT,
|
||||
properties: {
|
||||
adCopy: {
|
||||
type: Type.ARRAY,
|
||||
items: { type: Type.STRING }
|
||||
},
|
||||
lyrics: { type: Type.STRING }
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (response.text) {
|
||||
try {
|
||||
return JSON.parse(response.text);
|
||||
} catch (e) {
|
||||
console.error("JSON 파싱 오류", response.text);
|
||||
throw new Error("창의적 콘텐츠 파싱에 실패했습니다.");
|
||||
}
|
||||
}
|
||||
throw new Error("텍스트 콘텐츠 생성 실패");
|
||||
};
|
||||
|
||||
/**
|
||||
* 서버 사이드에서 고급 음성 합성 (TTS) - Gemini 2.5 Flash TTS
|
||||
* 텍스트를 입력받아 자연스러운 AI 성우 목소리(Base64)를 생성합니다.
|
||||
*
|
||||
* @param {string} text - 음성으로 변환할 텍스트
|
||||
* @param {object} config - TTS 설정 (gender, age, tone)
|
||||
* @returns {Promise<string>} - Base64 인코딩된 오디오 데이터
|
||||
*/
|
||||
const generateAdvancedSpeech = async (
|
||||
text,
|
||||
config
|
||||
) => {
|
||||
if (!GEMINI_API_KEY) {
|
||||
throw new Error("Gemini API Key가 서버에 설정되지 않았습니다.");
|
||||
}
|
||||
const ai = new GoogleGenAI({ apiKey: GEMINI_API_KEY });
|
||||
const voiceName = getVoiceName(config);
|
||||
|
||||
const cleanText = text
|
||||
.replace(/\[.*?\]/g, '')
|
||||
.replace(/\(.*?\)/g, '')
|
||||
.replace(/<.*?>/g, '')
|
||||
.replace(/(Narrator|나레이터|성우|Speaker|Woman|Man).*?:/gi, '')
|
||||
.replace(/\*\*/g, '')
|
||||
.replace(/[•*-]/g, '')
|
||||
.replace(/\s{2,}/g, ' ')
|
||||
.trim();
|
||||
|
||||
// console.log(`음성 생성 중: 목소리=${voiceName}, 텍스트=${cleanText.substring(0, 50)}...`); // 디버그 로그 제거
|
||||
|
||||
const response = await ai.models.generateContent({
|
||||
model: "gemini-2.5-flash-preview-tts",
|
||||
contents: [{ parts: [{ text: cleanText }] }],
|
||||
config: {
|
||||
responseModalities: [Modality.AUDIO],
|
||||
speechConfig: {
|
||||
voiceConfig: {
|
||||
prebuiltVoiceConfig: { voiceName }
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const base64Audio = response.candidates?.[0]?.content?.parts?.[0]?.inlineData?.data;
|
||||
|
||||
if (!base64Audio) {
|
||||
throw new Error("Gemini TTS로부터 오디오 데이터를 받지 못했습니다.");
|
||||
}
|
||||
return base64Audio;
|
||||
};
|
||||
|
||||
/**
|
||||
* 서버 사이드에서 광고 포스터 생성 - Gemini 3 Pro Image
|
||||
* 업로드된 이미지들을 합성하고 브랜드 분위기에 맞는 고화질 포스터를 생성합니다.
|
||||
*
|
||||
* @param {object} info - 비즈니스 정보 객체 (BusinessInfo와 유사)
|
||||
* @param {Array<object>} info.images - Base64 인코딩된 이미지 데이터 배열 ({ mimeType, base64 })
|
||||
* @param {string} info.name - 브랜드 이름
|
||||
* @param {string} info.description - 브랜드 설명
|
||||
* @param {string} info.aspectRatio - 화면 비율
|
||||
* @param {boolean} info.useAiImages - AI 이미지 생성 허용 여부
|
||||
* @returns {Promise<{ base64: string; mimeType: string }>}
|
||||
*/
|
||||
const generateAdPoster = async (info) => {
|
||||
if (!GEMINI_API_KEY) {
|
||||
throw new Error("Gemini API Key가 서버에 설정되지 않았습니다.");
|
||||
}
|
||||
const ai = new GoogleGenAI({ apiKey: GEMINI_API_KEY });
|
||||
|
||||
const imageParts = info.images.map((imageData) => ({
|
||||
inlineData: { mimeType: imageData.mimeType, data: imageData.base64 }
|
||||
}));
|
||||
|
||||
const model = 'gemini-3-pro-image-preview';
|
||||
|
||||
let prompt = '';
|
||||
|
||||
if (imageParts.length > 0) {
|
||||
if (info.useAiImages) {
|
||||
prompt = `
|
||||
역할: 전문 아트 디렉터.
|
||||
과제: 브랜드 "${info.name}"를 위한 단 하나의, 조화롭고 수상 경력에 빛나는 광고 포스터를 제작하라.
|
||||
|
||||
지침:
|
||||
1. **시각적 합성(Composite Visuals)**: 제공된 여러 참조 이미지를 바탕으로 예술적으로 재창조하라. 필요하다면 요소를 추가하거나 조명을 개선하여 퀄리티를 높여라.
|
||||
2. 테마: ${info.description}.
|
||||
3. 스타일: 시네마틱 조명, 4k 해상도, 하이엔드 상업 사진.
|
||||
4. 종횡비: ${info.aspectRatio === '9:16' ? '9:16 세로 모드' : '16:9 가로 모드'}.
|
||||
`;
|
||||
} else {
|
||||
prompt = `
|
||||
역할: 사진 편집자.
|
||||
과제: 제공된 이미지들을 사용하여 하나의 깔끔한 홍보 이미지를 만들어라.
|
||||
|
||||
**매우 중요한 제약사항 (Strict Constraints)**:
|
||||
1. **새로운 사물 생성 금지**: 제공된 이미지에 없는 물체, 사람, 배경을 절대로 새로 그려넣지 마라.
|
||||
2. **원본 유지**: 제공된 이미지들의 톤과 느낌을 최대한 유지하며 자연스럽게 합성하라. (Digital Collage).
|
||||
3. **사실성**: 과도한 AI 효과나 비현실적인 변형을 피하라.
|
||||
4. 종횡비: ${info.aspectRatio === '9:16' ? '9:16 세로 모드' : '16:9 가로 모드'}.
|
||||
`;
|
||||
}
|
||||
} else {
|
||||
if (!info.useAiImages) {
|
||||
throw new Error("이미지가 없고 AI 이미지 생성 옵션도 꺼져 있어 포스터를 만들 수 없습니다. 사진을 업로드하거나 옵션을 켜주세요.");
|
||||
}
|
||||
|
||||
prompt = `
|
||||
역할: 세계적인 상업 사진작가 및 아트 디렉터.
|
||||
과제: 브랜드 "${info.name}"를 홍보하기 위한 최고급 상업 광고 사진을 생성하라.
|
||||
|
||||
브랜드 설명: "${info.description}"
|
||||
|
||||
지침:
|
||||
1. **이미지 생성**: 위 브랜드 설명에 완벽하게 부합하는, 디테일이 살아있는 고해상도 사진을 창조하라. 실제 매장이나 제품을 촬영한 것 같은 사실감을 주어라.
|
||||
2. 스타일:
|
||||
- 조명: 드라마틱하고 따뜻한 시네마틱 조명.
|
||||
- 퀄리티: 8k UHD, 초고화질, 잡지 커버 수준의 디테일.
|
||||
- 분위기: 고객이 방문하고 싶게 만드는 매력적이고 환영하는 분위기.
|
||||
3. 구도: ${info.aspectRatio === '9:16' ? '9:16 세로 비율 (Vertical/Portrait) 필수. 스마트폰 전체 화면용. 가로 사진을 90도 회전시키지 마라.' : '16:9 와이드 비율 (Horizontal). 중앙이나 한쪽에 텍스트를 배치할 수 있는 여백을 고려한 구도.'}
|
||||
4. 금지: 흐릿하거나 왜곡된 이미지, 부자연스러운 텍스트 생성 금지.
|
||||
|
||||
이 이미지는 뮤직 비디오의 메인 배경으로 사용될 것이다.
|
||||
`;
|
||||
}
|
||||
|
||||
const response = await ai.models.generateContent({
|
||||
model,
|
||||
contents: {
|
||||
parts: [
|
||||
{ text: prompt },
|
||||
...imageParts
|
||||
]
|
||||
},
|
||||
});
|
||||
|
||||
for (const part of response.candidates?.[0]?.content?.parts || []) {
|
||||
if (part.inlineData) {
|
||||
return { base64: part.inlineData.data, mimeType: part.inlineData.mimeType || 'image/png' };
|
||||
}
|
||||
}
|
||||
throw new Error("광고 포스터 이미지 생성에 실패했습니다.");
|
||||
};
|
||||
|
||||
/**
|
||||
* 서버 사이드에서 다수의 비즈니스 관련 이미지 생성 (갤러리/슬라이드쇼용)
|
||||
* @param {object} info - 비즈니스 정보 객체
|
||||
* @param {number} count - 생성할 이미지 개수
|
||||
* @returns {Promise<string[]>} - Base64 Data URL 배열
|
||||
*/
|
||||
const generateImageGallery = async (info, count) => {
|
||||
if (!GEMINI_API_KEY) {
|
||||
throw new Error("Gemini API Key가 서버에 설정되지 않았습니다.");
|
||||
}
|
||||
const ai = new GoogleGenAI({ apiKey: GEMINI_API_KEY });
|
||||
const model = 'gemini-3-pro-image-preview';
|
||||
|
||||
const perspectives = [
|
||||
"Wide angle shot of the interior, welcoming atmosphere, cinematic lighting",
|
||||
"Close-up detail shot of the main product or service, high resolution, macro photography",
|
||||
"Exterior view of the storefront or location, inviting and stylish",
|
||||
"Candid shot of happy customers enjoying the service or atmosphere (soft focus background)",
|
||||
"Artistic composition of the brand elements or menu items, magazine style"
|
||||
];
|
||||
|
||||
const tasks = Array.from({ length: count }).map(async (_, i) => {
|
||||
const perspective = perspectives[i % perspectives.length];
|
||||
const prompt = `
|
||||
Role: Professional Photographer.
|
||||
Subject: ${info.name} - ${info.description}
|
||||
Shot Type: ${perspective}
|
||||
Style: 4k, Photorealistic, Commercial Advertisement Standard, ${info.textEffect} vibe.
|
||||
Aspect Ratio: 16:9.
|
||||
`;
|
||||
|
||||
try {
|
||||
const response = await ai.models.generateContent({
|
||||
model,
|
||||
contents: { parts: [{ text: prompt }] },
|
||||
});
|
||||
|
||||
const part = response.candidates?.[0]?.content?.parts?.[0];
|
||||
if (part && part.inlineData) {
|
||||
return `data:${part.inlineData.mimeType};base64,${part.inlineData.data}`;
|
||||
}
|
||||
return null;
|
||||
} catch (e) {
|
||||
console.error(`Image generation failed for index ${i}`, e);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
const results = await Promise.all(tasks);
|
||||
return results.filter((img) => img !== null);
|
||||
};
|
||||
|
||||
/**
|
||||
* 서버 사이드에서 비디오 배경 생성 - Veo (Video Generation Model)
|
||||
* 생성된 포스터 이미지를 기반으로 움직이는 시네마틱 배경 영상을 만듭니다.
|
||||
*
|
||||
* @param {string} posterBase64 - Base64 인코딩된 포스터 이미지 데이터
|
||||
* @param {string} posterMimeType - 포스터 이미지 MIME 타입
|
||||
* @param {string} aspectRatio - 비디오 화면 비율
|
||||
* @returns {Promise<string>} - 생성된 비디오의 원격 URL
|
||||
*/
|
||||
const generateVideoBackground = async (
|
||||
posterBase64,
|
||||
posterMimeType,
|
||||
aspectRatio = '16:9'
|
||||
) => {
|
||||
if (!GEMINI_API_KEY) {
|
||||
throw new Error("Gemini API Key가 서버에 설정되지 않았습니다.");
|
||||
}
|
||||
const ai = new GoogleGenAI({ apiKey: GEMINI_API_KEY });
|
||||
|
||||
let operation = await ai.models.generateVideos({
|
||||
model: 'veo-3.1-fast-generate-preview',
|
||||
prompt: '시네마틱한 움직임, 상업 광고 영상미, 4k, 느리고 부드러운 움직임, 감성적, 추상적이고 미니멀한 모션 그래픽 스타일',
|
||||
image: {
|
||||
imageBytes: posterBase64,
|
||||
mimeType: posterMimeType,
|
||||
},
|
||||
config: {
|
||||
numberOfVideos: 1,
|
||||
resolution: '720p',
|
||||
aspectRatio: aspectRatio
|
||||
}
|
||||
});
|
||||
|
||||
while (!operation.done) {
|
||||
await new Promise(resolve => setTimeout(resolve, 5000));
|
||||
operation = await ai.operations.getVideosOperation({ operation: operation });
|
||||
}
|
||||
|
||||
if (operation.error) {
|
||||
console.error("Veo 생성 오류:", operation.error);
|
||||
throw new Error(`비디오 생성 실패: ${operation.error.message || "알 수 없는 오류"}`);
|
||||
}
|
||||
|
||||
let downloadLink = operation.response?.generatedVideos?.[0]?.video?.uri;
|
||||
if (!downloadLink) {
|
||||
const anyOp = operation;
|
||||
downloadLink = anyOp.result?.generatedVideos?.[0]?.video?.uri;
|
||||
}
|
||||
|
||||
if (!downloadLink) {
|
||||
console.error("작업 내 다운로드 링크 누락. 응답 덤프:", JSON.stringify(operation, null, 2));
|
||||
throw new Error("비디오 생성이 완료되었으나 URI가 반환되지 않았습니다. 안전 필터에 의해 콘텐츠가 차단되었을 수 있습니다. 다른 이미지나 설명으로 시도해보세요.");
|
||||
}
|
||||
|
||||
// API 키를 직접 노출하지 않으므로, downloadLink만 반환
|
||||
return downloadLink;
|
||||
};
|
||||
|
||||
/**
|
||||
* 서버 사이드에서 AI 이미지 검수 (Gemini Vision)
|
||||
* 업로드되거나 크롤링된 이미지 중 마케팅에 적합한 사진만 선별합니다.
|
||||
*
|
||||
* @param {Array<object>} imagesData - Base64 인코딩된 이미지 데이터 배열 ({ mimeType, base64 })
|
||||
* @returns {Promise<Array<object>>} - 선별된 Base64 이미지 데이터 배열
|
||||
*/
|
||||
const filterBestImages = async (imagesData) => {
|
||||
if (!GEMINI_API_KEY) {
|
||||
throw new Error("Gemini API Key가 서버에 설정되지 않았습니다.");
|
||||
}
|
||||
const ai = new GoogleGenAI({ apiKey: GEMINI_API_KEY });
|
||||
|
||||
if (imagesData.length === 0) {
|
||||
// console.warn("검수할 유효한 이미지(Base64)가 없습니다."); // 디버그 로그 제거
|
||||
return [];
|
||||
}
|
||||
|
||||
// console.log(`AI 이미지 검수 시작: 총 ${imagesData.length}장 분석 중...`); // 디버그 로그 제거
|
||||
|
||||
const imageParts = imagesData.map((imageData) => ({
|
||||
inlineData: { mimeType: imageData.mimeType, data: imageData.base64 }
|
||||
}));
|
||||
|
||||
const prompt = `
|
||||
역할: 엄격한 상업 사진 편집장.
|
||||
작업: 다음 이미지들을 분석하여 "마케팅 비디오"에 사용할 수 있는 **최고의 사진**만 골라내라.
|
||||
|
||||
**엄격한 제외 기준 (무조건 탈락)**:
|
||||
1. **사람 얼굴**: 정면이든 측면이든 식별 가능한 사람 얼굴이 포함된 경우 (초상권 보호).
|
||||
2. **지저분함**: 먹다 남은 음식, 빈 그릇, 쓰레기, 지저분한 테이블.
|
||||
3. **무의미한 문서**: 영수증, 택배 송장, 흐릿한 A4 용지 문서. (단, **메뉴판은 허용**).
|
||||
4. **저품질**: 심하게 흔들림, 너무 어두움, 해상도 낮음.
|
||||
|
||||
**선정 기준 (우선 순위)**:
|
||||
1. 맛있어 보이는 음식 클로즈업.
|
||||
2. 분위기 있는 매장 인테리어 또는 익스테리어.
|
||||
3. **정보가 담긴 메뉴판**: 고객에게 메뉴와 가격을 알려주는 깔끔한 메뉴판 사진은 **반드시 포함**하라.
|
||||
4. 구도가 잡힌 감성적인 사진.
|
||||
|
||||
출력 형식:
|
||||
오직 선정된 이미지의 **인덱스 번호(0부터 시작)**만 포함된 JSON 배열.
|
||||
예시: [0, 2, 5]
|
||||
(만약 모든 사진이 부적합하다면 빈 배열 [] 반환)
|
||||
`;
|
||||
|
||||
try {
|
||||
const response = await ai.models.generateContent({
|
||||
model: 'gemini-2.5-flash',
|
||||
contents: {
|
||||
parts: [
|
||||
{ text: prompt },
|
||||
...imageParts
|
||||
]
|
||||
},
|
||||
config: {
|
||||
responseMimeType: 'application/json',
|
||||
temperature: 0.1
|
||||
}
|
||||
});
|
||||
|
||||
if (response.text) {
|
||||
const indices = JSON.parse(response.text);
|
||||
// console.log(`AI 검수 결과: ${indices.length}장 선정됨 (인덱스: ${indices.join(', ')})`); // 디버그 로그 제거
|
||||
|
||||
return indices
|
||||
.filter(i => i >= 0 && i < imagesData.length)
|
||||
.map(i => imagesData[i]);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("AI 이미지 검수 실패:", e);
|
||||
return imagesData; // 실패 시 안전하게 모든 이미지 반환
|
||||
}
|
||||
|
||||
return imagesData;
|
||||
};
|
||||
|
||||
/**
|
||||
* 서버 사이드에서 리뷰 기반 마케팅 설명 생성
|
||||
* @param {string} name - 업체명
|
||||
* @param {string} rawDescription - 기본 설명
|
||||
* @param {string[]} reviews - 고객 리뷰 배열
|
||||
* @param {number} rating - 평균 별점
|
||||
* @returns {Promise<string>} - 생성된 설명
|
||||
*/
|
||||
const enrichDescriptionWithReviews = async (
|
||||
name,
|
||||
rawDescription,
|
||||
reviews,
|
||||
rating
|
||||
) => {
|
||||
if (!GEMINI_API_KEY) {
|
||||
throw new Error("Gemini API Key가 서버에 설정되지 않았습니다.");
|
||||
}
|
||||
const ai = new GoogleGenAI({ apiKey: GEMINI_API_KEY });
|
||||
|
||||
const prompt = `
|
||||
역할: 전문 마케팅 카피라이터.
|
||||
업체명: ${name}
|
||||
기본 정보: ${rawDescription}
|
||||
평균 별점: ${rating}점
|
||||
실제 고객 리뷰 요약:
|
||||
${reviews.map(r => `- ${r}`).join('\n')}
|
||||
|
||||
지침:
|
||||
위 정보를 바탕으로 뮤직 비디오 제작을 위한 **매력적이고 풍부한 업체 설명(Description)**을 한 단락으로 작성하라.
|
||||
|
||||
요구사항:
|
||||
1. 실제 고객의 목소리(리뷰)를 자연스럽게 녹여내라.
|
||||
2. 별점이 높다면(4.5 이상) 이를 강조하라.
|
||||
3. 분위기, 맛, 서비스의 특징을 감성적으로 묘사하라.
|
||||
4. 길이는 3~4문장 정도로 요약하라.
|
||||
5. 한국어로 작성하라.
|
||||
`;
|
||||
|
||||
const response = await ai.models.generateContent({
|
||||
model: 'gemini-2.5-flash',
|
||||
contents: [{ parts: [{ text: prompt }] }]
|
||||
});
|
||||
|
||||
return response.text?.trim() || rawDescription;
|
||||
};
|
||||
|
||||
/**
|
||||
* 서버 사이드에서 이미지에서 텍스트 스타일(CSS) 추출 - Gemini 1.5 Flash
|
||||
* @param {object} imageFile - Base64 인코딩된 이미지 데이터 ({ mimeType, base64 })
|
||||
* @returns {Promise<string>} - 생성된 CSS 코드
|
||||
*/
|
||||
const extractTextEffectFromImage = async (
|
||||
imageFile
|
||||
) => {
|
||||
if (!GEMINI_API_KEY) {
|
||||
throw new Error("Gemini API Key가 서버에 설정되지 않았습니다.");
|
||||
}
|
||||
const ai = new GoogleGenAI({ apiKey: GEMINI_API_KEY });
|
||||
|
||||
const imageBase64 = imageFile.base64;
|
||||
const mimeType = imageFile.mimeType;
|
||||
|
||||
const prompt = `
|
||||
역할: 전문 프론트엔드 개발자 및 UI 디자이너.
|
||||
작업: 제공된 이미지에 있는 **메인 텍스트의 스타일**을 분석하여 똑같이 재현할 수 있는 **CSS 코드**를 작성하라.
|
||||
|
||||
분석 항목:
|
||||
1. **색상 (Color)**: 텍스트 색상 및 그라디언트.
|
||||
2. **폰트 (Font)**: 폰트 두께(weight), 스타일(italic 등), 자간(letter-spacing). (폰트 패밀리는 일반적인 sans-serif나 serif 사용)
|
||||
3. **효과 (Effects)**:
|
||||
- text-shadow (네온, 그림자, 외곽선 등)
|
||||
- background (배경색, 반투명 등)
|
||||
- transform (기울임, 회전 등)
|
||||
4. **애니메이션 (Animation)**: 이미지의 분위기에 어울리는 적절한 @keyframes 애니메이션을 하나 추가하라. (예: 부드러운 등장, 반짝임, 흔들림 등)
|
||||
|
||||
출력 형식:
|
||||
- 오직 **CSS 코드만** 출력하라. 설명이나 마크다운 코드블록은 제외하라.
|
||||
- 클래스 이름은 반드시 **.custom-effect** 로 정의하라.
|
||||
- 애니메이션이 있다면 @keyframes도 함께 포함하라.
|
||||
`;
|
||||
|
||||
const response = await ai.models.generateContent({
|
||||
model: 'gemini-2.5-flash',
|
||||
contents: {
|
||||
parts: [
|
||||
{ text: prompt },
|
||||
{ inlineData: { mimeType: mimeType, data: imageBase64 } }
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
let css = response.text || '';
|
||||
css = css.replace(/```css/g, '').replace(/```/g, '').trim();
|
||||
|
||||
return css;
|
||||
};
|
||||
|
||||
/**
|
||||
* YouTube SEO 최적화 메타데이터 생성 (다국어 지원)
|
||||
* @param {object} params - 비즈니스 정보
|
||||
* @param {string} params.businessName - 펜션 이름 (한국어)
|
||||
* @param {string} params.businessNameEn - 펜션 이름 (영어)
|
||||
* @param {string} params.description - 비즈니스 설명
|
||||
* @param {Array<string>} params.categories - 펜션 카테고리
|
||||
* @param {string} params.address - 주소
|
||||
* @param {string} params.region - 지역명
|
||||
* @param {string} params.targetAudience - 타깃 고객
|
||||
* @param {Array<string>} params.mainStrengths - 주요 장점
|
||||
* @param {Array<string>} params.nearbyAttractions - 인근 관광지
|
||||
* @param {string} params.bookingUrl - 예약 링크
|
||||
* @param {number} params.videoDuration - 영상 길이 (초)
|
||||
* @param {string} params.seasonTheme - 계절/테마
|
||||
* @param {string} params.priceRange - 가격대 설명
|
||||
* @param {string} params.language - 추가 언어 코드 (KO는 기본)
|
||||
* @returns {Promise<object>} - 다국어 SEO 메타데이터
|
||||
*/
|
||||
const generateYouTubeSEO = async (params) => {
|
||||
if (!GEMINI_API_KEY) {
|
||||
throw new Error("Gemini API Key가 서버에 설정되지 않았습니다.");
|
||||
}
|
||||
const ai = new GoogleGenAI({ apiKey: GEMINI_API_KEY });
|
||||
|
||||
const langMap = {
|
||||
'KO': { name: '한국어', code: 'ko' },
|
||||
'EN': { name: 'English', code: 'en' },
|
||||
'JA': { name: '日本語', code: 'ja' },
|
||||
'ZH': { name: '中文', code: 'zh' },
|
||||
'TH': { name: 'ไทย', code: 'th' },
|
||||
'VI': { name: 'Tiếng Việt', code: 'vi' }
|
||||
};
|
||||
|
||||
const categoryMap = {
|
||||
'PoolVilla': { ko: '풀빌라', en: 'Pool Villa' },
|
||||
'OceanView': { ko: '오션뷰', en: 'Ocean View' },
|
||||
'Mountain': { ko: '산장/계곡', en: 'Mountain Retreat' },
|
||||
'Private': { ko: '독채펜션', en: 'Private Pension' },
|
||||
'Couple': { ko: '커플펜션', en: 'Couple Pension' },
|
||||
'Family': { ko: '가족펜션', en: 'Family Pension' },
|
||||
'Pet': { ko: '애견동반', en: 'Pet-Friendly' },
|
||||
'Glamping': { ko: '글램핑', en: 'Glamping' },
|
||||
'Traditional': { ko: '한옥펜션', en: 'Traditional Hanok' }
|
||||
};
|
||||
|
||||
const categoryTagsKo = params.categories?.map(cat => categoryMap[cat]?.ko || cat) || [];
|
||||
const categoryTagsEn = params.categories?.map(cat => categoryMap[cat]?.en || cat) || [];
|
||||
const pensionType = categoryTagsKo[0] || '펜션';
|
||||
const pensionTypeEn = categoryTagsEn[0] || 'Pension';
|
||||
|
||||
// 지역 정보 추출
|
||||
const regionKo = params.region || params.address?.split(' ')[0] || '';
|
||||
const regionEn = params.regionEn || regionKo;
|
||||
|
||||
// 영상 길이 (분)
|
||||
const videoDurationMin = Math.ceil((params.videoDuration || 60) / 60);
|
||||
|
||||
// 추가 언어 설정
|
||||
const additionalLang = params.language && params.language !== 'KO' ? langMap[params.language] : null;
|
||||
|
||||
const prompt = `
|
||||
너는 유튜브 여행/숙소 채널의 SEO 전문가이자 카피라이터다.
|
||||
나는 "펜션 전문 웹사이트"를 운영하고 있고, 아래 입력 정보를 기반으로
|
||||
특정 펜션을 소개하는 유튜브 영상을 올리려고 한다.
|
||||
|
||||
목표:
|
||||
1) 한국어 시청자에게는 예약 전 정보를 자세하고 감성적으로 전달
|
||||
2) ${additionalLang ? `${additionalLang.name} 시청자(외국인 여행객)에게는 핵심 정보와 위치/장점을 명확하게 안내` : '검색 최적화'}
|
||||
3) YouTube 검색, 연관 동영상, Google 검색, AI 검색(LLM)까지 고려한 SEO 최적화
|
||||
|
||||
[입력 정보]
|
||||
- 펜션 이름: ${params.businessName} / 영어 이름: ${params.businessNameEn || params.businessName}
|
||||
- 지역/도시: ${regionKo} (영어 표기: ${regionEn})
|
||||
- 펜션 타입: ${pensionType}
|
||||
- 주요 타깃 고객: ${params.targetAudience || '커플, 가족'}
|
||||
- 핵심 장점: ${params.mainStrengths?.join(', ') || categoryTagsKo.join(', ')}
|
||||
- 인근 관광지: ${params.nearbyAttractions?.join(', ') || ''}
|
||||
- 예약 링크(URL): ${params.bookingUrl || ''}
|
||||
- 공식 웹사이트/브랜드: CastAD
|
||||
- 영상 길이: ${videoDurationMin}분
|
||||
- 계절/테마: ${params.seasonTheme || '사계절'}
|
||||
- 가격대: ${params.priceRange || '문의'}
|
||||
- 설명: ${params.description || ''}
|
||||
|
||||
[출력 형식 - JSON만 출력]
|
||||
|
||||
{
|
||||
"snippet": {
|
||||
"title_ko": "70자 이내, 지역 + 펜션타입 + 강점1~2개 포함. 예: '${regionKo} ${pensionType} | 전 객실 개별바비큐 & 야외수영장'",
|
||||
"title_${additionalLang?.code || 'en'}": "70자 이내 ${additionalLang?.name || 'English'} 제목",
|
||||
"description_ko": "유튜브 본문 전체 (500~1500자, 아래 구조 포함):\\n\\n[펜션 한 줄 요약]\\n[위치 & 교통]\\n[객실 & 인원 안내]\\n[편의시설 상세]\\n[인근 관광지 추천 코스]\\n[이용 팁 & 주의사항]\\n[예약/문의 안내 + 예약링크]\\n\\n자연스러운 여행 블로그 글처럼 작성",
|
||||
"description_${additionalLang?.code || 'en'}": "${additionalLang?.name || 'English'} 설명 (300~800자, 핵심 정보 위주, 한국 지명은 영어 표기 + 한글 병기)",
|
||||
"tags_ko": ["한국어 태그 15~25개, 지역/펜션타입/타깃고객/계절/관광지 키워드 포함, 롱테일 키워드도 포함"],
|
||||
"tags_${additionalLang?.code || 'en'}": ["${additionalLang?.name || 'English'} 태그 15~25개"],
|
||||
"hashtags_ko": ["#형식의 해시태그 10~15개"],
|
||||
"categoryId": "19"
|
||||
},
|
||||
"chapters": [
|
||||
{"time": "00:00", "title_ko": "인트로 & 뷰 소개", "title_${additionalLang?.code || 'en'}": "Intro & View"},
|
||||
{"time": "00:30", "title_ko": "외관 & 공용시설", "title_${additionalLang?.code || 'en'}": "Exterior & Facilities"},
|
||||
{"time": "01:30", "title_ko": "객실 내부 투어", "title_${additionalLang?.code || 'en'}": "Room Tour"},
|
||||
{"time": "03:00", "title_ko": "바비큐/수영장/스파", "title_${additionalLang?.code || 'en'}": "BBQ / Pool / Spa"},
|
||||
{"time": "04:30", "title_ko": "주변 관광지 & 추천 코스", "title_${additionalLang?.code || 'en'}": "Nearby Attractions"},
|
||||
{"time": "05:30", "title_ko": "예약 안내 & 팁", "title_${additionalLang?.code || 'en'}": "Booking Tips"}
|
||||
],
|
||||
"thumbnail_text": {
|
||||
"short_ko": "${regionKo} ${pensionType}",
|
||||
"short_${additionalLang?.code || 'en'}": "${regionEn} ${pensionTypeEn}",
|
||||
"sub_ko": "핵심 강점 2개 요약",
|
||||
"sub_${additionalLang?.code || 'en'}": "Key features summary"
|
||||
},
|
||||
"pinned_comment_ko": "고정 댓글용 한국어 멘트 (예약 링크, 문의 안내, 타임스탬프 요약 포함)",
|
||||
"pinned_comment_${additionalLang?.code || 'en'}": "${additionalLang?.name || 'English'} pinned comment for foreign viewers"
|
||||
}
|
||||
|
||||
[작성 규칙]
|
||||
1) title_ko: 지역 + 펜션타입 + 강점1~2개 포함
|
||||
2) description_ko: 첫 2~3줄에 핵심 키워드와 강력한 후킹 문장, 구조화된 섹션
|
||||
3) description_${additionalLang?.code || 'en'}: 외국인 기준으로 위치/교통/시설 명확히
|
||||
4) tags: 지역, 펜션타입, 타깃고객, 계절/테마, 주변관광지 키워드 모두 커버
|
||||
5) chapters: 영상 길이(${videoDurationMin}분)에 맞는 타임스탬프
|
||||
6) 톤: 과한 광고 피하고, 실제 방문 후기처럼 신뢰감 있게
|
||||
|
||||
예약 링크가 있으면 description에 반드시 포함: ${params.bookingUrl || '없음'}
|
||||
`;
|
||||
|
||||
try {
|
||||
const response = await ai.models.generateContent({
|
||||
model: 'gemini-2.0-flash',
|
||||
contents: { parts: [{ text: prompt }] }
|
||||
});
|
||||
|
||||
let result = response.text || '';
|
||||
result = result.replace(/```json/g, '').replace(/```/g, '').trim();
|
||||
|
||||
const seoData = JSON.parse(result);
|
||||
|
||||
// 태그 검증 (YouTube 제한: 500자)
|
||||
['tags_ko', 'tags_en', 'tags_ja', 'tags_zh', 'tags_th', 'tags_vi'].forEach(tagKey => {
|
||||
if (seoData.snippet?.[tagKey]) {
|
||||
let totalTagLength = seoData.snippet[tagKey].join(',').length;
|
||||
while (totalTagLength > 500 && seoData.snippet[tagKey].length > 5) {
|
||||
seoData.snippet[tagKey].pop();
|
||||
totalTagLength = seoData.snippet[tagKey].join(',').length;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 제목 길이 검증 (100자)
|
||||
Object.keys(seoData.snippet || {}).forEach(key => {
|
||||
if (key.startsWith('title_') && seoData.snippet[key]?.length > 100) {
|
||||
seoData.snippet[key] = seoData.snippet[key].substring(0, 97) + '...';
|
||||
}
|
||||
});
|
||||
|
||||
// 설명 길이 검증 (5000자)
|
||||
Object.keys(seoData.snippet || {}).forEach(key => {
|
||||
if (key.startsWith('description_') && seoData.snippet[key]?.length > 5000) {
|
||||
seoData.snippet[key] = seoData.snippet[key].substring(0, 4997) + '...';
|
||||
}
|
||||
});
|
||||
|
||||
// 메타 정보 추가
|
||||
seoData.meta = {
|
||||
businessName: params.businessName,
|
||||
businessNameEn: params.businessNameEn || params.businessName,
|
||||
region: regionKo,
|
||||
regionEn: regionEn,
|
||||
pensionType: pensionType,
|
||||
pensionTypeEn: pensionTypeEn,
|
||||
bookingUrl: params.bookingUrl || '',
|
||||
videoDuration: params.videoDuration,
|
||||
language: params.language || 'KO',
|
||||
additionalLanguage: additionalLang?.code || 'en'
|
||||
};
|
||||
|
||||
console.log(`[YouTube SEO] ${params.businessName}: 다국어 메타데이터 생성 완료`);
|
||||
return seoData;
|
||||
|
||||
} catch (error) {
|
||||
console.error('[YouTube SEO] 생성 오류:', error.message);
|
||||
// 폴백: 기본 메타데이터 반환
|
||||
return {
|
||||
snippet: {
|
||||
title_ko: `${regionKo} ${pensionType} | ${params.businessName}`,
|
||||
title_en: `${regionEn} ${pensionTypeEn} | ${params.businessNameEn || params.businessName}`,
|
||||
description_ko: `${params.businessName}\n\n${params.description}\n\n📍 위치: ${params.address || regionKo}\n🔗 예약: ${params.bookingUrl || '문의'}\n\n#펜션 #숙소 #여행 #휴가 #${regionKo}`,
|
||||
description_en: `${params.businessNameEn || params.businessName}\n\n📍 Location: ${params.address || regionEn}\n🔗 Booking: ${params.bookingUrl || 'Contact us'}\n\n#pension #accommodation #travel #korea`,
|
||||
tags_ko: [params.businessName, pensionType, regionKo, '펜션', '숙소', '여행', '휴가', ...categoryTagsKo],
|
||||
tags_en: [params.businessNameEn || params.businessName, pensionTypeEn, regionEn, 'pension', 'korea travel', ...categoryTagsEn],
|
||||
hashtags_ko: [`#${params.businessName}`, `#${regionKo}펜션`, `#${pensionType}`, '#펜션추천', '#국내여행'],
|
||||
categoryId: '19'
|
||||
},
|
||||
chapters: [
|
||||
{ time: '0:00', title_ko: '인트로', title_en: 'Intro' },
|
||||
{ time: '0:15', title_ko: '시설 소개', title_en: 'Facilities' },
|
||||
{ time: '0:45', title_ko: '마무리', title_en: 'Outro' }
|
||||
],
|
||||
thumbnail_text: {
|
||||
short_ko: `${regionKo} ${pensionType}`,
|
||||
short_en: `${regionEn} ${pensionTypeEn}`,
|
||||
sub_ko: params.mainStrengths?.[0] || '프라이빗 힐링',
|
||||
sub_en: 'Private Retreat'
|
||||
},
|
||||
pinned_comment_ko: `📍 ${params.businessName} 예약 안내\n🔗 ${params.bookingUrl || '문의하기'}\n\n영상이 도움이 되셨다면 구독과 좋아요 부탁드려요! 🙏`,
|
||||
pinned_comment_en: `📍 ${params.businessNameEn || params.businessName} Booking\n🔗 ${params.bookingUrl || 'Contact us'}\n\nIf you found this helpful, please subscribe! 🙏`,
|
||||
meta: {
|
||||
businessName: params.businessName,
|
||||
businessNameEn: params.businessNameEn || params.businessName,
|
||||
region: regionKo,
|
||||
regionEn: regionEn,
|
||||
bookingUrl: params.bookingUrl || '',
|
||||
language: params.language || 'KO'
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
generateCreativeContent,
|
||||
generateAdvancedSpeech,
|
||||
generateAdPoster,
|
||||
generateImageGallery,
|
||||
filterBestImages,
|
||||
enrichDescriptionWithReviews,
|
||||
extractTextEffectFromImage,
|
||||
generateVideoBackground,
|
||||
generateYouTubeSEO,
|
||||
};
|
||||
+5022
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,243 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
암호화 서비스
|
||||
|
||||
Fernet 대칭 암호화를 사용하여 Instagram 비밀번호와 세션 데이터를
|
||||
안전하게 암호화/복호화합니다.
|
||||
|
||||
Fernet 특징:
|
||||
- AES-128-CBC 암호화
|
||||
- HMAC-SHA256 무결성 검증
|
||||
- 타임스탬프 포함 (TTL 검증 가능)
|
||||
- URL-safe base64 인코딩
|
||||
|
||||
사용 예시:
|
||||
encryptor = EncryptionService()
|
||||
encrypted = encryptor.encrypt("비밀번호")
|
||||
decrypted = encryptor.decrypt(encrypted)
|
||||
"""
|
||||
|
||||
import os
|
||||
import json
|
||||
import base64
|
||||
import logging
|
||||
from typing import Optional, Any, Dict
|
||||
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class EncryptionService:
|
||||
"""
|
||||
Fernet 기반 암호화/복호화 서비스
|
||||
|
||||
비밀번호, 세션 데이터 등 민감한 정보를 안전하게 저장하기 위한
|
||||
암호화 기능을 제공합니다.
|
||||
|
||||
Attributes:
|
||||
_cipher: Fernet 암호화 인스턴스
|
||||
_key: 암호화 키 (bytes)
|
||||
|
||||
Example:
|
||||
>>> service = EncryptionService()
|
||||
>>> encrypted = service.encrypt("my_password")
|
||||
>>> decrypted = service.decrypt(encrypted)
|
||||
>>> print(decrypted) # "my_password"
|
||||
"""
|
||||
|
||||
def __init__(self, key: Optional[str] = None):
|
||||
"""
|
||||
암호화 서비스 초기화
|
||||
|
||||
Args:
|
||||
key: Base64 인코딩된 Fernet 키 (32바이트)
|
||||
None이면 새 키 생성
|
||||
|
||||
Raises:
|
||||
ValueError: 유효하지 않은 키 형식
|
||||
"""
|
||||
if key:
|
||||
try:
|
||||
# Base64 문자열을 바이트로 디코딩
|
||||
self._key = key.encode() if isinstance(key, str) else key
|
||||
self._cipher = Fernet(self._key)
|
||||
logger.info("암호화 서비스 초기화 완료 (기존 키 사용)")
|
||||
except Exception as e:
|
||||
raise ValueError(f"유효하지 않은 암호화 키입니다: {e}")
|
||||
else:
|
||||
# 새 키 생성
|
||||
self._key = Fernet.generate_key()
|
||||
self._cipher = Fernet(self._key)
|
||||
logger.warning("새 암호화 키가 생성되었습니다. 환경변수에 저장하세요!")
|
||||
|
||||
def get_key_string(self) -> str:
|
||||
"""
|
||||
암호화 키를 문자열로 반환
|
||||
|
||||
환경변수에 저장할 수 있는 형태로 키를 반환합니다.
|
||||
|
||||
Returns:
|
||||
Base64 인코딩된 키 문자열
|
||||
"""
|
||||
return self._key.decode() if isinstance(self._key, bytes) else self._key
|
||||
|
||||
def encrypt(self, data: str) -> str:
|
||||
"""
|
||||
문자열 데이터 암호화
|
||||
|
||||
Args:
|
||||
data: 암호화할 평문 문자열
|
||||
|
||||
Returns:
|
||||
Base64 인코딩된 암호문
|
||||
|
||||
Raises:
|
||||
ValueError: 빈 데이터
|
||||
"""
|
||||
if not data:
|
||||
raise ValueError("암호화할 데이터가 없습니다")
|
||||
|
||||
try:
|
||||
# 문자열을 UTF-8 바이트로 변환 후 암호화
|
||||
encrypted_bytes = self._cipher.encrypt(data.encode('utf-8'))
|
||||
# Base64 문자열로 반환
|
||||
return encrypted_bytes.decode('utf-8')
|
||||
except Exception as e:
|
||||
logger.error(f"암호화 실패: {e}")
|
||||
raise
|
||||
|
||||
def decrypt(self, encrypted_data: str) -> str:
|
||||
"""
|
||||
암호화된 데이터 복호화
|
||||
|
||||
Args:
|
||||
encrypted_data: Base64 인코딩된 암호문
|
||||
|
||||
Returns:
|
||||
복호화된 평문 문자열
|
||||
|
||||
Raises:
|
||||
ValueError: 빈 데이터 또는 유효하지 않은 암호문
|
||||
InvalidToken: 잘못된 토큰 또는 키 불일치
|
||||
"""
|
||||
if not encrypted_data:
|
||||
raise ValueError("복호화할 데이터가 없습니다")
|
||||
|
||||
try:
|
||||
# Base64 문자열을 바이트로 변환 후 복호화
|
||||
encrypted_bytes = encrypted_data.encode('utf-8')
|
||||
decrypted_bytes = self._cipher.decrypt(encrypted_bytes)
|
||||
return decrypted_bytes.decode('utf-8')
|
||||
except InvalidToken:
|
||||
logger.error("복호화 실패: 유효하지 않은 토큰 또는 키 불일치")
|
||||
raise ValueError("암호화 키가 올바르지 않거나 데이터가 손상되었습니다")
|
||||
except Exception as e:
|
||||
logger.error(f"복호화 실패: {e}")
|
||||
raise
|
||||
|
||||
def encrypt_json(self, data: Dict[str, Any]) -> str:
|
||||
"""
|
||||
JSON 객체 암호화
|
||||
|
||||
딕셔너리를 JSON 문자열로 변환 후 암호화합니다.
|
||||
세션 데이터 저장에 유용합니다.
|
||||
|
||||
Args:
|
||||
data: 암호화할 딕셔너리 데이터
|
||||
|
||||
Returns:
|
||||
암호화된 문자열
|
||||
"""
|
||||
json_string = json.dumps(data, ensure_ascii=False)
|
||||
return self.encrypt(json_string)
|
||||
|
||||
def decrypt_json(self, encrypted_data: str) -> Dict[str, Any]:
|
||||
"""
|
||||
암호화된 JSON 데이터 복호화
|
||||
|
||||
암호문을 복호화하여 딕셔너리로 파싱합니다.
|
||||
|
||||
Args:
|
||||
encrypted_data: 암호화된 문자열
|
||||
|
||||
Returns:
|
||||
복호화된 딕셔너리
|
||||
|
||||
Raises:
|
||||
ValueError: JSON 파싱 실패
|
||||
"""
|
||||
decrypted_string = self.decrypt(encrypted_data)
|
||||
try:
|
||||
return json.loads(decrypted_string)
|
||||
except json.JSONDecodeError as e:
|
||||
logger.error(f"JSON 파싱 실패: {e}")
|
||||
raise ValueError("유효하지 않은 JSON 데이터입니다")
|
||||
|
||||
@staticmethod
|
||||
def generate_new_key() -> str:
|
||||
"""
|
||||
새 암호화 키 생성
|
||||
|
||||
환경변수 설정에 사용할 수 있는 새 Fernet 키를 생성합니다.
|
||||
|
||||
Returns:
|
||||
새로 생성된 Base64 인코딩 키 문자열
|
||||
|
||||
Example:
|
||||
>>> new_key = EncryptionService.generate_new_key()
|
||||
>>> print(f"INSTAGRAM_ENCRYPTION_KEY={new_key}")
|
||||
"""
|
||||
return Fernet.generate_key().decode()
|
||||
|
||||
|
||||
# ============================================
|
||||
# 테스트용 메인 함수
|
||||
# ============================================
|
||||
if __name__ == '__main__':
|
||||
# 새 키 생성 테스트
|
||||
print("=" * 50)
|
||||
print("새 암호화 키 생성 테스트")
|
||||
print("=" * 50)
|
||||
|
||||
new_key = EncryptionService.generate_new_key()
|
||||
print(f"\n생성된 키: {new_key}")
|
||||
print(f"\n환경변수 설정:")
|
||||
print(f"INSTAGRAM_ENCRYPTION_KEY={new_key}")
|
||||
|
||||
# 암호화/복호화 테스트
|
||||
print("\n" + "=" * 50)
|
||||
print("암호화/복호화 테스트")
|
||||
print("=" * 50)
|
||||
|
||||
encryptor = EncryptionService(new_key)
|
||||
|
||||
# 문자열 테스트
|
||||
test_password = "my_instagram_password_123!"
|
||||
encrypted = encryptor.encrypt(test_password)
|
||||
decrypted = encryptor.decrypt(encrypted)
|
||||
|
||||
print(f"\n원본: {test_password}")
|
||||
print(f"암호화: {encrypted[:50]}...")
|
||||
print(f"복호화: {decrypted}")
|
||||
print(f"일치: {test_password == decrypted}")
|
||||
|
||||
# JSON 테스트
|
||||
print("\n" + "=" * 50)
|
||||
print("JSON 암호화 테스트")
|
||||
print("=" * 50)
|
||||
|
||||
test_session = {
|
||||
'session_id': 'abc123',
|
||||
'cookies': {'ds_user_id': '12345'},
|
||||
'user_agent': 'Instagram 123.0'
|
||||
}
|
||||
|
||||
encrypted_json = encryptor.encrypt_json(test_session)
|
||||
decrypted_json = encryptor.decrypt_json(encrypted_json)
|
||||
|
||||
print(f"\n원본: {test_session}")
|
||||
print(f"암호화: {encrypted_json[:50]}...")
|
||||
print(f"복호화: {decrypted_json}")
|
||||
print(f"일치: {test_session == decrypted_json}")
|
||||
@@ -0,0 +1,558 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Instagram 클라이언트 매니저
|
||||
|
||||
instagrapi 라이브러리를 래핑하여 Instagram 로그인, 세션 관리,
|
||||
영상 업로드 기능을 제공합니다.
|
||||
|
||||
주요 클래스:
|
||||
- InstagramClientManager: Instagram API 작업을 위한 고수준 인터페이스
|
||||
|
||||
안전한 사용을 위한 권장사항:
|
||||
- 주 1회 이하 업로드 권장
|
||||
- 빠른 연속 요청 자제
|
||||
- 2FA 활성화된 계정 지원
|
||||
"""
|
||||
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Optional, Dict, Any, Tuple
|
||||
from datetime import datetime
|
||||
|
||||
from instagrapi import Client
|
||||
from instagrapi.exceptions import (
|
||||
LoginRequired,
|
||||
TwoFactorRequired,
|
||||
ChallengeRequired,
|
||||
BadPassword,
|
||||
PleaseWaitFewMinutes,
|
||||
ClientError
|
||||
)
|
||||
|
||||
from encryption_service import EncryptionService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ============================================
|
||||
# 상수 정의
|
||||
# ============================================
|
||||
|
||||
# 기본 User-Agent (Instagram Android 앱)
|
||||
DEFAULT_USER_AGENT = (
|
||||
"Instagram 275.0.0.27.98 Android "
|
||||
"(33/13; 420dpi; 1080x2400; samsung; SM-G998B; "
|
||||
"o1s; exynos2100; ko_KR; 458229258)"
|
||||
)
|
||||
|
||||
# 업로드 재시도 설정
|
||||
MAX_UPLOAD_RETRIES = 2
|
||||
RETRY_DELAY_SECONDS = 5
|
||||
|
||||
# 세션 파일 저장 경로 (디버깅용)
|
||||
SESSION_DIR = Path(__file__).parent / 'sessions'
|
||||
|
||||
|
||||
class InstagramClientManager:
|
||||
"""
|
||||
Instagram API 클라이언트 매니저
|
||||
|
||||
Instagram 계정 로그인, 세션 관리, 영상 업로드 등의 기능을 제공합니다.
|
||||
모든 민감한 데이터는 암호화하여 처리합니다.
|
||||
|
||||
Attributes:
|
||||
encryption: 암호화 서비스 인스턴스
|
||||
|
||||
Example:
|
||||
>>> manager = InstagramClientManager(encryption_service)
|
||||
>>> result = manager.login("username", "password")
|
||||
>>> if result['success']:
|
||||
... print(f"로그인 성공! 세션: {result['encrypted_session']}")
|
||||
"""
|
||||
|
||||
def __init__(self, encryption_service: EncryptionService):
|
||||
"""
|
||||
Instagram 클라이언트 매니저 초기화
|
||||
|
||||
Args:
|
||||
encryption_service: 비밀번호/세션 암호화를 위한 서비스
|
||||
"""
|
||||
self.encryption = encryption_service
|
||||
|
||||
# 세션 디렉토리 생성 (디버깅용)
|
||||
SESSION_DIR.mkdir(exist_ok=True)
|
||||
|
||||
def _create_client(self) -> Client:
|
||||
"""
|
||||
새 Instagram 클라이언트 인스턴스 생성
|
||||
|
||||
적절한 설정으로 초기화된 instagrapi Client를 반환합니다.
|
||||
|
||||
Returns:
|
||||
초기화된 Client 인스턴스
|
||||
"""
|
||||
client = Client()
|
||||
|
||||
# 기본 설정
|
||||
client.delay_range = [1, 3] # API 호출 간 딜레이 (초)
|
||||
client.set_locale('ko_KR')
|
||||
client.set_timezone_offset(9 * 3600) # KST (UTC+9)
|
||||
|
||||
return client
|
||||
|
||||
def _handle_login_error(self, error: Exception, username: str) -> Dict[str, Any]:
|
||||
"""
|
||||
로그인 에러 처리 및 적절한 응답 생성
|
||||
|
||||
Args:
|
||||
error: 발생한 예외
|
||||
username: 로그인 시도한 사용자명
|
||||
|
||||
Returns:
|
||||
에러 정보가 담긴 딕셔너리
|
||||
"""
|
||||
error_str = str(error).lower()
|
||||
|
||||
if isinstance(error, BadPassword):
|
||||
return {
|
||||
'success': False,
|
||||
'error': '아이디 또는 비밀번호가 올바르지 않습니다.',
|
||||
'error_code': 'BAD_PASSWORD'
|
||||
}
|
||||
|
||||
elif isinstance(error, TwoFactorRequired):
|
||||
return {
|
||||
'success': False,
|
||||
'error': '2단계 인증이 필요합니다. 인증 코드를 입력해주세요.',
|
||||
'error_code': 'TWO_FACTOR_REQUIRED',
|
||||
'requires_2fa': True
|
||||
}
|
||||
|
||||
elif isinstance(error, ChallengeRequired):
|
||||
return {
|
||||
'success': False,
|
||||
'error': 'Instagram 보안 확인이 필요합니다. 앱에서 확인 후 다시 시도해주세요.',
|
||||
'error_code': 'CHALLENGE_REQUIRED'
|
||||
}
|
||||
|
||||
elif isinstance(error, PleaseWaitFewMinutes):
|
||||
return {
|
||||
'success': False,
|
||||
'error': '너무 많은 요청이 발생했습니다. 몇 분 후 다시 시도해주세요.',
|
||||
'error_code': 'RATE_LIMITED'
|
||||
}
|
||||
|
||||
elif 'checkpoint' in error_str or 'challenge' in error_str:
|
||||
return {
|
||||
'success': False,
|
||||
'error': 'Instagram에서 계정 확인을 요청했습니다. 앱에서 확인 후 다시 시도해주세요.',
|
||||
'error_code': 'CHECKPOINT_REQUIRED'
|
||||
}
|
||||
|
||||
else:
|
||||
logger.error(f"[로그인 에러] 사용자: {username}, 에러: {error}", exc_info=True)
|
||||
return {
|
||||
'success': False,
|
||||
'error': f'로그인 중 오류가 발생했습니다: {str(error)}',
|
||||
'error_code': 'LOGIN_FAILED'
|
||||
}
|
||||
|
||||
def login(
|
||||
self,
|
||||
username: str,
|
||||
password: str,
|
||||
verification_code: Optional[str] = None
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Instagram 계정 로그인
|
||||
|
||||
사용자명과 비밀번호로 Instagram에 로그인합니다.
|
||||
성공 시 암호화된 비밀번호와 세션 정보를 반환합니다.
|
||||
|
||||
Args:
|
||||
username: Instagram 사용자명
|
||||
password: Instagram 비밀번호
|
||||
verification_code: 2FA 인증 코드 (선택)
|
||||
|
||||
Returns:
|
||||
성공 시: {
|
||||
'success': True,
|
||||
'encrypted_password': '암호화된 비밀번호',
|
||||
'encrypted_session': '암호화된 세션',
|
||||
'username': '확인된 사용자명',
|
||||
'user_id': 'Instagram 사용자 ID',
|
||||
'full_name': '표시 이름'
|
||||
}
|
||||
실패 시: {
|
||||
'success': False,
|
||||
'error': '에러 메시지',
|
||||
'error_code': '에러 코드'
|
||||
}
|
||||
"""
|
||||
client = self._create_client()
|
||||
|
||||
try:
|
||||
logger.info(f"[로그인 시도] 사용자: {username}")
|
||||
|
||||
# 2FA 코드가 있는 경우
|
||||
if verification_code:
|
||||
logger.info(f"[2FA 인증] 코드 입력됨")
|
||||
client.login(
|
||||
username,
|
||||
password,
|
||||
verification_code=verification_code
|
||||
)
|
||||
else:
|
||||
client.login(username, password)
|
||||
|
||||
# 로그인 성공 - 세션 정보 추출
|
||||
session_data = client.get_settings()
|
||||
user_id = client.user_id
|
||||
user_info = client.user_info(user_id)
|
||||
|
||||
# 비밀번호와 세션 암호화
|
||||
encrypted_password = self.encryption.encrypt(password)
|
||||
encrypted_session = self.encryption.encrypt_json(session_data)
|
||||
|
||||
logger.info(f"[로그인 성공] 사용자: {username}, ID: {user_id}")
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'encrypted_password': encrypted_password,
|
||||
'encrypted_session': encrypted_session,
|
||||
'username': user_info.username,
|
||||
'user_id': str(user_id),
|
||||
'full_name': user_info.full_name,
|
||||
'profile_pic_url': str(user_info.profile_pic_url) if user_info.profile_pic_url else None
|
||||
}
|
||||
|
||||
except TwoFactorRequired:
|
||||
# 2FA 필요 - 사용자에게 코드 입력 요청
|
||||
logger.info(f"[2FA 필요] 사용자: {username}")
|
||||
return {
|
||||
'success': False,
|
||||
'error': '2단계 인증이 필요합니다. 인증 코드를 입력해주세요.',
|
||||
'error_code': 'TWO_FACTOR_REQUIRED',
|
||||
'requires_2fa': True
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
return self._handle_login_error(e, username)
|
||||
|
||||
def login_with_session(self, encrypted_session: str) -> Tuple[Optional[Client], Optional[str]]:
|
||||
"""
|
||||
저장된 세션으로 로그인
|
||||
|
||||
암호화된 세션 데이터를 복호화하여 로그인 상태를 복원합니다.
|
||||
새 로그인 과정 없이 빠르게 인증된 클라이언트를 얻을 수 있습니다.
|
||||
|
||||
Args:
|
||||
encrypted_session: 암호화된 세션 JSON 문자열
|
||||
|
||||
Returns:
|
||||
(Client 인스턴스, None) - 성공 시
|
||||
(None, 에러 메시지) - 실패 시
|
||||
"""
|
||||
try:
|
||||
# 세션 복호화
|
||||
session_data = self.encryption.decrypt_json(encrypted_session)
|
||||
|
||||
# 클라이언트 생성 및 세션 설정
|
||||
client = self._create_client()
|
||||
client.set_settings(session_data)
|
||||
|
||||
# 세션 유효성 확인 (간단한 API 호출)
|
||||
client.get_timeline_feed()
|
||||
|
||||
return client, None
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"[세션 로그인 실패] {e}")
|
||||
return None, str(e)
|
||||
|
||||
def verify_and_refresh_session(
|
||||
self,
|
||||
encrypted_session: str,
|
||||
encrypted_password: Optional[str] = None,
|
||||
username: Optional[str] = None
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
세션 유효성 검증 및 필요시 갱신
|
||||
|
||||
저장된 세션이 유효한지 확인하고, 만료된 경우
|
||||
비밀번호로 재로그인을 시도합니다.
|
||||
|
||||
Args:
|
||||
encrypted_session: 암호화된 세션
|
||||
encrypted_password: 암호화된 비밀번호 (재로그인용)
|
||||
username: 사용자명 (재로그인용)
|
||||
|
||||
Returns:
|
||||
세션 상태 및 갱신된 세션 정보
|
||||
"""
|
||||
# 먼저 기존 세션으로 시도
|
||||
client, error = self.login_with_session(encrypted_session)
|
||||
|
||||
if client:
|
||||
return {
|
||||
'success': True,
|
||||
'valid': True,
|
||||
'message': '세션이 유효합니다.',
|
||||
'encrypted_session': encrypted_session
|
||||
}
|
||||
|
||||
# 세션 만료 - 재로그인 시도
|
||||
if encrypted_password and username:
|
||||
logger.info(f"[세션 만료] 재로그인 시도: {username}")
|
||||
try:
|
||||
password = self.encryption.decrypt(encrypted_password)
|
||||
return self.login(username, password)
|
||||
except Exception as e:
|
||||
logger.error(f"[재로그인 실패] {e}")
|
||||
return {
|
||||
'success': False,
|
||||
'valid': False,
|
||||
'error': '세션이 만료되었고 재로그인에 실패했습니다.',
|
||||
'error_code': 'SESSION_EXPIRED'
|
||||
}
|
||||
else:
|
||||
return {
|
||||
'success': False,
|
||||
'valid': False,
|
||||
'error': '세션이 만료되었습니다. 다시 로그인해주세요.',
|
||||
'error_code': 'SESSION_EXPIRED'
|
||||
}
|
||||
|
||||
def upload_video(
|
||||
self,
|
||||
encrypted_session: str,
|
||||
encrypted_password: Optional[str],
|
||||
username: Optional[str],
|
||||
video_path: str,
|
||||
caption: str = "",
|
||||
thumbnail_path: Optional[str] = None,
|
||||
as_reel: bool = True
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Instagram에 영상 업로드
|
||||
|
||||
릴스(Reels) 또는 일반 비디오로 영상을 업로드합니다.
|
||||
|
||||
Args:
|
||||
encrypted_session: 암호화된 세션
|
||||
encrypted_password: 암호화된 비밀번호 (세션 만료 시 재로그인용)
|
||||
username: 사용자명
|
||||
video_path: 업로드할 영상 파일 경로
|
||||
caption: 게시물 캡션 (해시태그 포함 가능)
|
||||
thumbnail_path: 커버 이미지 경로 (선택)
|
||||
as_reel: True면 릴스로, False면 일반 비디오로 업로드
|
||||
|
||||
Returns:
|
||||
성공 시: {
|
||||
'success': True,
|
||||
'media_id': 'Instagram 미디어 ID',
|
||||
'post_code': '게시물 코드',
|
||||
'permalink': '게시물 URL',
|
||||
'new_session': '갱신된 세션 (있는 경우)'
|
||||
}
|
||||
실패 시: {
|
||||
'success': False,
|
||||
'error': '에러 메시지',
|
||||
'error_code': '에러 코드'
|
||||
}
|
||||
"""
|
||||
client = None
|
||||
new_session = None
|
||||
|
||||
# 1. 세션으로 로그인 시도
|
||||
client, error = self.login_with_session(encrypted_session)
|
||||
|
||||
# 2. 세션 만료 시 재로그인
|
||||
if not client and encrypted_password and username:
|
||||
logger.info(f"[세션 만료] 재로그인 후 업로드 시도: {username}")
|
||||
try:
|
||||
password = self.encryption.decrypt(encrypted_password)
|
||||
login_result = self.login(username, password)
|
||||
if login_result['success']:
|
||||
client, _ = self.login_with_session(login_result['encrypted_session'])
|
||||
new_session = login_result['encrypted_session']
|
||||
except Exception as e:
|
||||
logger.error(f"[재로그인 실패] {e}")
|
||||
|
||||
if not client:
|
||||
return {
|
||||
'success': False,
|
||||
'error': '로그인에 실패했습니다. 계정 연결을 다시 해주세요.',
|
||||
'error_code': 'LOGIN_FAILED'
|
||||
}
|
||||
|
||||
# 3. 업로드 실행 (재시도 로직 포함)
|
||||
for attempt in range(MAX_UPLOAD_RETRIES + 1):
|
||||
try:
|
||||
logger.info(f"[업로드 시도 {attempt + 1}/{MAX_UPLOAD_RETRIES + 1}] {video_path}")
|
||||
|
||||
# 파일 경로 처리
|
||||
video_path_obj = Path(video_path)
|
||||
|
||||
if as_reel:
|
||||
# 릴스로 업로드
|
||||
if thumbnail_path and Path(thumbnail_path).exists():
|
||||
media = client.clip_upload(
|
||||
path=video_path_obj,
|
||||
caption=caption,
|
||||
thumbnail=Path(thumbnail_path)
|
||||
)
|
||||
else:
|
||||
media = client.clip_upload(
|
||||
path=video_path_obj,
|
||||
caption=caption
|
||||
)
|
||||
else:
|
||||
# 일반 비디오로 업로드
|
||||
if thumbnail_path and Path(thumbnail_path).exists():
|
||||
media = client.video_upload(
|
||||
path=video_path_obj,
|
||||
caption=caption,
|
||||
thumbnail=Path(thumbnail_path)
|
||||
)
|
||||
else:
|
||||
media = client.video_upload(
|
||||
path=video_path_obj,
|
||||
caption=caption
|
||||
)
|
||||
|
||||
# 업로드 성공
|
||||
result = {
|
||||
'success': True,
|
||||
'media_id': str(media.pk),
|
||||
'post_code': media.code,
|
||||
'permalink': f'https://www.instagram.com/p/{media.code}/',
|
||||
'media_type': 'reel' if as_reel else 'video'
|
||||
}
|
||||
|
||||
if new_session:
|
||||
result['new_session'] = new_session
|
||||
|
||||
logger.info(f"[업로드 성공] 미디어 ID: {media.pk}")
|
||||
return result
|
||||
|
||||
except PleaseWaitFewMinutes as e:
|
||||
logger.warning(f"[Rate Limit] {e}")
|
||||
if attempt < MAX_UPLOAD_RETRIES:
|
||||
time.sleep(RETRY_DELAY_SECONDS * (attempt + 1))
|
||||
continue
|
||||
return {
|
||||
'success': False,
|
||||
'error': '업로드 제한에 걸렸습니다. 나중에 다시 시도해주세요.',
|
||||
'error_code': 'RATE_LIMITED'
|
||||
}
|
||||
|
||||
except LoginRequired as e:
|
||||
logger.error(f"[로그인 필요] {e}")
|
||||
return {
|
||||
'success': False,
|
||||
'error': '세션이 만료되었습니다. 다시 로그인해주세요.',
|
||||
'error_code': 'SESSION_EXPIRED'
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[업로드 에러] {e}", exc_info=True)
|
||||
if attempt < MAX_UPLOAD_RETRIES:
|
||||
time.sleep(RETRY_DELAY_SECONDS)
|
||||
continue
|
||||
return {
|
||||
'success': False,
|
||||
'error': f'업로드 중 오류가 발생했습니다: {str(e)}',
|
||||
'error_code': 'UPLOAD_FAILED'
|
||||
}
|
||||
|
||||
return {
|
||||
'success': False,
|
||||
'error': '업로드에 실패했습니다. 최대 재시도 횟수를 초과했습니다.',
|
||||
'error_code': 'MAX_RETRIES_EXCEEDED'
|
||||
}
|
||||
|
||||
def get_account_info(self, encrypted_session: str) -> Dict[str, Any]:
|
||||
"""
|
||||
연결된 Instagram 계정 정보 조회
|
||||
|
||||
Args:
|
||||
encrypted_session: 암호화된 세션
|
||||
|
||||
Returns:
|
||||
계정 정보 딕셔너리
|
||||
"""
|
||||
client, error = self.login_with_session(encrypted_session)
|
||||
|
||||
if not client:
|
||||
return {
|
||||
'success': False,
|
||||
'error': '세션이 유효하지 않습니다.',
|
||||
'error_code': 'INVALID_SESSION'
|
||||
}
|
||||
|
||||
try:
|
||||
user_id = client.user_id
|
||||
user_info = client.user_info(user_id)
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'username': user_info.username,
|
||||
'full_name': user_info.full_name,
|
||||
'profile_pic_url': str(user_info.profile_pic_url) if user_info.profile_pic_url else None,
|
||||
'follower_count': user_info.follower_count,
|
||||
'following_count': user_info.following_count,
|
||||
'media_count': user_info.media_count,
|
||||
'is_private': user_info.is_private,
|
||||
'is_verified': user_info.is_verified
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[계정 정보 조회 실패] {e}")
|
||||
return {
|
||||
'success': False,
|
||||
'error': f'계정 정보를 가져오는 데 실패했습니다: {str(e)}',
|
||||
'error_code': 'INFO_FAILED'
|
||||
}
|
||||
|
||||
def logout(self, encrypted_session: str) -> bool:
|
||||
"""
|
||||
로그아웃 (세션 무효화)
|
||||
|
||||
실제로 Instagram 세션을 로그아웃하지는 않고,
|
||||
로컬에서 세션 데이터만 제거합니다.
|
||||
|
||||
Args:
|
||||
encrypted_session: 암호화된 세션
|
||||
|
||||
Returns:
|
||||
항상 True (에러 무시)
|
||||
"""
|
||||
try:
|
||||
client, _ = self.login_with_session(encrypted_session)
|
||||
if client:
|
||||
# Instagram API에는 공식 로그아웃이 없음
|
||||
# 세션 데이터만 버림
|
||||
pass
|
||||
except:
|
||||
pass
|
||||
|
||||
return True
|
||||
|
||||
|
||||
# ============================================
|
||||
# 테스트용 메인 함수
|
||||
# ============================================
|
||||
if __name__ == '__main__':
|
||||
from encryption_service import EncryptionService
|
||||
|
||||
print("=" * 50)
|
||||
print("Instagram 클라이언트 매니저 테스트")
|
||||
print("=" * 50)
|
||||
print("\n이 모듈은 직접 실행하지 않습니다.")
|
||||
print("instagram_service.py를 실행하세요.")
|
||||
print("\n사용 예:")
|
||||
print(" python instagram_service.py")
|
||||
@@ -0,0 +1,425 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Instagram 자동 업로드 서비스
|
||||
|
||||
이 모듈은 Instagram 계정 연결 및 릴스/영상 업로드 기능을 제공합니다.
|
||||
Flask REST API를 통해 Node.js 백엔드와 통신합니다.
|
||||
|
||||
주요 기능:
|
||||
1. Instagram 계정 로그인 및 세션 관리
|
||||
2. 비밀번호/세션 암호화 저장
|
||||
3. 릴스(Reels) 영상 업로드
|
||||
4. 업로드 상태 추적
|
||||
|
||||
사용법:
|
||||
python instagram_service.py
|
||||
|
||||
환경변수:
|
||||
INSTAGRAM_ENCRYPTION_KEY: Fernet 암호화 키 (32바이트 base64)
|
||||
INSTAGRAM_SERVICE_PORT: 서비스 포트 (기본: 5001)
|
||||
"""
|
||||
|
||||
import os
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Optional, Dict, Any, Tuple
|
||||
|
||||
from flask import Flask, request, jsonify
|
||||
from flask_cors import CORS
|
||||
from dotenv import load_dotenv
|
||||
|
||||
from encryption_service import EncryptionService
|
||||
from instagram_client import InstagramClientManager
|
||||
|
||||
# ============================================
|
||||
# 로깅 설정
|
||||
# ============================================
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='[%(asctime)s] [%(levelname)s] %(message)s',
|
||||
datefmt='%Y-%m-%d %H:%M:%S'
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ============================================
|
||||
# 환경변수 로드
|
||||
# ============================================
|
||||
load_dotenv(dotenv_path=Path(__file__).parent.parent.parent / '.env')
|
||||
|
||||
# Flask 앱 초기화
|
||||
app = Flask(__name__)
|
||||
CORS(app)
|
||||
|
||||
# 서비스 초기화
|
||||
encryption_service: Optional[EncryptionService] = None
|
||||
instagram_manager: Optional[InstagramClientManager] = None
|
||||
|
||||
|
||||
def get_encryption_service() -> EncryptionService:
|
||||
"""암호화 서비스 인스턴스 반환 (지연 초기화)"""
|
||||
global encryption_service
|
||||
if encryption_service is None:
|
||||
key = os.getenv('INSTAGRAM_ENCRYPTION_KEY')
|
||||
if not key:
|
||||
# 키가 없으면 새로 생성하고 경고
|
||||
logger.warning("INSTAGRAM_ENCRYPTION_KEY 환경변수가 없습니다. 새 키를 생성합니다.")
|
||||
encryption_service = EncryptionService()
|
||||
logger.warning(f"생성된 키 (환경변수에 저장하세요): {encryption_service.get_key_string()}")
|
||||
else:
|
||||
encryption_service = EncryptionService(key)
|
||||
return encryption_service
|
||||
|
||||
|
||||
def get_instagram_manager() -> InstagramClientManager:
|
||||
"""Instagram 클라이언트 매니저 인스턴스 반환 (지연 초기화)"""
|
||||
global instagram_manager
|
||||
if instagram_manager is None:
|
||||
instagram_manager = InstagramClientManager(get_encryption_service())
|
||||
return instagram_manager
|
||||
|
||||
|
||||
# ============================================
|
||||
# API 엔드포인트
|
||||
# ============================================
|
||||
|
||||
@app.route('/health', methods=['GET'])
|
||||
def health_check():
|
||||
"""
|
||||
헬스 체크 엔드포인트
|
||||
|
||||
서비스가 정상 동작 중인지 확인합니다.
|
||||
"""
|
||||
return jsonify({
|
||||
'status': 'ok',
|
||||
'service': 'instagram-upload-service',
|
||||
'timestamp': datetime.now().isoformat()
|
||||
})
|
||||
|
||||
|
||||
@app.route('/connect', methods=['POST'])
|
||||
def connect_account():
|
||||
"""
|
||||
Instagram 계정 연결
|
||||
|
||||
사용자의 Instagram 아이디/비밀번호로 로그인을 시도하고,
|
||||
성공 시 암호화된 비밀번호와 세션 정보를 반환합니다.
|
||||
|
||||
Request Body:
|
||||
{
|
||||
"username": "instagram_username",
|
||||
"password": "instagram_password",
|
||||
"verification_code": "2FA 코드 (선택사항)"
|
||||
}
|
||||
|
||||
Response:
|
||||
성공: {
|
||||
"success": true,
|
||||
"encrypted_password": "암호화된 비밀번호",
|
||||
"encrypted_session": "암호화된 세션 데이터",
|
||||
"username": "확인된 사용자명",
|
||||
"user_id": "Instagram 사용자 ID"
|
||||
}
|
||||
실패: {
|
||||
"success": false,
|
||||
"error": "에러 메시지",
|
||||
"error_code": "에러 코드",
|
||||
"requires_2fa": true/false
|
||||
}
|
||||
"""
|
||||
try:
|
||||
data = request.get_json()
|
||||
|
||||
if not data:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': '요청 데이터가 없습니다.',
|
||||
'error_code': 'NO_DATA'
|
||||
}), 400
|
||||
|
||||
username = data.get('username', '').strip()
|
||||
password = data.get('password', '').strip()
|
||||
verification_code = data.get('verification_code', '').strip()
|
||||
|
||||
if not username or not password:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': '아이디와 비밀번호를 입력해주세요.',
|
||||
'error_code': 'MISSING_CREDENTIALS'
|
||||
}), 400
|
||||
|
||||
logger.info(f"[Instagram 연결 시도] 사용자: {username}")
|
||||
|
||||
manager = get_instagram_manager()
|
||||
result = manager.login(username, password, verification_code)
|
||||
|
||||
if result['success']:
|
||||
logger.info(f"[Instagram 연결 성공] 사용자: {username}")
|
||||
return jsonify(result)
|
||||
else:
|
||||
logger.warning(f"[Instagram 연결 실패] 사용자: {username}, 에러: {result.get('error')}")
|
||||
return jsonify(result), 401 if result.get('error_code') == 'LOGIN_FAILED' else 400
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[Instagram 연결 에러] {str(e)}", exc_info=True)
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': f'서버 오류가 발생했습니다: {str(e)}',
|
||||
'error_code': 'SERVER_ERROR'
|
||||
}), 500
|
||||
|
||||
|
||||
@app.route('/verify-session', methods=['POST'])
|
||||
def verify_session():
|
||||
"""
|
||||
저장된 세션 유효성 검증
|
||||
|
||||
암호화된 세션으로 로그인이 가능한지 확인합니다.
|
||||
세션이 만료되었으면 비밀번호로 재로그인을 시도합니다.
|
||||
|
||||
Request Body:
|
||||
{
|
||||
"encrypted_session": "암호화된 세션",
|
||||
"encrypted_password": "암호화된 비밀번호 (재로그인용)",
|
||||
"username": "사용자명"
|
||||
}
|
||||
|
||||
Response:
|
||||
성공: {
|
||||
"success": true,
|
||||
"valid": true,
|
||||
"new_session": "새 세션 (갱신된 경우)",
|
||||
"username": "사용자명"
|
||||
}
|
||||
"""
|
||||
try:
|
||||
data = request.get_json()
|
||||
|
||||
encrypted_session = data.get('encrypted_session')
|
||||
encrypted_password = data.get('encrypted_password')
|
||||
username = data.get('username')
|
||||
|
||||
if not encrypted_session:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': '세션 정보가 없습니다.',
|
||||
'error_code': 'NO_SESSION'
|
||||
}), 400
|
||||
|
||||
manager = get_instagram_manager()
|
||||
result = manager.verify_and_refresh_session(
|
||||
encrypted_session,
|
||||
encrypted_password,
|
||||
username
|
||||
)
|
||||
|
||||
return jsonify(result)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[세션 검증 에러] {str(e)}", exc_info=True)
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': f'세션 검증 중 오류: {str(e)}',
|
||||
'error_code': 'SERVER_ERROR'
|
||||
}), 500
|
||||
|
||||
|
||||
@app.route('/upload', methods=['POST'])
|
||||
def upload_video():
|
||||
"""
|
||||
Instagram에 릴스/영상 업로드
|
||||
|
||||
저장된 세션을 사용하여 영상을 Instagram에 업로드합니다.
|
||||
|
||||
Request Body:
|
||||
{
|
||||
"encrypted_session": "암호화된 세션",
|
||||
"encrypted_password": "암호화된 비밀번호 (세션 만료 시 재로그인용)",
|
||||
"username": "사용자명",
|
||||
"video_path": "업로드할 영상 파일 경로",
|
||||
"caption": "게시물 캡션",
|
||||
"thumbnail_path": "썸네일 이미지 경로 (선택)",
|
||||
"upload_as_reel": true/false (기본: true)
|
||||
}
|
||||
|
||||
Response:
|
||||
성공: {
|
||||
"success": true,
|
||||
"media_id": "Instagram 미디어 ID",
|
||||
"post_code": "게시물 코드",
|
||||
"permalink": "게시물 URL"
|
||||
}
|
||||
"""
|
||||
try:
|
||||
data = request.get_json()
|
||||
|
||||
encrypted_session = data.get('encrypted_session')
|
||||
encrypted_password = data.get('encrypted_password')
|
||||
username = data.get('username')
|
||||
video_path = data.get('video_path')
|
||||
caption = data.get('caption', '')
|
||||
thumbnail_path = data.get('thumbnail_path')
|
||||
upload_as_reel = data.get('upload_as_reel', True)
|
||||
|
||||
# 필수 필드 검증
|
||||
if not encrypted_session:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': '세션 정보가 없습니다. 먼저 계정을 연결해주세요.',
|
||||
'error_code': 'NO_SESSION'
|
||||
}), 400
|
||||
|
||||
if not video_path:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': '업로드할 영상 경로가 없습니다.',
|
||||
'error_code': 'NO_VIDEO'
|
||||
}), 400
|
||||
|
||||
# 파일 존재 확인
|
||||
if not os.path.exists(video_path):
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': f'영상 파일을 찾을 수 없습니다: {video_path}',
|
||||
'error_code': 'FILE_NOT_FOUND'
|
||||
}), 400
|
||||
|
||||
logger.info(f"[Instagram 업로드 시작] 사용자: {username}, 파일: {video_path}")
|
||||
|
||||
manager = get_instagram_manager()
|
||||
result = manager.upload_video(
|
||||
encrypted_session=encrypted_session,
|
||||
encrypted_password=encrypted_password,
|
||||
username=username,
|
||||
video_path=video_path,
|
||||
caption=caption,
|
||||
thumbnail_path=thumbnail_path,
|
||||
as_reel=upload_as_reel
|
||||
)
|
||||
|
||||
if result['success']:
|
||||
logger.info(f"[Instagram 업로드 성공] 미디어 ID: {result.get('media_id')}")
|
||||
return jsonify(result)
|
||||
else:
|
||||
logger.error(f"[Instagram 업로드 실패] {result.get('error')}")
|
||||
return jsonify(result), 400
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[Instagram 업로드 에러] {str(e)}", exc_info=True)
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': f'업로드 중 오류 발생: {str(e)}',
|
||||
'error_code': 'UPLOAD_ERROR'
|
||||
}), 500
|
||||
|
||||
|
||||
@app.route('/disconnect', methods=['POST'])
|
||||
def disconnect_account():
|
||||
"""
|
||||
Instagram 계정 연결 해제
|
||||
|
||||
로컬에 저장된 세션 정보만 삭제합니다.
|
||||
Instagram 계정 자체에는 영향이 없습니다.
|
||||
|
||||
Request Body:
|
||||
{
|
||||
"encrypted_session": "암호화된 세션"
|
||||
}
|
||||
|
||||
Response:
|
||||
{
|
||||
"success": true,
|
||||
"message": "계정 연결이 해제되었습니다."
|
||||
}
|
||||
"""
|
||||
try:
|
||||
data = request.get_json()
|
||||
encrypted_session = data.get('encrypted_session')
|
||||
|
||||
if encrypted_session:
|
||||
manager = get_instagram_manager()
|
||||
manager.logout(encrypted_session)
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'message': '계정 연결이 해제되었습니다.'
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[연결 해제 에러] {str(e)}", exc_info=True)
|
||||
return jsonify({
|
||||
'success': True, # 에러가 나도 성공으로 처리 (어차피 연결 해제)
|
||||
'message': '계정 연결이 해제되었습니다.'
|
||||
})
|
||||
|
||||
|
||||
@app.route('/account-info', methods=['POST'])
|
||||
def get_account_info():
|
||||
"""
|
||||
Instagram 계정 정보 조회
|
||||
|
||||
연결된 계정의 기본 정보를 조회합니다.
|
||||
|
||||
Request Body:
|
||||
{
|
||||
"encrypted_session": "암호화된 세션"
|
||||
}
|
||||
|
||||
Response:
|
||||
{
|
||||
"success": true,
|
||||
"username": "사용자명",
|
||||
"full_name": "이름",
|
||||
"profile_pic_url": "프로필 사진 URL",
|
||||
"follower_count": 팔로워 수,
|
||||
"media_count": 게시물 수
|
||||
}
|
||||
"""
|
||||
try:
|
||||
data = request.get_json()
|
||||
encrypted_session = data.get('encrypted_session')
|
||||
|
||||
if not encrypted_session:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': '세션 정보가 없습니다.',
|
||||
'error_code': 'NO_SESSION'
|
||||
}), 400
|
||||
|
||||
manager = get_instagram_manager()
|
||||
result = manager.get_account_info(encrypted_session)
|
||||
|
||||
return jsonify(result)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[계정 정보 조회 에러] {str(e)}", exc_info=True)
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': f'계정 정보 조회 중 오류: {str(e)}',
|
||||
'error_code': 'SERVER_ERROR'
|
||||
}), 500
|
||||
|
||||
|
||||
# ============================================
|
||||
# 메인 실행
|
||||
# ============================================
|
||||
if __name__ == '__main__':
|
||||
port = int(os.getenv('INSTAGRAM_SERVICE_PORT', 5001))
|
||||
debug = os.getenv('FLASK_DEBUG', 'false').lower() == 'true'
|
||||
|
||||
logger.info(f"Instagram 업로드 서비스 시작 - 포트: {port}")
|
||||
logger.info("엔드포인트:")
|
||||
logger.info(" GET /health - 헬스 체크")
|
||||
logger.info(" POST /connect - 계정 연결")
|
||||
logger.info(" POST /verify-session - 세션 검증")
|
||||
logger.info(" POST /upload - 영상 업로드")
|
||||
logger.info(" POST /disconnect - 계정 연결 해제")
|
||||
logger.info(" POST /account-info - 계정 정보 조회")
|
||||
|
||||
app.run(
|
||||
host='0.0.0.0',
|
||||
port=port,
|
||||
debug=debug
|
||||
)
|
||||
@@ -0,0 +1,9 @@
|
||||
# Instagram 자동 업로드를 위한 Python 패키지
|
||||
# pip install -r requirements.txt
|
||||
|
||||
instagrapi==2.1.2 # Instagram Private API 클라이언트
|
||||
Pillow>=8.1.1 # 이미지 처리 (instagrapi 의존성)
|
||||
cryptography==41.0.7 # 비밀번호/세션 암호화
|
||||
flask==3.0.0 # REST API 서버
|
||||
flask-cors==4.0.0 # CORS 지원
|
||||
python-dotenv==1.0.0 # 환경변수 로드
|
||||
@@ -0,0 +1,611 @@
|
||||
/**
|
||||
* Instagram 업로드 서비스
|
||||
*
|
||||
* Python Instagram 마이크로서비스와 통신하여
|
||||
* Instagram 계정 연결 및 영상 업로드 기능을 제공합니다.
|
||||
*
|
||||
* 주요 기능:
|
||||
* 1. Instagram 계정 연결 (로그인)
|
||||
* 2. 계정 연결 해제
|
||||
* 3. 릴스/영상 업로드
|
||||
* 4. 업로드 히스토리 관리
|
||||
*
|
||||
* @module instagramService
|
||||
*/
|
||||
|
||||
const db = require('./db');
|
||||
const path = require('path');
|
||||
|
||||
// ============================================
|
||||
// 설정
|
||||
// ============================================
|
||||
|
||||
// Python Instagram 서비스 URL
|
||||
const INSTAGRAM_SERVICE_URL = process.env.INSTAGRAM_SERVICE_URL || 'http://localhost:5001';
|
||||
|
||||
// 주당 최대 업로드 횟수 (안전한 사용을 위해)
|
||||
const MAX_UPLOADS_PER_WEEK = 1;
|
||||
|
||||
// ============================================
|
||||
// 유틸리티 함수
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Python Instagram 서비스에 HTTP 요청
|
||||
*
|
||||
* @param {string} endpoint - API 엔드포인트 (예: '/connect')
|
||||
* @param {Object} data - 요청 본문 데이터
|
||||
* @returns {Promise<Object>} 응답 데이터
|
||||
*/
|
||||
async function callInstagramService(endpoint, data = {}) {
|
||||
const url = `${INSTAGRAM_SERVICE_URL}${endpoint}`;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
return result;
|
||||
|
||||
} catch (error) {
|
||||
console.error(`[Instagram 서비스 호출 실패] ${endpoint}:`, error.message);
|
||||
|
||||
// 서비스 연결 실패
|
||||
if (error.code === 'ECONNREFUSED') {
|
||||
throw new Error('Instagram 서비스에 연결할 수 없습니다. 서비스가 실행 중인지 확인하세요.');
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Instagram 서비스 헬스 체크
|
||||
*
|
||||
* @returns {Promise<boolean>} 서비스 정상 여부
|
||||
*/
|
||||
async function checkServiceHealth() {
|
||||
try {
|
||||
const response = await fetch(`${INSTAGRAM_SERVICE_URL}/health`);
|
||||
const data = await response.json();
|
||||
return data.status === 'ok';
|
||||
} catch (error) {
|
||||
console.error('[Instagram 서비스 헬스 체크 실패]', error.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 계정 연결 관리
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Instagram 계정 연결
|
||||
*
|
||||
* 사용자의 Instagram 계정을 연결하고 인증 정보를 암호화하여 저장합니다.
|
||||
*
|
||||
* @param {number} userId - 사용자 ID
|
||||
* @param {string} username - Instagram 사용자명
|
||||
* @param {string} password - Instagram 비밀번호
|
||||
* @param {string} [verificationCode] - 2FA 인증 코드 (선택)
|
||||
* @returns {Promise<Object>} 연결 결과
|
||||
*/
|
||||
async function connectAccount(userId, username, password, verificationCode = null) {
|
||||
console.log(`[Instagram 연결 시도] 사용자 ID: ${userId}, Instagram: ${username}`);
|
||||
|
||||
// Python 서비스에 로그인 요청
|
||||
const loginResult = await callInstagramService('/connect', {
|
||||
username,
|
||||
password,
|
||||
verification_code: verificationCode
|
||||
});
|
||||
|
||||
if (!loginResult.success) {
|
||||
return loginResult;
|
||||
}
|
||||
|
||||
// DB에 연결 정보 저장
|
||||
return new Promise((resolve, reject) => {
|
||||
db.run(`
|
||||
INSERT OR REPLACE INTO instagram_connections
|
||||
(user_id, instagram_username, encrypted_password, encrypted_session,
|
||||
is_active, last_login_at, connected_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, 1, datetime('now'), datetime('now'), datetime('now'))
|
||||
`, [
|
||||
userId,
|
||||
loginResult.username,
|
||||
loginResult.encrypted_password,
|
||||
loginResult.encrypted_session
|
||||
], function(err) {
|
||||
if (err) {
|
||||
console.error('[Instagram 연결 정보 저장 실패]', err);
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
|
||||
// 기본 설정도 생성
|
||||
db.run(`
|
||||
INSERT OR IGNORE INTO instagram_settings
|
||||
(user_id, auto_upload, upload_as_reel, max_uploads_per_week)
|
||||
VALUES (?, 0, 1, ?)
|
||||
`, [userId, MAX_UPLOADS_PER_WEEK]);
|
||||
|
||||
console.log(`[Instagram 연결 성공] 사용자 ID: ${userId}`);
|
||||
|
||||
resolve({
|
||||
success: true,
|
||||
message: 'Instagram 계정이 연결되었습니다.',
|
||||
username: loginResult.username,
|
||||
user_id: loginResult.user_id,
|
||||
full_name: loginResult.full_name,
|
||||
profile_pic_url: loginResult.profile_pic_url
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Instagram 계정 연결 해제
|
||||
*
|
||||
* @param {number} userId - 사용자 ID
|
||||
* @returns {Promise<Object>} 해제 결과
|
||||
*/
|
||||
async function disconnectAccount(userId) {
|
||||
console.log(`[Instagram 연결 해제] 사용자 ID: ${userId}`);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
// 먼저 저장된 세션 조회
|
||||
db.get(
|
||||
'SELECT encrypted_session FROM instagram_connections WHERE user_id = ?',
|
||||
[userId],
|
||||
async (err, row) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
|
||||
// Python 서비스에 로그아웃 요청 (실패해도 무시)
|
||||
if (row && row.encrypted_session) {
|
||||
try {
|
||||
await callInstagramService('/disconnect', {
|
||||
encrypted_session: row.encrypted_session
|
||||
});
|
||||
} catch (e) {
|
||||
// 무시
|
||||
}
|
||||
}
|
||||
|
||||
// DB에서 삭제
|
||||
db.run(
|
||||
'DELETE FROM instagram_connections WHERE user_id = ?',
|
||||
[userId],
|
||||
function(err) {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
|
||||
// 설정도 삭제
|
||||
db.run(
|
||||
'DELETE FROM instagram_settings WHERE user_id = ?',
|
||||
[userId]
|
||||
);
|
||||
|
||||
resolve({
|
||||
success: true,
|
||||
message: 'Instagram 계정 연결이 해제되었습니다.'
|
||||
});
|
||||
}
|
||||
);
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Instagram 연결 상태 조회
|
||||
*
|
||||
* @param {number} userId - 사용자 ID
|
||||
* @returns {Promise<Object>} 연결 상태 정보
|
||||
*/
|
||||
async function getConnectionStatus(userId) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.get(`
|
||||
SELECT
|
||||
ic.instagram_username,
|
||||
ic.is_active,
|
||||
ic.two_factor_required,
|
||||
ic.connected_at,
|
||||
ic.last_login_at,
|
||||
ic.encrypted_session,
|
||||
inst.auto_upload,
|
||||
inst.upload_as_reel,
|
||||
inst.default_caption_template,
|
||||
inst.default_hashtags,
|
||||
inst.max_uploads_per_week,
|
||||
inst.notify_on_upload
|
||||
FROM instagram_connections ic
|
||||
LEFT JOIN instagram_settings inst ON ic.user_id = inst.user_id
|
||||
WHERE ic.user_id = ?
|
||||
`, [userId], async (err, row) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!row) {
|
||||
resolve({
|
||||
connected: false,
|
||||
message: 'Instagram 계정이 연결되지 않았습니다.'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// 계정 정보 조회 시도 (세션 유효성 확인)
|
||||
let accountInfo = null;
|
||||
if (row.encrypted_session) {
|
||||
try {
|
||||
const info = await callInstagramService('/account-info', {
|
||||
encrypted_session: row.encrypted_session
|
||||
});
|
||||
if (info.success) {
|
||||
accountInfo = info;
|
||||
}
|
||||
} catch (e) {
|
||||
// 세션 만료 가능성
|
||||
console.warn('[Instagram 계정 정보 조회 실패]', e.message);
|
||||
}
|
||||
}
|
||||
|
||||
resolve({
|
||||
connected: true,
|
||||
username: row.instagram_username,
|
||||
is_active: row.is_active === 1,
|
||||
two_factor_required: row.two_factor_required === 1,
|
||||
connected_at: row.connected_at,
|
||||
last_login_at: row.last_login_at,
|
||||
settings: {
|
||||
auto_upload: row.auto_upload === 1,
|
||||
upload_as_reel: row.upload_as_reel === 1,
|
||||
default_caption_template: row.default_caption_template,
|
||||
default_hashtags: row.default_hashtags,
|
||||
max_uploads_per_week: row.max_uploads_per_week || MAX_UPLOADS_PER_WEEK,
|
||||
notify_on_upload: row.notify_on_upload === 1
|
||||
},
|
||||
account_info: accountInfo ? {
|
||||
full_name: accountInfo.full_name,
|
||||
profile_pic_url: accountInfo.profile_pic_url,
|
||||
follower_count: accountInfo.follower_count,
|
||||
media_count: accountInfo.media_count
|
||||
} : null
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 설정 관리
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Instagram 업로드 설정 업데이트
|
||||
*
|
||||
* @param {number} userId - 사용자 ID
|
||||
* @param {Object} settings - 설정 객체
|
||||
* @returns {Promise<Object>} 업데이트 결과
|
||||
*/
|
||||
async function updateSettings(userId, settings) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const {
|
||||
auto_upload,
|
||||
upload_as_reel,
|
||||
default_caption_template,
|
||||
default_hashtags,
|
||||
max_uploads_per_week,
|
||||
notify_on_upload
|
||||
} = settings;
|
||||
|
||||
db.run(`
|
||||
INSERT OR REPLACE INTO instagram_settings
|
||||
(user_id, auto_upload, upload_as_reel, default_caption_template,
|
||||
default_hashtags, max_uploads_per_week, notify_on_upload, updatedAt)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now'))
|
||||
`, [
|
||||
userId,
|
||||
auto_upload ? 1 : 0,
|
||||
upload_as_reel !== false ? 1 : 0, // 기본값 true
|
||||
default_caption_template || null,
|
||||
default_hashtags || null,
|
||||
max_uploads_per_week || MAX_UPLOADS_PER_WEEK,
|
||||
notify_on_upload !== false ? 1 : 0 // 기본값 true
|
||||
], function(err) {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
|
||||
resolve({
|
||||
success: true,
|
||||
message: '설정이 저장되었습니다.'
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 영상 업로드
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* 주간 업로드 횟수 확인
|
||||
*
|
||||
* @param {number} userId - 사용자 ID
|
||||
* @returns {Promise<Object>} 이번 주 업로드 정보
|
||||
*/
|
||||
async function getWeeklyUploadCount(userId) {
|
||||
return new Promise((resolve, reject) => {
|
||||
// 이번 주 월요일 기준
|
||||
db.get(`
|
||||
SELECT
|
||||
COUNT(*) as count,
|
||||
MAX(uploaded_at) as last_upload
|
||||
FROM instagram_upload_history
|
||||
WHERE user_id = ?
|
||||
AND status = 'success'
|
||||
AND uploaded_at >= date('now', 'weekday 0', '-6 days')
|
||||
`, [userId], (err, row) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
|
||||
db.get(
|
||||
'SELECT max_uploads_per_week FROM instagram_settings WHERE user_id = ?',
|
||||
[userId],
|
||||
(err, settings) => {
|
||||
resolve({
|
||||
count: row?.count || 0,
|
||||
max: settings?.max_uploads_per_week || MAX_UPLOADS_PER_WEEK,
|
||||
last_upload: row?.last_upload
|
||||
});
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Instagram에 영상 업로드
|
||||
*
|
||||
* @param {number} userId - 사용자 ID
|
||||
* @param {number} historyId - 영상 히스토리 ID
|
||||
* @param {string} videoPath - 영상 파일 경로
|
||||
* @param {string} caption - 게시물 캡션
|
||||
* @param {Object} [options] - 추가 옵션
|
||||
* @param {string} [options.thumbnailPath] - 썸네일 이미지 경로
|
||||
* @param {boolean} [options.forceUpload] - 주간 제한 무시 여부
|
||||
* @returns {Promise<Object>} 업로드 결과
|
||||
*/
|
||||
async function uploadVideo(userId, historyId, videoPath, caption, options = {}) {
|
||||
console.log(`[Instagram 업로드 시작] 사용자 ID: ${userId}, 히스토리: ${historyId}`);
|
||||
|
||||
const { thumbnailPath, forceUpload = false } = options;
|
||||
|
||||
// 1. 주간 업로드 횟수 확인
|
||||
if (!forceUpload) {
|
||||
const weeklyStats = await getWeeklyUploadCount(userId);
|
||||
if (weeklyStats.count >= weeklyStats.max) {
|
||||
console.log(`[Instagram 업로드 제한] 주간 최대 ${weeklyStats.max}회 초과`);
|
||||
return {
|
||||
success: false,
|
||||
error: `이번 주 업로드 제한(${weeklyStats.max}회)을 초과했습니다. 다음 주에 다시 시도해주세요.`,
|
||||
error_code: 'WEEKLY_LIMIT_EXCEEDED',
|
||||
weekly_count: weeklyStats.count,
|
||||
weekly_max: weeklyStats.max,
|
||||
last_upload: weeklyStats.last_upload
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 연결 정보 조회
|
||||
const connection = await new Promise((resolve, reject) => {
|
||||
db.get(`
|
||||
SELECT * FROM instagram_connections WHERE user_id = ? AND is_active = 1
|
||||
`, [userId], (err, row) => {
|
||||
if (err) reject(err);
|
||||
else resolve(row);
|
||||
});
|
||||
});
|
||||
|
||||
if (!connection) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'Instagram 계정이 연결되지 않았습니다.',
|
||||
error_code: 'NOT_CONNECTED'
|
||||
};
|
||||
}
|
||||
|
||||
// 3. 설정 조회
|
||||
const settings = await new Promise((resolve, reject) => {
|
||||
db.get(
|
||||
'SELECT * FROM instagram_settings WHERE user_id = ?',
|
||||
[userId],
|
||||
(err, row) => {
|
||||
if (err) reject(err);
|
||||
else resolve(row || {});
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
// 4. 업로드 히스토리 레코드 생성 (pending 상태)
|
||||
const uploadHistoryId = await new Promise((resolve, reject) => {
|
||||
db.run(`
|
||||
INSERT INTO instagram_upload_history
|
||||
(user_id, history_id, caption, upload_type, status, createdAt)
|
||||
VALUES (?, ?, ?, ?, 'pending', datetime('now'))
|
||||
`, [
|
||||
userId,
|
||||
historyId,
|
||||
caption,
|
||||
settings.upload_as_reel ? 'reel' : 'video'
|
||||
], function(err) {
|
||||
if (err) reject(err);
|
||||
else resolve(this.lastID);
|
||||
});
|
||||
});
|
||||
|
||||
// 5. Python 서비스에 업로드 요청
|
||||
try {
|
||||
const result = await callInstagramService('/upload', {
|
||||
encrypted_session: connection.encrypted_session,
|
||||
encrypted_password: connection.encrypted_password,
|
||||
username: connection.instagram_username,
|
||||
video_path: videoPath,
|
||||
caption: caption,
|
||||
thumbnail_path: thumbnailPath,
|
||||
upload_as_reel: settings.upload_as_reel !== 0
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
// 성공 - 히스토리 업데이트
|
||||
await new Promise((resolve, reject) => {
|
||||
db.run(`
|
||||
UPDATE instagram_upload_history
|
||||
SET instagram_media_id = ?,
|
||||
instagram_post_code = ?,
|
||||
permalink = ?,
|
||||
status = 'success',
|
||||
uploaded_at = datetime('now')
|
||||
WHERE id = ?
|
||||
`, [
|
||||
result.media_id,
|
||||
result.post_code,
|
||||
result.permalink,
|
||||
uploadHistoryId
|
||||
], (err) => {
|
||||
if (err) reject(err);
|
||||
else resolve();
|
||||
});
|
||||
});
|
||||
|
||||
// 세션 갱신된 경우 DB 업데이트
|
||||
if (result.new_session) {
|
||||
db.run(`
|
||||
UPDATE instagram_connections
|
||||
SET encrypted_session = ?, last_login_at = datetime('now'), updated_at = datetime('now')
|
||||
WHERE user_id = ?
|
||||
`, [result.new_session, userId]);
|
||||
}
|
||||
|
||||
console.log(`[Instagram 업로드 성공] 미디어 ID: ${result.media_id}`);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
media_id: result.media_id,
|
||||
post_code: result.post_code,
|
||||
permalink: result.permalink,
|
||||
upload_history_id: uploadHistoryId
|
||||
};
|
||||
|
||||
} else {
|
||||
// 실패 - 히스토리 업데이트
|
||||
await new Promise((resolve, reject) => {
|
||||
db.run(`
|
||||
UPDATE instagram_upload_history
|
||||
SET status = 'failed',
|
||||
error_message = ?,
|
||||
retry_count = retry_count + 1
|
||||
WHERE id = ?
|
||||
`, [result.error, uploadHistoryId], (err) => {
|
||||
if (err) reject(err);
|
||||
else resolve();
|
||||
});
|
||||
});
|
||||
|
||||
console.error(`[Instagram 업로드 실패] ${result.error}`);
|
||||
return result;
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
// 에러 - 히스토리 업데이트
|
||||
await new Promise((resolve) => {
|
||||
db.run(`
|
||||
UPDATE instagram_upload_history
|
||||
SET status = 'failed',
|
||||
error_message = ?,
|
||||
retry_count = retry_count + 1
|
||||
WHERE id = ?
|
||||
`, [error.message, uploadHistoryId], () => resolve());
|
||||
});
|
||||
|
||||
console.error(`[Instagram 업로드 에러]`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 히스토리 조회
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Instagram 업로드 히스토리 조회
|
||||
*
|
||||
* @param {number} userId - 사용자 ID
|
||||
* @param {number} [limit=20] - 최대 조회 개수
|
||||
* @param {number} [offset=0] - 시작 위치
|
||||
* @returns {Promise<Array>} 업로드 히스토리 목록
|
||||
*/
|
||||
async function getUploadHistory(userId, limit = 20, offset = 0) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.all(`
|
||||
SELECT
|
||||
iuh.*,
|
||||
h.business_name,
|
||||
h.details as video_details,
|
||||
pp.brand_name as pension_name
|
||||
FROM instagram_upload_history iuh
|
||||
LEFT JOIN history h ON iuh.history_id = h.id
|
||||
LEFT JOIN pension_profiles pp ON iuh.pension_id = pp.id
|
||||
WHERE iuh.user_id = ?
|
||||
ORDER BY iuh.createdAt DESC
|
||||
LIMIT ? OFFSET ?
|
||||
`, [userId, limit, offset], (err, rows) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
resolve(rows || []);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 모듈 익스포트
|
||||
// ============================================
|
||||
|
||||
module.exports = {
|
||||
// 서비스 상태
|
||||
checkServiceHealth,
|
||||
|
||||
// 계정 관리
|
||||
connectAccount,
|
||||
disconnectAccount,
|
||||
getConnectionStatus,
|
||||
|
||||
// 설정
|
||||
updateSettings,
|
||||
|
||||
// 업로드
|
||||
uploadVideo,
|
||||
getWeeklyUploadCount,
|
||||
getUploadHistory,
|
||||
|
||||
// 상수
|
||||
INSTAGRAM_SERVICE_URL,
|
||||
MAX_UPLOADS_PER_WEEK
|
||||
};
|
||||
Generated
+5202
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "bizvibe-render-server",
|
||||
"version": "0.5.0",
|
||||
"description": "Puppeteer render server for BizVibe",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"start": "node index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.13.2",
|
||||
"bcrypt": "^6.0.0",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^17.2.3",
|
||||
"express": "^4.18.2",
|
||||
"googleapis": "^166.0.0",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"multer": "^2.0.2",
|
||||
"open": "^11.0.0",
|
||||
"puppeteer": "^22.0.0",
|
||||
"puppeteer-screen-recorder": "^3.0.0",
|
||||
"resend": "^6.5.2",
|
||||
"sqlite3": "^5.1.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"concurrently": "^9.2.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,580 @@
|
||||
/**
|
||||
* CaStAD Statistics Service v3.0.0
|
||||
* 고급 통계 및 분석 서비스
|
||||
*/
|
||||
|
||||
const db = require('./db');
|
||||
|
||||
/**
|
||||
* 일별 시스템 통계 스냅샷 생성/업데이트
|
||||
*/
|
||||
async function updateDailyStats() {
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
// 오늘의 통계 계산
|
||||
db.serialize(() => {
|
||||
// 전체 사용자 수
|
||||
db.get('SELECT COUNT(*) as total FROM users', [], (err, totalUsers) => {
|
||||
if (err) return reject(err);
|
||||
|
||||
// 오늘 신규 가입자
|
||||
db.get(`
|
||||
SELECT COUNT(*) as count FROM users
|
||||
WHERE date(createdAt) = date('now')
|
||||
`, [], (err, newUsers) => {
|
||||
if (err) return reject(err);
|
||||
|
||||
// 오늘 활성 사용자 (영상 생성)
|
||||
db.get(`
|
||||
SELECT COUNT(DISTINCT user_id) as count FROM history
|
||||
WHERE date(createdAt) = date('now')
|
||||
`, [], (err, activeUsers) => {
|
||||
if (err) return reject(err);
|
||||
|
||||
// 오늘 생성된 영상 수
|
||||
db.get(`
|
||||
SELECT COUNT(*) as count FROM history
|
||||
WHERE date(createdAt) = date('now')
|
||||
`, [], (err, videos) => {
|
||||
if (err) return reject(err);
|
||||
|
||||
// 오늘 전체 업로드 수 (YouTube + Instagram + TikTok)
|
||||
db.get(`
|
||||
SELECT
|
||||
(SELECT COUNT(*) FROM upload_history WHERE date(uploaded_at) = date('now')) +
|
||||
(SELECT COUNT(*) FROM instagram_upload_history WHERE date(createdAt) = date('now')) +
|
||||
(SELECT COUNT(*) FROM tiktok_upload_history WHERE date(createdAt) = date('now'))
|
||||
as total_uploads,
|
||||
(SELECT COUNT(*) FROM upload_history WHERE date(uploaded_at) = date('now')) as youtube,
|
||||
(SELECT COUNT(*) FROM instagram_upload_history WHERE date(createdAt) = date('now')) as instagram,
|
||||
(SELECT COUNT(*) FROM tiktok_upload_history WHERE date(createdAt) = date('now')) as tiktok
|
||||
`, [], (err, uploads) => {
|
||||
if (err) return reject(err);
|
||||
|
||||
// 오늘 사용된 크레딧
|
||||
db.get(`
|
||||
SELECT COALESCE(SUM(ABS(amount)), 0) as total FROM credit_history
|
||||
WHERE amount < 0 AND date(createdAt) = date('now')
|
||||
`, [], (err, credits) => {
|
||||
if (err) return reject(err);
|
||||
|
||||
// 저장 또는 업데이트
|
||||
db.run(`
|
||||
INSERT OR REPLACE INTO system_stats_daily
|
||||
(date, total_users, new_users, active_users, total_videos_generated,
|
||||
total_uploads, youtube_uploads, instagram_uploads, tiktok_uploads,
|
||||
total_credits_used, createdAt)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
|
||||
`, [
|
||||
today,
|
||||
totalUsers.total,
|
||||
newUsers.count,
|
||||
activeUsers.count,
|
||||
videos.count,
|
||||
uploads?.total_uploads || 0,
|
||||
uploads?.youtube || 0,
|
||||
uploads?.instagram || 0,
|
||||
uploads?.tiktok || 0,
|
||||
credits.total
|
||||
], function (err) {
|
||||
if (err) reject(err);
|
||||
else resolve({ success: true });
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자 성장 트렌드 조회
|
||||
* @param {number} days - 조회 기간 (일)
|
||||
*/
|
||||
function getUserGrowthTrend(days = 30) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.all(`
|
||||
SELECT
|
||||
date(createdAt) as date,
|
||||
COUNT(*) as new_users,
|
||||
SUM(COUNT(*)) OVER (ORDER BY date(createdAt)) as cumulative_users
|
||||
FROM users
|
||||
WHERE createdAt >= date('now', '-' || ? || ' days')
|
||||
GROUP BY date(createdAt)
|
||||
ORDER BY date ASC
|
||||
`, [days], (err, rows) => {
|
||||
if (err) reject(err);
|
||||
else resolve(rows || []);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 영상 생성 트렌드 조회
|
||||
* @param {number} days - 조회 기간 (일)
|
||||
*/
|
||||
function getVideoGenerationTrend(days = 30) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.all(`
|
||||
SELECT
|
||||
date(createdAt) as date,
|
||||
COUNT(*) as videos_generated,
|
||||
COUNT(DISTINCT user_id) as unique_users
|
||||
FROM history
|
||||
WHERE createdAt >= date('now', '-' || ? || ' days')
|
||||
GROUP BY date(createdAt)
|
||||
ORDER BY date ASC
|
||||
`, [days], (err, rows) => {
|
||||
if (err) reject(err);
|
||||
else resolve(rows || []);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 플랫폼별 업로드 통계
|
||||
* @param {number} days - 조회 기간 (일)
|
||||
*/
|
||||
function getPlatformUploadStats(days = 30) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const result = {
|
||||
youtube: [],
|
||||
instagram: [],
|
||||
tiktok: [],
|
||||
summary: {}
|
||||
};
|
||||
|
||||
db.all(`
|
||||
SELECT date(uploaded_at) as date, COUNT(*) as count, status
|
||||
FROM upload_history
|
||||
WHERE uploaded_at >= date('now', '-' || ? || ' days')
|
||||
GROUP BY date(uploaded_at), status
|
||||
ORDER BY date ASC
|
||||
`, [days], (err, youtubeRows) => {
|
||||
if (err) return reject(err);
|
||||
result.youtube = youtubeRows || [];
|
||||
|
||||
db.all(`
|
||||
SELECT date(createdAt) as date, COUNT(*) as count, status
|
||||
FROM instagram_upload_history
|
||||
WHERE createdAt >= date('now', '-' || ? || ' days')
|
||||
GROUP BY date(createdAt), status
|
||||
ORDER BY date ASC
|
||||
`, [days], (err, instaRows) => {
|
||||
if (err) return reject(err);
|
||||
result.instagram = instaRows || [];
|
||||
|
||||
db.all(`
|
||||
SELECT date(createdAt) as date, COUNT(*) as count, status
|
||||
FROM tiktok_upload_history
|
||||
WHERE createdAt >= date('now', '-' || ? || ' days')
|
||||
GROUP BY date(createdAt), status
|
||||
ORDER BY date ASC
|
||||
`, [days], (err, tiktokRows) => {
|
||||
if (err) return reject(err);
|
||||
result.tiktok = tiktokRows || [];
|
||||
|
||||
// 요약 통계 계산
|
||||
db.get(`
|
||||
SELECT
|
||||
(SELECT COUNT(*) FROM upload_history WHERE uploaded_at >= date('now', '-' || ? || ' days')) as youtube_total,
|
||||
(SELECT COUNT(*) FROM upload_history WHERE uploaded_at >= date('now', '-' || ? || ' days') AND status = 'completed') as youtube_success,
|
||||
(SELECT COUNT(*) FROM instagram_upload_history WHERE createdAt >= date('now', '-' || ? || ' days')) as instagram_total,
|
||||
(SELECT COUNT(*) FROM instagram_upload_history WHERE createdAt >= date('now', '-' || ? || ' days') AND status = 'completed') as instagram_success,
|
||||
(SELECT COUNT(*) FROM tiktok_upload_history WHERE createdAt >= date('now', '-' || ? || ' days')) as tiktok_total,
|
||||
(SELECT COUNT(*) FROM tiktok_upload_history WHERE createdAt >= date('now', '-' || ? || ' days') AND status = 'completed') as tiktok_success
|
||||
`, [days, days, days, days, days, days], (err, summary) => {
|
||||
if (err) return reject(err);
|
||||
result.summary = summary || {};
|
||||
resolve(result);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 크레딧 사용 통계
|
||||
* @param {number} days - 조회 기간 (일)
|
||||
*/
|
||||
function getCreditUsageStats(days = 30) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.all(`
|
||||
SELECT
|
||||
date(createdAt) as date,
|
||||
type,
|
||||
SUM(CASE WHEN amount > 0 THEN amount ELSE 0 END) as credits_added,
|
||||
SUM(CASE WHEN amount < 0 THEN ABS(amount) ELSE 0 END) as credits_used
|
||||
FROM credit_history
|
||||
WHERE createdAt >= date('now', '-' || ? || ' days')
|
||||
GROUP BY date(createdAt), type
|
||||
ORDER BY date ASC
|
||||
`, [days], (err, rows) => {
|
||||
if (err) reject(err);
|
||||
else resolve(rows || []);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 플랜별 사용자 분포
|
||||
*/
|
||||
function getPlanDistribution() {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.all(`
|
||||
SELECT
|
||||
COALESCE(plan_type, 'free') as plan,
|
||||
COUNT(*) as count,
|
||||
ROUND(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM users), 2) as percentage
|
||||
FROM users
|
||||
GROUP BY plan_type
|
||||
ORDER BY count DESC
|
||||
`, [], (err, rows) => {
|
||||
if (err) reject(err);
|
||||
else resolve(rows || []);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 톱 사용자 (가장 많은 영상 생성)
|
||||
* @param {number} limit - 조회 개수
|
||||
*/
|
||||
function getTopUsers(limit = 10) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.all(`
|
||||
SELECT
|
||||
u.id,
|
||||
u.username,
|
||||
u.name,
|
||||
u.plan_type,
|
||||
u.credits,
|
||||
COUNT(h.id) as total_videos,
|
||||
(SELECT COUNT(*) FROM upload_history WHERE user_id = u.id) as youtube_uploads,
|
||||
(SELECT COUNT(*) FROM instagram_upload_history WHERE user_id = u.id) as instagram_uploads,
|
||||
(SELECT COUNT(*) FROM tiktok_upload_history WHERE user_id = u.id) as tiktok_uploads,
|
||||
(SELECT COUNT(*) FROM pension_profiles WHERE user_id = u.id) as pension_count
|
||||
FROM users u
|
||||
LEFT JOIN history h ON u.id = h.user_id
|
||||
WHERE u.role != 'admin'
|
||||
GROUP BY u.id
|
||||
ORDER BY total_videos DESC
|
||||
LIMIT ?
|
||||
`, [limit], (err, rows) => {
|
||||
if (err) reject(err);
|
||||
else resolve(rows || []);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 최근 활동 로그
|
||||
* @param {number} limit - 조회 개수
|
||||
*/
|
||||
function getRecentActivityLogs(limit = 50) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.all(`
|
||||
SELECT
|
||||
al.*,
|
||||
u.username,
|
||||
u.name
|
||||
FROM activity_logs al
|
||||
LEFT JOIN users u ON al.user_id = u.id
|
||||
ORDER BY al.createdAt DESC
|
||||
LIMIT ?
|
||||
`, [limit], (err, rows) => {
|
||||
if (err) reject(err);
|
||||
else resolve(rows || []);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 활동 로그 기록
|
||||
* @param {number|null} userId - 사용자 ID
|
||||
* @param {string} actionType - 액션 타입
|
||||
* @param {string} actionDetail - 액션 상세
|
||||
* @param {object} metadata - 추가 메타데이터
|
||||
*/
|
||||
function logActivity(userId, actionType, actionDetail, metadata = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.run(`
|
||||
INSERT INTO activity_logs (user_id, action_type, action_detail, metadata, createdAt)
|
||||
VALUES (?, ?, ?, ?, datetime('now'))
|
||||
`, [userId, actionType, actionDetail, JSON.stringify(metadata)], function (err) {
|
||||
if (err) reject(err);
|
||||
else resolve({ id: this.lastID });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 대시보드 요약 통계
|
||||
*/
|
||||
function getDashboardSummary() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const summary = {};
|
||||
|
||||
db.serialize(() => {
|
||||
// 전체 사용자
|
||||
db.get('SELECT COUNT(*) as total FROM users WHERE role != ?', ['admin'], (err, row) => {
|
||||
if (err) return reject(err);
|
||||
summary.totalUsers = row.total;
|
||||
|
||||
// 오늘 신규 가입
|
||||
db.get(`
|
||||
SELECT COUNT(*) as count FROM users
|
||||
WHERE date(createdAt) = date('now') AND role != 'admin'
|
||||
`, [], (err, row) => {
|
||||
if (err) return reject(err);
|
||||
summary.newUsersToday = row.count;
|
||||
|
||||
// 이번 주 활성 사용자
|
||||
db.get(`
|
||||
SELECT COUNT(DISTINCT user_id) as count FROM history
|
||||
WHERE createdAt >= date('now', '-7 days')
|
||||
`, [], (err, row) => {
|
||||
if (err) return reject(err);
|
||||
summary.activeUsersWeek = row.count;
|
||||
|
||||
// 전체 생성 영상 수
|
||||
db.get('SELECT COUNT(*) as total FROM history', [], (err, row) => {
|
||||
if (err) return reject(err);
|
||||
summary.totalVideos = row.total;
|
||||
|
||||
// 오늘 생성 영상
|
||||
db.get(`
|
||||
SELECT COUNT(*) as count FROM history
|
||||
WHERE date(createdAt) = date('now')
|
||||
`, [], (err, row) => {
|
||||
if (err) return reject(err);
|
||||
summary.videosToday = row.count;
|
||||
|
||||
// 전체 업로드 수
|
||||
db.get(`
|
||||
SELECT
|
||||
(SELECT COUNT(*) FROM upload_history) +
|
||||
(SELECT COUNT(*) FROM instagram_upload_history) +
|
||||
(SELECT COUNT(*) FROM tiktok_upload_history) as total
|
||||
`, [], (err, row) => {
|
||||
if (err) return reject(err);
|
||||
summary.totalUploads = row.total;
|
||||
|
||||
// 플랫폼별 업로드
|
||||
db.get(`
|
||||
SELECT
|
||||
(SELECT COUNT(*) FROM upload_history) as youtube,
|
||||
(SELECT COUNT(*) FROM instagram_upload_history) as instagram,
|
||||
(SELECT COUNT(*) FROM tiktok_upload_history) as tiktok
|
||||
`, [], (err, row) => {
|
||||
if (err) return reject(err);
|
||||
summary.platformUploads = row;
|
||||
|
||||
// 전체 펜션 수
|
||||
db.get('SELECT COUNT(*) as total FROM pension_profiles', [], (err, row) => {
|
||||
if (err) return reject(err);
|
||||
summary.totalPensions = row.total;
|
||||
|
||||
// 대기중인 승인 요청
|
||||
db.get(`
|
||||
SELECT COUNT(*) as count FROM users
|
||||
WHERE approved = 0 AND role != 'admin'
|
||||
`, [], (err, row) => {
|
||||
if (err) return reject(err);
|
||||
summary.pendingApprovals = row.count;
|
||||
|
||||
// 대기중인 크레딧 요청
|
||||
db.get(`
|
||||
SELECT COUNT(*) as count FROM credit_requests
|
||||
WHERE status = 'pending'
|
||||
`, [], (err, row) => {
|
||||
if (err) return reject(err);
|
||||
summary.pendingCreditRequests = row.count;
|
||||
|
||||
// 전체 크레딧 발행량
|
||||
db.get(`
|
||||
SELECT
|
||||
COALESCE(SUM(CASE WHEN amount > 0 THEN amount ELSE 0 END), 0) as issued,
|
||||
COALESCE(SUM(CASE WHEN amount < 0 THEN ABS(amount) ELSE 0 END), 0) as used
|
||||
FROM credit_history
|
||||
`, [], (err, row) => {
|
||||
if (err) return reject(err);
|
||||
summary.credits = row;
|
||||
|
||||
resolve(summary);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 시간대별 사용 패턴 분석
|
||||
*/
|
||||
function getUsagePattern() {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.all(`
|
||||
SELECT
|
||||
strftime('%H', createdAt) as hour,
|
||||
COUNT(*) as count
|
||||
FROM history
|
||||
WHERE createdAt >= date('now', '-30 days')
|
||||
GROUP BY strftime('%H', createdAt)
|
||||
ORDER BY hour ASC
|
||||
`, [], (err, rows) => {
|
||||
if (err) reject(err);
|
||||
else resolve(rows || []);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 지역별 사용자 분포 (펜션 주소 기반)
|
||||
*/
|
||||
function getRegionalDistribution() {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.all(`
|
||||
SELECT
|
||||
COALESCE(region, '미설정') as region,
|
||||
COUNT(*) as count
|
||||
FROM pension_profiles
|
||||
GROUP BY region
|
||||
ORDER BY count DESC
|
||||
LIMIT 20
|
||||
`, [], (err, rows) => {
|
||||
if (err) reject(err);
|
||||
else resolve(rows || []);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 월별 수익 예측 (플랜 기반)
|
||||
*/
|
||||
function getRevenueProjection() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const PLAN_PRICES = {
|
||||
free: 0,
|
||||
basic: 29000,
|
||||
pro: 99000,
|
||||
business: 299000
|
||||
};
|
||||
|
||||
db.all(`
|
||||
SELECT
|
||||
COALESCE(plan_type, 'free') as plan,
|
||||
COUNT(*) as count
|
||||
FROM users
|
||||
WHERE role != 'admin'
|
||||
GROUP BY plan_type
|
||||
`, [], (err, rows) => {
|
||||
if (err) return reject(err);
|
||||
|
||||
let monthlyRevenue = 0;
|
||||
const breakdown = {};
|
||||
|
||||
(rows || []).forEach(row => {
|
||||
const price = PLAN_PRICES[row.plan] || 0;
|
||||
const revenue = price * row.count;
|
||||
monthlyRevenue += revenue;
|
||||
breakdown[row.plan] = {
|
||||
users: row.count,
|
||||
price,
|
||||
revenue
|
||||
};
|
||||
});
|
||||
|
||||
resolve({
|
||||
monthlyRevenue,
|
||||
annualProjection: monthlyRevenue * 12,
|
||||
breakdown
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 시스템 헬스 체크
|
||||
*/
|
||||
function getSystemHealth() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const health = {
|
||||
database: 'ok',
|
||||
diskUsage: null,
|
||||
lastVideoGenerated: null,
|
||||
uptime: process.uptime()
|
||||
};
|
||||
|
||||
// DB 연결 확인
|
||||
db.get('SELECT 1', [], (err) => {
|
||||
if (err) {
|
||||
health.database = 'error';
|
||||
}
|
||||
|
||||
// 마지막 영상 생성 시간
|
||||
db.get(`
|
||||
SELECT createdAt FROM history
|
||||
ORDER BY createdAt DESC LIMIT 1
|
||||
`, [], (err, row) => {
|
||||
if (!err && row) {
|
||||
health.lastVideoGenerated = row.createdAt;
|
||||
}
|
||||
|
||||
// 디스크 사용량 (downloads 폴더)
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const downloadsDir = path.join(__dirname, 'downloads');
|
||||
|
||||
try {
|
||||
let totalSize = 0;
|
||||
const files = fs.readdirSync(downloadsDir);
|
||||
files.forEach(file => {
|
||||
const filePath = path.join(downloadsDir, file);
|
||||
const stats = fs.statSync(filePath);
|
||||
totalSize += stats.size;
|
||||
});
|
||||
health.diskUsage = {
|
||||
bytes: totalSize,
|
||||
mb: Math.round(totalSize / 1024 / 1024),
|
||||
fileCount: files.length
|
||||
};
|
||||
} catch (e) {
|
||||
health.diskUsage = { error: e.message };
|
||||
}
|
||||
|
||||
resolve(health);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
updateDailyStats,
|
||||
getUserGrowthTrend,
|
||||
getVideoGenerationTrend,
|
||||
getPlatformUploadStats,
|
||||
getCreditUsageStats,
|
||||
getPlanDistribution,
|
||||
getTopUsers,
|
||||
getRecentActivityLogs,
|
||||
logActivity,
|
||||
getDashboardSummary,
|
||||
getUsagePattern,
|
||||
getRegionalDistribution,
|
||||
getRevenueProjection,
|
||||
getSystemHealth
|
||||
};
|
||||
Binary file not shown.
@@ -0,0 +1,606 @@
|
||||
/**
|
||||
* TikTok Content Posting API Service
|
||||
* CaStAD v3.0.0
|
||||
*
|
||||
* TikTok API Reference: https://developers.tiktok.com/doc/content-posting-api-get-started/
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const axios = require('axios');
|
||||
const db = require('./db');
|
||||
|
||||
// TikTok API Endpoints
|
||||
const TIKTOK_AUTH_URL = 'https://www.tiktok.com/v2/auth/authorize/';
|
||||
const TIKTOK_TOKEN_URL = 'https://open.tiktokapis.com/v2/oauth/token/';
|
||||
const TIKTOK_REVOKE_URL = 'https://open.tiktokapis.com/v2/oauth/revoke/';
|
||||
const TIKTOK_USER_INFO_URL = 'https://open.tiktokapis.com/v2/user/info/';
|
||||
const TIKTOK_UPLOAD_INIT_URL = 'https://open.tiktokapis.com/v2/post/publish/video/init/';
|
||||
const TIKTOK_UPLOAD_INBOX_URL = 'https://open.tiktokapis.com/v2/post/publish/inbox/video/init/';
|
||||
const TIKTOK_PUBLISH_STATUS_URL = 'https://open.tiktokapis.com/v2/post/publish/status/fetch/';
|
||||
|
||||
// Scopes
|
||||
const TIKTOK_SCOPES = [
|
||||
'user.info.basic',
|
||||
'user.info.profile',
|
||||
'user.info.stats',
|
||||
'video.publish',
|
||||
'video.upload'
|
||||
];
|
||||
|
||||
// TikTok Client credentials (from environment or config)
|
||||
const TIKTOK_CLIENT_KEY = process.env.TIKTOK_CLIENT_KEY;
|
||||
const TIKTOK_CLIENT_SECRET = process.env.TIKTOK_CLIENT_SECRET;
|
||||
|
||||
/**
|
||||
* TikTok OAuth 인증 URL 생성
|
||||
* @param {number} userId - 사용자 ID
|
||||
* @param {string} redirectUri - 콜백 URI
|
||||
*/
|
||||
function generateAuthUrl(userId, redirectUri = null) {
|
||||
if (!TIKTOK_CLIENT_KEY) {
|
||||
throw new Error('TIKTOK_CLIENT_KEY 환경변수가 설정되지 않았습니다.');
|
||||
}
|
||||
|
||||
const finalRedirectUri = redirectUri || `${process.env.BACKEND_URL || 'http://localhost:3001'}/api/tiktok/oauth/callback`;
|
||||
|
||||
const params = new URLSearchParams({
|
||||
client_key: TIKTOK_CLIENT_KEY,
|
||||
scope: TIKTOK_SCOPES.join(','),
|
||||
response_type: 'code',
|
||||
redirect_uri: finalRedirectUri,
|
||||
state: JSON.stringify({ userId })
|
||||
});
|
||||
|
||||
return `${TIKTOK_AUTH_URL}?${params.toString()}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 인증 코드로 토큰 교환
|
||||
* @param {string} code - 인증 코드
|
||||
* @param {number} userId - 사용자 ID
|
||||
* @param {string} redirectUri - 콜백 URI
|
||||
*/
|
||||
async function exchangeCodeForTokens(code, userId, redirectUri = null) {
|
||||
if (!TIKTOK_CLIENT_KEY || !TIKTOK_CLIENT_SECRET) {
|
||||
throw new Error('TikTok 클라이언트 자격증명이 설정되지 않았습니다.');
|
||||
}
|
||||
|
||||
const finalRedirectUri = redirectUri || `${process.env.BACKEND_URL || 'http://localhost:3001'}/api/tiktok/oauth/callback`;
|
||||
|
||||
try {
|
||||
// 토큰 요청
|
||||
const tokenResponse = await axios.post(TIKTOK_TOKEN_URL, null, {
|
||||
params: {
|
||||
client_key: TIKTOK_CLIENT_KEY,
|
||||
client_secret: TIKTOK_CLIENT_SECRET,
|
||||
code,
|
||||
grant_type: 'authorization_code',
|
||||
redirect_uri: finalRedirectUri
|
||||
}
|
||||
});
|
||||
|
||||
const tokens = tokenResponse.data;
|
||||
|
||||
if (tokens.error) {
|
||||
throw new Error(tokens.error.message || 'Token exchange failed');
|
||||
}
|
||||
|
||||
const accessToken = tokens.access_token;
|
||||
const refreshToken = tokens.refresh_token;
|
||||
const expiresIn = tokens.expires_in;
|
||||
const openId = tokens.open_id;
|
||||
const tokenExpiry = new Date(Date.now() + expiresIn * 1000).toISOString();
|
||||
|
||||
// 사용자 정보 가져오기
|
||||
const userInfo = await getTikTokUserInfo(accessToken, openId);
|
||||
|
||||
// DB에 저장
|
||||
return new Promise((resolve, reject) => {
|
||||
db.run(`
|
||||
INSERT OR REPLACE INTO tiktok_connections
|
||||
(user_id, open_id, display_name, avatar_url, follower_count, following_count,
|
||||
access_token, refresh_token, token_expiry, scopes, connected_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
|
||||
`, [
|
||||
userId,
|
||||
openId,
|
||||
userInfo.display_name || null,
|
||||
userInfo.avatar_url || null,
|
||||
userInfo.follower_count || 0,
|
||||
userInfo.following_count || 0,
|
||||
accessToken,
|
||||
refreshToken,
|
||||
tokenExpiry,
|
||||
TIKTOK_SCOPES.join(',')
|
||||
], function (err) {
|
||||
if (err) {
|
||||
console.error('[TikTok OAuth] 토큰 저장 실패:', err);
|
||||
reject(err);
|
||||
} else {
|
||||
// 기본 설정 생성
|
||||
db.run(`INSERT OR IGNORE INTO tiktok_settings (user_id) VALUES (?)`, [userId]);
|
||||
|
||||
resolve({
|
||||
success: true,
|
||||
openId,
|
||||
displayName: userInfo.display_name,
|
||||
avatarUrl: userInfo.avatar_url,
|
||||
followerCount: userInfo.follower_count
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('[TikTok OAuth] 토큰 교환 실패:', error.response?.data || error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* TikTok 사용자 정보 조회
|
||||
* @param {string} accessToken - 액세스 토큰
|
||||
* @param {string} openId - TikTok Open ID
|
||||
*/
|
||||
async function getTikTokUserInfo(accessToken, openId) {
|
||||
try {
|
||||
const response = await axios.get(TIKTOK_USER_INFO_URL, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`
|
||||
},
|
||||
params: {
|
||||
fields: 'open_id,display_name,avatar_url,follower_count,following_count,bio_description'
|
||||
}
|
||||
});
|
||||
|
||||
return response.data.data?.user || {};
|
||||
} catch (error) {
|
||||
console.error('[TikTok] 사용자 정보 조회 실패:', error.response?.data || error.message);
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 토큰 갱신
|
||||
* @param {string} refreshToken - 리프레시 토큰
|
||||
*/
|
||||
async function refreshAccessToken(refreshToken) {
|
||||
try {
|
||||
const response = await axios.post(TIKTOK_TOKEN_URL, null, {
|
||||
params: {
|
||||
client_key: TIKTOK_CLIENT_KEY,
|
||||
client_secret: TIKTOK_CLIENT_SECRET,
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: refreshToken
|
||||
}
|
||||
});
|
||||
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error('[TikTok] 토큰 갱신 실패:', error.response?.data || error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자별 인증된 클라이언트 정보 가져오기
|
||||
* @param {number} userId - 사용자 ID
|
||||
*/
|
||||
async function getAuthenticatedCredentials(userId) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.get(`SELECT * FROM tiktok_connections WHERE user_id = ?`, [userId], async (err, row) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!row) {
|
||||
reject(new Error('TikTok 계정이 연결되지 않았습니다. 설정에서 계정을 연결해주세요.'));
|
||||
return;
|
||||
}
|
||||
|
||||
// 토큰 만료 체크
|
||||
const tokenExpiry = new Date(row.token_expiry);
|
||||
const now = new Date();
|
||||
|
||||
if (tokenExpiry <= now) {
|
||||
// 토큰 갱신 시도
|
||||
try {
|
||||
const newTokens = await refreshAccessToken(row.refresh_token);
|
||||
|
||||
const newExpiry = new Date(Date.now() + newTokens.expires_in * 1000).toISOString();
|
||||
|
||||
// DB 업데이트
|
||||
db.run(`
|
||||
UPDATE tiktok_connections
|
||||
SET access_token = ?, refresh_token = ?, token_expiry = ?
|
||||
WHERE user_id = ?
|
||||
`, [newTokens.access_token, newTokens.refresh_token, newExpiry, userId]);
|
||||
|
||||
resolve({
|
||||
accessToken: newTokens.access_token,
|
||||
openId: row.open_id,
|
||||
displayName: row.display_name
|
||||
});
|
||||
} catch (refreshError) {
|
||||
console.error('[TikTok] 토큰 갱신 실패:', refreshError);
|
||||
// 연결 해제
|
||||
db.run(`DELETE FROM tiktok_connections WHERE user_id = ?`, [userId]);
|
||||
reject(new Error('TikTok 인증이 만료되었습니다. 다시 연결해주세요.'));
|
||||
}
|
||||
} else {
|
||||
resolve({
|
||||
accessToken: row.access_token,
|
||||
openId: row.open_id,
|
||||
displayName: row.display_name
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자의 TikTok 연결 상태 확인
|
||||
*/
|
||||
function getConnectionStatus(userId) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.get(`
|
||||
SELECT open_id, display_name, avatar_url, follower_count, following_count, connected_at
|
||||
FROM tiktok_connections WHERE user_id = ?
|
||||
`, [userId], (err, row) => {
|
||||
if (err) reject(err);
|
||||
else resolve(row || null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* TikTok 연결 해제
|
||||
*/
|
||||
async function disconnectTikTok(userId) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.get(`SELECT access_token FROM tiktok_connections WHERE user_id = ?`, [userId], async (err, row) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
|
||||
// 토큰 폐기 시도
|
||||
if (row?.access_token) {
|
||||
try {
|
||||
await axios.post(TIKTOK_REVOKE_URL, null, {
|
||||
params: {
|
||||
client_key: TIKTOK_CLIENT_KEY,
|
||||
client_secret: TIKTOK_CLIENT_SECRET,
|
||||
token: row.access_token
|
||||
}
|
||||
});
|
||||
} catch (revokeError) {
|
||||
console.error('[TikTok] 토큰 폐기 실패 (무시):', revokeError.message);
|
||||
}
|
||||
}
|
||||
|
||||
// DB에서 삭제
|
||||
db.run(`DELETE FROM tiktok_connections WHERE user_id = ?`, [userId], function (delErr) {
|
||||
if (delErr) reject(delErr);
|
||||
else resolve({ success: true, deleted: this.changes });
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 비디오 업로드 (Direct Post)
|
||||
* @param {number} userId - 사용자 ID
|
||||
* @param {string} videoPath - 비디오 파일 경로
|
||||
* @param {object} metadata - 메타데이터 (title, description, etc.)
|
||||
* @param {object} options - 업로드 옵션
|
||||
*/
|
||||
async function uploadVideo(userId, videoPath, metadata, options = {}) {
|
||||
try {
|
||||
const credentials = await getAuthenticatedCredentials(userId);
|
||||
const fileSize = fs.statSync(videoPath).size;
|
||||
|
||||
// Step 1: Initialize upload
|
||||
const initResponse = await axios.post(
|
||||
TIKTOK_UPLOAD_INIT_URL,
|
||||
{
|
||||
post_info: {
|
||||
title: (metadata.title || 'CaStAD Video').substring(0, 150),
|
||||
privacy_level: options.privacyLevel || 'SELF_ONLY', // SELF_ONLY, MUTUAL_FOLLOW_FRIENDS, FOLLOWER_OF_CREATOR, PUBLIC_TO_EVERYONE
|
||||
disable_duet: options.disableDuet || false,
|
||||
disable_comment: options.disableComment || false,
|
||||
disable_stitch: options.disableStitch || false,
|
||||
video_cover_timestamp_ms: options.coverTimestamp || 1000
|
||||
},
|
||||
source_info: {
|
||||
source: 'FILE_UPLOAD',
|
||||
video_size: fileSize,
|
||||
chunk_size: Math.min(fileSize, 10 * 1024 * 1024), // 10MB chunks
|
||||
total_chunk_count: Math.ceil(fileSize / (10 * 1024 * 1024))
|
||||
}
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Authorization': `Bearer ${credentials.accessToken}`,
|
||||
'Content-Type': 'application/json; charset=UTF-8'
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
if (initResponse.data.error?.code) {
|
||||
throw new Error(initResponse.data.error.message || 'Upload initialization failed');
|
||||
}
|
||||
|
||||
const uploadUrl = initResponse.data.data?.upload_url;
|
||||
const publishId = initResponse.data.data?.publish_id;
|
||||
|
||||
if (!uploadUrl) {
|
||||
throw new Error('Upload URL not received from TikTok');
|
||||
}
|
||||
|
||||
// Step 2: Upload video file in chunks
|
||||
const chunkSize = 10 * 1024 * 1024; // 10MB
|
||||
const totalChunks = Math.ceil(fileSize / chunkSize);
|
||||
const fileStream = fs.createReadStream(videoPath);
|
||||
|
||||
let uploadedBytes = 0;
|
||||
let chunkIndex = 0;
|
||||
|
||||
for await (const chunk of fileStream) {
|
||||
const start = uploadedBytes;
|
||||
const end = Math.min(uploadedBytes + chunk.length - 1, fileSize - 1);
|
||||
|
||||
await axios.put(uploadUrl, chunk, {
|
||||
headers: {
|
||||
'Content-Type': 'video/mp4',
|
||||
'Content-Length': chunk.length,
|
||||
'Content-Range': `bytes ${start}-${end}/${fileSize}`
|
||||
}
|
||||
});
|
||||
|
||||
uploadedBytes += chunk.length;
|
||||
chunkIndex++;
|
||||
|
||||
if (options.onProgress) {
|
||||
options.onProgress((uploadedBytes / fileSize) * 100);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[TikTok] 업로드 완료! Publish ID: ${publishId}`);
|
||||
|
||||
// Step 3: Check publish status
|
||||
const status = await checkPublishStatus(credentials.accessToken, publishId);
|
||||
|
||||
// 업로드 히스토리 저장
|
||||
db.run(`
|
||||
INSERT INTO tiktok_upload_history
|
||||
(user_id, history_id, publish_id, title, privacy_level, status, uploaded_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, datetime('now'))
|
||||
`, [userId, options.historyId || null, publishId, metadata.title, options.privacyLevel || 'SELF_ONLY', status.status]);
|
||||
|
||||
return {
|
||||
publishId,
|
||||
status: status.status,
|
||||
videoId: status.video_id
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
console.error('[TikTok] 업로드 오류:', error.response?.data || error.message);
|
||||
|
||||
// 에러 기록
|
||||
db.run(`
|
||||
INSERT INTO tiktok_upload_history
|
||||
(user_id, history_id, status, error_message, uploaded_at)
|
||||
VALUES (?, ?, 'failed', ?, datetime('now'))
|
||||
`, [userId, options.historyId || null, error.message]);
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 비디오 업로드 (Inbox/Draft 방식)
|
||||
* @param {number} userId - 사용자 ID
|
||||
* @param {string} videoPath - 비디오 파일 경로
|
||||
* @param {object} metadata - 메타데이터
|
||||
* @param {object} options - 업로드 옵션
|
||||
*/
|
||||
async function uploadVideoToInbox(userId, videoPath, metadata, options = {}) {
|
||||
try {
|
||||
const credentials = await getAuthenticatedCredentials(userId);
|
||||
const fileSize = fs.statSync(videoPath).size;
|
||||
|
||||
// Initialize inbox upload
|
||||
const initResponse = await axios.post(
|
||||
TIKTOK_UPLOAD_INBOX_URL,
|
||||
{
|
||||
source_info: {
|
||||
source: 'FILE_UPLOAD',
|
||||
video_size: fileSize,
|
||||
chunk_size: Math.min(fileSize, 10 * 1024 * 1024),
|
||||
total_chunk_count: Math.ceil(fileSize / (10 * 1024 * 1024))
|
||||
}
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Authorization': `Bearer ${credentials.accessToken}`,
|
||||
'Content-Type': 'application/json; charset=UTF-8'
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
if (initResponse.data.error?.code) {
|
||||
throw new Error(initResponse.data.error.message || 'Inbox upload initialization failed');
|
||||
}
|
||||
|
||||
const uploadUrl = initResponse.data.data?.upload_url;
|
||||
const publishId = initResponse.data.data?.publish_id;
|
||||
|
||||
// Upload file
|
||||
const fileBuffer = fs.readFileSync(videoPath);
|
||||
await axios.put(uploadUrl, fileBuffer, {
|
||||
headers: {
|
||||
'Content-Type': 'video/mp4',
|
||||
'Content-Length': fileSize,
|
||||
'Content-Range': `bytes 0-${fileSize - 1}/${fileSize}`
|
||||
}
|
||||
});
|
||||
|
||||
console.log(`[TikTok] Inbox 업로드 완료! Publish ID: ${publishId}`);
|
||||
|
||||
return {
|
||||
publishId,
|
||||
status: 'uploaded_to_inbox',
|
||||
message: 'TikTok 앱에서 영상을 확인하고 게시해주세요.'
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
console.error('[TikTok] Inbox 업로드 오류:', error.response?.data || error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시 상태 확인
|
||||
* @param {string} accessToken - 액세스 토큰
|
||||
* @param {string} publishId - 게시 ID
|
||||
*/
|
||||
async function checkPublishStatus(accessToken, publishId) {
|
||||
try {
|
||||
const response = await axios.post(
|
||||
TIKTOK_PUBLISH_STATUS_URL,
|
||||
{ publish_id: publishId },
|
||||
{
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return response.data.data || { status: 'unknown' };
|
||||
} catch (error) {
|
||||
console.error('[TikTok] 상태 확인 오류:', error.response?.data || error.message);
|
||||
return { status: 'unknown', error: error.message };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자 TikTok 설정 조회
|
||||
*/
|
||||
function getUserTikTokSettings(userId) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.get(`SELECT * FROM tiktok_settings WHERE user_id = ?`, [userId], (err, row) => {
|
||||
if (err) reject(err);
|
||||
else resolve(row || {
|
||||
default_privacy: 'SELF_ONLY',
|
||||
disable_duet: 0,
|
||||
disable_comment: 0,
|
||||
disable_stitch: 0,
|
||||
auto_upload: 0,
|
||||
upload_to_inbox: 1
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자 TikTok 설정 업데이트
|
||||
*/
|
||||
function updateUserTikTokSettings(userId, settings) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const fields = [];
|
||||
const values = [];
|
||||
|
||||
const allowedFields = [
|
||||
'default_privacy', 'disable_duet', 'disable_comment',
|
||||
'disable_stitch', 'auto_upload', 'upload_to_inbox', 'default_hashtags'
|
||||
];
|
||||
|
||||
for (const field of allowedFields) {
|
||||
if (settings[field] !== undefined) {
|
||||
fields.push(`${field} = ?`);
|
||||
values.push(settings[field]);
|
||||
}
|
||||
}
|
||||
|
||||
if (fields.length === 0) {
|
||||
resolve({ success: true });
|
||||
return;
|
||||
}
|
||||
|
||||
values.push(userId);
|
||||
|
||||
db.run(`
|
||||
UPDATE tiktok_settings SET ${fields.join(', ')}, updated_at = datetime('now')
|
||||
WHERE user_id = ?
|
||||
`, values, function (err) {
|
||||
if (err) {
|
||||
// INSERT 시도
|
||||
db.run(`
|
||||
INSERT INTO tiktok_settings (user_id, ${fields.map(f => f.split(' = ')[0]).join(', ')})
|
||||
VALUES (?, ${fields.map(() => '?').join(', ')})
|
||||
`, [userId, ...values.slice(0, -1)], function (err2) {
|
||||
if (err2) reject(err2);
|
||||
else resolve({ success: true });
|
||||
});
|
||||
} else {
|
||||
resolve({ success: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 업로드 히스토리 조회
|
||||
*/
|
||||
function getUploadHistory(userId, limit = 20) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.all(`
|
||||
SELECT * FROM tiktok_upload_history
|
||||
WHERE user_id = ?
|
||||
ORDER BY uploaded_at DESC
|
||||
LIMIT ?
|
||||
`, [userId, limit], (err, rows) => {
|
||||
if (err) reject(err);
|
||||
else resolve(rows || []);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* TikTok 통계 조회 (사용자별)
|
||||
*/
|
||||
function getTikTokStats(userId) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.get(`
|
||||
SELECT
|
||||
COUNT(*) as total_uploads,
|
||||
SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as successful_uploads,
|
||||
SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed_uploads
|
||||
FROM tiktok_upload_history
|
||||
WHERE user_id = ?
|
||||
`, [userId], (err, row) => {
|
||||
if (err) reject(err);
|
||||
else resolve(row || { total_uploads: 0, successful_uploads: 0, failed_uploads: 0 });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
generateAuthUrl,
|
||||
exchangeCodeForTokens,
|
||||
getAuthenticatedCredentials,
|
||||
getConnectionStatus,
|
||||
disconnectTikTok,
|
||||
uploadVideo,
|
||||
uploadVideoToInbox,
|
||||
checkPublishStatus,
|
||||
getUserTikTokSettings,
|
||||
updateUserTikTokSettings,
|
||||
getUploadHistory,
|
||||
getTikTokStats,
|
||||
TIKTOK_SCOPES
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
{"access_token":"ya29.a0ATi6K2v63SXXTZsXQhStk2KUONtfIy0UAEfNGJVezoesFeezqHiLneS1DGEK03Zi_OH5xweYQUE2QLtTLzlhhKz1k5Qjc6I67UJ03JFymrBYSFLQuSgEDP_3eAWCAXTWZaAEm3s7PJafWExpvxmtxJuWgZinqMyGdJ6QPh3rEkLf3lRODuNlv9cLAnGEJ6HLwNoh4mIaCgYKAf0SARYSFQHGX2Mi9Syyrl8EnOnXfBynBDZ80A0206","refresh_token":"1//0e1hhg4utFxpwCgYIARAAGA4SNwF-L9IrW2g5xFxohoak303VFYDgWck8r_Le3IZRSAvDC6ieFlRPIf-Trn-f2YNTMdoCAKtaFhI","scope":"https://www.googleapis.com/auth/youtube.upload","token_type":"Bearer","refresh_token_expires_in":604799,"expiry_date":1764463744341}
|
||||
@@ -0,0 +1,610 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { google } = require('googleapis');
|
||||
const db = require('./db');
|
||||
|
||||
// 클라이언트 시크릿 파일 (Google Cloud Console에서 다운로드)
|
||||
const CREDENTIALS_PATH = path.join(__dirname, 'client_secret.json');
|
||||
|
||||
const SCOPES = [
|
||||
'https://www.googleapis.com/auth/youtube.upload',
|
||||
'https://www.googleapis.com/auth/youtube',
|
||||
'https://www.googleapis.com/auth/youtube.readonly',
|
||||
'https://www.googleapis.com/auth/userinfo.email',
|
||||
'https://www.googleapis.com/auth/userinfo.profile'
|
||||
];
|
||||
|
||||
/**
|
||||
* Google OAuth2 클라이언트 생성
|
||||
* @param {string} redirectUri - 콜백 URI
|
||||
*/
|
||||
function createOAuth2Client(redirectUri = null) {
|
||||
if (!fs.existsSync(CREDENTIALS_PATH)) {
|
||||
throw new Error("client_secret.json 파일이 없습니다. Google Cloud Console에서 다운로드하여 server 폴더에 넣어주세요.");
|
||||
}
|
||||
|
||||
const content = fs.readFileSync(CREDENTIALS_PATH, 'utf-8');
|
||||
const credentials = JSON.parse(content);
|
||||
const { client_secret, client_id, redirect_uris } = credentials.installed || credentials.web;
|
||||
|
||||
const finalRedirectUri = redirectUri || redirect_uris[0] || 'http://localhost:3001/api/youtube/oauth/callback';
|
||||
|
||||
return new google.auth.OAuth2(client_id, client_secret, finalRedirectUri);
|
||||
}
|
||||
|
||||
/**
|
||||
* OAuth 인증 URL 생성
|
||||
* @param {number} userId - 사용자 ID (state 파라미터로 전달)
|
||||
* @param {string} redirectUri - 콜백 URI
|
||||
*/
|
||||
function generateAuthUrl(userId, redirectUri = null) {
|
||||
const oAuth2Client = createOAuth2Client(redirectUri);
|
||||
|
||||
const authUrl = oAuth2Client.generateAuthUrl({
|
||||
access_type: 'offline',
|
||||
scope: SCOPES,
|
||||
prompt: 'consent', // 항상 refresh_token 받기 위해
|
||||
state: JSON.stringify({ userId }) // 콜백에서 사용자 식별용
|
||||
});
|
||||
|
||||
return authUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* 인증 코드로 토큰 교환 및 저장
|
||||
* @param {string} code - 인증 코드
|
||||
* @param {number} userId - 사용자 ID
|
||||
* @param {string} redirectUri - 콜백 URI
|
||||
*/
|
||||
async function exchangeCodeForTokens(code, userId, redirectUri = null) {
|
||||
const oAuth2Client = createOAuth2Client(redirectUri);
|
||||
|
||||
try {
|
||||
const { tokens } = await oAuth2Client.getToken(code);
|
||||
oAuth2Client.setCredentials(tokens);
|
||||
|
||||
// 사용자 정보 가져오기
|
||||
const oauth2 = google.oauth2({ version: 'v2', auth: oAuth2Client });
|
||||
const userInfo = await oauth2.userinfo.get();
|
||||
|
||||
// YouTube 채널 정보 가져오기
|
||||
const youtube = google.youtube({ version: 'v3', auth: oAuth2Client });
|
||||
const channelRes = await youtube.channels.list({
|
||||
part: 'snippet',
|
||||
mine: true
|
||||
});
|
||||
|
||||
const channel = channelRes.data.items?.[0];
|
||||
|
||||
// DB에 저장
|
||||
const tokenExpiry = tokens.expiry_date ? new Date(tokens.expiry_date).toISOString() : null;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
db.run(`
|
||||
INSERT OR REPLACE INTO youtube_connections
|
||||
(user_id, google_user_id, google_email, youtube_channel_id, youtube_channel_title,
|
||||
access_token, refresh_token, token_expiry, scopes, connected_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
|
||||
`, [
|
||||
userId,
|
||||
userInfo.data.id,
|
||||
userInfo.data.email,
|
||||
channel?.id || null,
|
||||
channel?.snippet?.title || null,
|
||||
tokens.access_token,
|
||||
tokens.refresh_token,
|
||||
tokenExpiry,
|
||||
SCOPES.join(',')
|
||||
], function(err) {
|
||||
if (err) {
|
||||
console.error('[YouTube OAuth] 토큰 저장 실패:', err);
|
||||
reject(err);
|
||||
} else {
|
||||
// 기본 설정도 생성
|
||||
db.run(`
|
||||
INSERT OR IGNORE INTO youtube_settings (user_id) VALUES (?)
|
||||
`, [userId]);
|
||||
|
||||
resolve({
|
||||
success: true,
|
||||
channelId: channel?.id,
|
||||
channelTitle: channel?.snippet?.title,
|
||||
email: userInfo.data.email
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('[YouTube OAuth] 토큰 교환 실패:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자별 인증된 클라이언트 가져오기
|
||||
* @param {number} userId - 사용자 ID
|
||||
*/
|
||||
async function getAuthenticatedClientForUser(userId) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.get(`
|
||||
SELECT * FROM youtube_connections WHERE user_id = ?
|
||||
`, [userId], async (err, row) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!row) {
|
||||
reject(new Error('YouTube 채널이 연결되지 않았습니다. 설정에서 채널을 연결해주세요.'));
|
||||
return;
|
||||
}
|
||||
|
||||
const oAuth2Client = createOAuth2Client();
|
||||
oAuth2Client.setCredentials({
|
||||
access_token: row.access_token,
|
||||
refresh_token: row.refresh_token,
|
||||
expiry_date: row.token_expiry ? new Date(row.token_expiry).getTime() : null
|
||||
});
|
||||
|
||||
// 토큰 만료 체크 및 갱신
|
||||
try {
|
||||
const tokenInfo = await oAuth2Client.getAccessToken();
|
||||
|
||||
// 새 토큰으로 갱신되었으면 DB 업데이트
|
||||
if (tokenInfo.token !== row.access_token) {
|
||||
const credentials = oAuth2Client.credentials;
|
||||
db.run(`
|
||||
UPDATE youtube_connections
|
||||
SET access_token = ?, token_expiry = ?
|
||||
WHERE user_id = ?
|
||||
`, [
|
||||
credentials.access_token,
|
||||
credentials.expiry_date ? new Date(credentials.expiry_date).toISOString() : null,
|
||||
userId
|
||||
]);
|
||||
}
|
||||
|
||||
resolve(oAuth2Client);
|
||||
} catch (refreshError) {
|
||||
console.error('[YouTube] 토큰 갱신 실패:', refreshError);
|
||||
// 연결 해제 처리
|
||||
db.run(`DELETE FROM youtube_connections WHERE user_id = ?`, [userId]);
|
||||
reject(new Error('YouTube 인증이 만료되었습니다. 다시 연결해주세요.'));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자의 YouTube 연결 상태 확인
|
||||
*/
|
||||
function getConnectionStatus(userId) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.get(`
|
||||
SELECT youtube_channel_id, youtube_channel_title, google_email, connected_at
|
||||
FROM youtube_connections WHERE user_id = ?
|
||||
`, [userId], (err, row) => {
|
||||
if (err) reject(err);
|
||||
else resolve(row || null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* YouTube 연결 해제
|
||||
*/
|
||||
function disconnectYouTube(userId) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.run(`DELETE FROM youtube_connections WHERE user_id = ?`, [userId], function(err) {
|
||||
if (err) reject(err);
|
||||
else resolve({ success: true, deleted: this.changes });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자별 비디오 업로드
|
||||
* @param {number} userId - 사용자 ID
|
||||
* @param {string} videoPath - 비디오 파일 경로
|
||||
* @param {object} seoData - SEO 메타데이터
|
||||
* @param {object} options - 업로드 옵션
|
||||
*/
|
||||
async function uploadVideoForUser(userId, videoPath, seoData, options = {}) {
|
||||
try {
|
||||
const auth = await getAuthenticatedClientForUser(userId);
|
||||
const youtube = google.youtube({ version: 'v3', auth });
|
||||
|
||||
// 사용자 설정 가져오기
|
||||
const settings = await getUserYouTubeSettings(userId);
|
||||
|
||||
const fileSize = fs.statSync(videoPath).size;
|
||||
|
||||
// SEO 데이터 + 기본 설정 병합
|
||||
const title = (seoData.title || 'CastAD 생성 영상').substring(0, 100);
|
||||
const description = (seoData.description || '').substring(0, 5000);
|
||||
const tags = [...(seoData.tags || []), ...(settings.default_tags ? JSON.parse(settings.default_tags) : [])];
|
||||
const categoryId = options.categoryId || settings.default_category_id || '19';
|
||||
const privacyStatus = options.privacyStatus || settings.default_privacy || 'private';
|
||||
|
||||
const res = await youtube.videos.insert({
|
||||
part: 'snippet,status',
|
||||
requestBody: {
|
||||
snippet: {
|
||||
title,
|
||||
description,
|
||||
tags: tags.slice(0, 500), // YouTube 태그 제한
|
||||
categoryId,
|
||||
},
|
||||
status: {
|
||||
privacyStatus,
|
||||
selfDeclaredMadeForKids: false,
|
||||
},
|
||||
},
|
||||
media: {
|
||||
body: fs.createReadStream(videoPath),
|
||||
},
|
||||
}, {
|
||||
onUploadProgress: evt => {
|
||||
const progress = (evt.bytesRead / fileSize) * 100;
|
||||
if (options.onProgress) options.onProgress(progress);
|
||||
},
|
||||
});
|
||||
|
||||
const videoId = res.data.id;
|
||||
const youtubeUrl = `https://youtu.be/${videoId}`;
|
||||
|
||||
console.log(`[YouTube] 업로드 성공! ${youtubeUrl}`);
|
||||
|
||||
// 플레이리스트에 추가
|
||||
const playlistId = options.playlistId || settings.default_playlist_id;
|
||||
if (playlistId) {
|
||||
try {
|
||||
await addVideoToPlaylist(youtube, playlistId, videoId);
|
||||
console.log(`[YouTube] 플레이리스트(${playlistId})에 추가 완료`);
|
||||
} catch (playlistError) {
|
||||
console.error('[YouTube] 플레이리스트 추가 실패:', playlistError.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 고정 댓글 달기
|
||||
if (seoData.pinnedComment) {
|
||||
try {
|
||||
await postPinnedComment(youtube, videoId, seoData.pinnedComment);
|
||||
console.log('[YouTube] 고정 댓글 추가 완료');
|
||||
} catch (commentError) {
|
||||
console.error('[YouTube] 고정 댓글 실패:', commentError.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 업로드 히스토리 저장
|
||||
db.run(`
|
||||
INSERT INTO upload_history
|
||||
(user_id, history_id, youtube_video_id, youtube_url, title, privacy_status, playlist_id, status)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 'completed')
|
||||
`, [userId, options.historyId || null, videoId, youtubeUrl, title, privacyStatus, playlistId]);
|
||||
|
||||
return { videoId, url: youtubeUrl };
|
||||
|
||||
} catch (error) {
|
||||
console.error('[YouTube] 업로드 오류:', error.message);
|
||||
|
||||
// 에러 기록
|
||||
db.run(`
|
||||
INSERT INTO upload_history
|
||||
(user_id, history_id, status, error_message)
|
||||
VALUES (?, ?, 'failed', ?)
|
||||
`, [userId, options.historyId || null, error.message]);
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 고정 댓글 달기
|
||||
*/
|
||||
async function postPinnedComment(youtube, videoId, commentText) {
|
||||
const res = await youtube.commentThreads.insert({
|
||||
part: 'snippet',
|
||||
requestBody: {
|
||||
snippet: {
|
||||
videoId,
|
||||
topLevelComment: {
|
||||
snippet: {
|
||||
textOriginal: commentText
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 댓글 고정 (채널 소유자만 가능)
|
||||
// Note: YouTube API에서 직접 고정은 지원하지 않음, 수동으로 해야 함
|
||||
return res.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 플레이리스트에 비디오 추가
|
||||
*/
|
||||
async function addVideoToPlaylist(youtube, playlistId, videoId) {
|
||||
await youtube.playlistItems.insert({
|
||||
part: 'snippet',
|
||||
requestBody: {
|
||||
snippet: {
|
||||
playlistId,
|
||||
resourceId: {
|
||||
kind: 'youtube#video',
|
||||
videoId,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자의 플레이리스트 목록 조회
|
||||
*/
|
||||
async function getPlaylistsForUser(userId) {
|
||||
try {
|
||||
const auth = await getAuthenticatedClientForUser(userId);
|
||||
const youtube = google.youtube({ version: 'v3', auth });
|
||||
|
||||
const res = await youtube.playlists.list({
|
||||
part: 'snippet,contentDetails',
|
||||
mine: true,
|
||||
maxResults: 50,
|
||||
});
|
||||
|
||||
const playlists = res.data.items.map(item => ({
|
||||
id: item.id,
|
||||
title: item.snippet.title,
|
||||
description: item.snippet.description,
|
||||
itemCount: item.contentDetails.itemCount,
|
||||
thumbnail: item.snippet.thumbnails?.default?.url,
|
||||
}));
|
||||
|
||||
// 캐시 업데이트
|
||||
playlists.forEach(p => {
|
||||
db.run(`
|
||||
INSERT OR REPLACE INTO youtube_playlists
|
||||
(user_id, playlist_id, title, item_count, cached_at)
|
||||
VALUES (?, ?, ?, ?, datetime('now'))
|
||||
`, [userId, p.id, p.title, p.itemCount]);
|
||||
});
|
||||
|
||||
return playlists;
|
||||
|
||||
} catch (error) {
|
||||
console.error('[YouTube] 플레이리스트 조회 오류:', error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 플레이리스트 생성
|
||||
*/
|
||||
async function createPlaylistForUser(userId, title, description = '', privacyStatus = 'public') {
|
||||
try {
|
||||
const auth = await getAuthenticatedClientForUser(userId);
|
||||
const youtube = google.youtube({ version: 'v3', auth });
|
||||
|
||||
const res = await youtube.playlists.insert({
|
||||
part: 'snippet,status',
|
||||
requestBody: {
|
||||
snippet: {
|
||||
title: title.substring(0, 150),
|
||||
description: description.substring(0, 5000),
|
||||
},
|
||||
status: { privacyStatus },
|
||||
},
|
||||
});
|
||||
|
||||
const playlist = {
|
||||
id: res.data.id,
|
||||
title: res.data.snippet.title
|
||||
};
|
||||
|
||||
// 캐시에 추가
|
||||
db.run(`
|
||||
INSERT INTO youtube_playlists
|
||||
(user_id, playlist_id, title, item_count, cached_at)
|
||||
VALUES (?, ?, ?, 0, datetime('now'))
|
||||
`, [userId, playlist.id, playlist.title]);
|
||||
|
||||
return playlist;
|
||||
|
||||
} catch (error) {
|
||||
console.error('[YouTube] 플레이리스트 생성 오류:', error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자 YouTube 설정 조회
|
||||
*/
|
||||
function getUserYouTubeSettings(userId) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.get(`SELECT * FROM youtube_settings WHERE user_id = ?`, [userId], (err, row) => {
|
||||
if (err) reject(err);
|
||||
else resolve(row || {
|
||||
default_privacy: 'private',
|
||||
default_category_id: '19',
|
||||
default_tags: '[]',
|
||||
auto_upload: 0,
|
||||
upload_timing: 'manual'
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자 YouTube 설정 업데이트
|
||||
*/
|
||||
function updateUserYouTubeSettings(userId, settings) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const fields = [];
|
||||
const values = [];
|
||||
|
||||
const allowedFields = [
|
||||
'default_privacy', 'default_category_id', 'default_tags',
|
||||
'default_hashtags', 'auto_upload', 'upload_timing',
|
||||
'scheduled_day', 'scheduled_time', 'default_playlist_id', 'notify_on_upload'
|
||||
];
|
||||
|
||||
for (const field of allowedFields) {
|
||||
if (settings[field] !== undefined) {
|
||||
fields.push(`${field} = ?`);
|
||||
values.push(typeof settings[field] === 'object' ? JSON.stringify(settings[field]) : settings[field]);
|
||||
}
|
||||
}
|
||||
|
||||
if (fields.length === 0) {
|
||||
resolve({ success: true });
|
||||
return;
|
||||
}
|
||||
|
||||
values.push(userId);
|
||||
|
||||
db.run(`
|
||||
INSERT INTO youtube_settings (user_id, ${allowedFields.map(f => f).join(', ')})
|
||||
VALUES (?, ${allowedFields.map(() => '?').join(', ')})
|
||||
ON CONFLICT(user_id) DO UPDATE SET ${fields.join(', ')}, updatedAt = datetime('now')
|
||||
`.replace('INSERT INTO youtube_settings (user_id, ', `UPDATE youtube_settings SET ${fields.join(', ')}, updatedAt = datetime('now') WHERE user_id = ?`).split('ON CONFLICT')[0] + ' WHERE user_id = ?', values, function(err) {
|
||||
if (err) {
|
||||
// INSERT 시도
|
||||
db.run(`
|
||||
INSERT OR REPLACE INTO youtube_settings (user_id, ${fields.map(f => f.split(' = ')[0]).join(', ')})
|
||||
VALUES (?, ${fields.map(() => '?').join(', ')})
|
||||
`, [userId, ...values.slice(0, -1)], function(err2) {
|
||||
if (err2) reject(err2);
|
||||
else resolve({ success: true });
|
||||
});
|
||||
} else {
|
||||
resolve({ success: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자의 업로드 히스토리 조회
|
||||
*/
|
||||
function getUploadHistory(userId, limit = 20) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.all(`
|
||||
SELECT * FROM upload_history
|
||||
WHERE user_id = ?
|
||||
ORDER BY uploaded_at DESC
|
||||
LIMIT ?
|
||||
`, [userId, limit], (err, rows) => {
|
||||
if (err) reject(err);
|
||||
else resolve(rows || []);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Legacy 함수들 (기존 코드 호환용)
|
||||
// ============================================
|
||||
const TOKEN_PATH = path.join(__dirname, 'tokens.json');
|
||||
|
||||
async function getAuthenticatedClient() {
|
||||
if (!fs.existsSync(CREDENTIALS_PATH)) {
|
||||
throw new Error("client_secret.json 파일이 없습니다.");
|
||||
}
|
||||
|
||||
const content = fs.readFileSync(CREDENTIALS_PATH, 'utf-8');
|
||||
const credentials = JSON.parse(content);
|
||||
const { client_secret, client_id, redirect_uris } = credentials.installed || credentials.web;
|
||||
|
||||
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, "http://localhost:3001/oauth2callback");
|
||||
|
||||
if (fs.existsSync(TOKEN_PATH)) {
|
||||
const token = fs.readFileSync(TOKEN_PATH, 'utf-8');
|
||||
oAuth2Client.setCredentials(JSON.parse(token));
|
||||
return oAuth2Client;
|
||||
}
|
||||
|
||||
throw new Error("YouTube 인증 토큰이 없습니다.");
|
||||
}
|
||||
|
||||
async function uploadVideo(videoPath, seoData, playlistId = null, privacyStatus = 'public') {
|
||||
// Legacy: 기존 단일 계정 방식
|
||||
try {
|
||||
const auth = await getAuthenticatedClient();
|
||||
const youtube = google.youtube({ version: 'v3', auth });
|
||||
|
||||
const fileSize = fs.statSync(videoPath).size;
|
||||
const title = (seoData.title || 'CastAD 생성 영상').substring(0, 100);
|
||||
const description = (seoData.description || '').substring(0, 5000);
|
||||
const tags = seoData.tags || ['AI', 'CastAD'];
|
||||
|
||||
const res = await youtube.videos.insert({
|
||||
part: 'snippet,status',
|
||||
requestBody: {
|
||||
snippet: { title, description, tags, categoryId: '22' },
|
||||
status: { privacyStatus, selfDeclaredMadeForKids: false },
|
||||
},
|
||||
media: { body: fs.createReadStream(videoPath) },
|
||||
});
|
||||
|
||||
const videoId = res.data.id;
|
||||
console.log(`[YouTube] 업로드 성공! https://youtu.be/${videoId}`);
|
||||
|
||||
if (playlistId) {
|
||||
await addVideoToPlaylist(youtube, playlistId, videoId);
|
||||
}
|
||||
|
||||
return { videoId, url: `https://youtu.be/${videoId}` };
|
||||
} catch (error) {
|
||||
console.error('[YouTube] 업로드 오류:', error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function getPlaylists(maxResults = 50) {
|
||||
const auth = await getAuthenticatedClient();
|
||||
const youtube = google.youtube({ version: 'v3', auth });
|
||||
const res = await youtube.playlists.list({ part: 'snippet,contentDetails', mine: true, maxResults });
|
||||
return res.data.items.map(item => ({
|
||||
id: item.id,
|
||||
title: item.snippet.title,
|
||||
itemCount: item.contentDetails.itemCount,
|
||||
}));
|
||||
}
|
||||
|
||||
async function createPlaylist(title, description = '', privacyStatus = 'public') {
|
||||
const auth = await getAuthenticatedClient();
|
||||
const youtube = google.youtube({ version: 'v3', auth });
|
||||
const res = await youtube.playlists.insert({
|
||||
part: 'snippet,status',
|
||||
requestBody: {
|
||||
snippet: { title, description },
|
||||
status: { privacyStatus },
|
||||
},
|
||||
});
|
||||
return { playlistId: res.data.id, title: res.data.snippet.title };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
// 새로운 다중 사용자 함수들
|
||||
createOAuth2Client,
|
||||
generateAuthUrl,
|
||||
exchangeCodeForTokens,
|
||||
getAuthenticatedClientForUser,
|
||||
getConnectionStatus,
|
||||
disconnectYouTube,
|
||||
uploadVideoForUser,
|
||||
getPlaylistsForUser,
|
||||
createPlaylistForUser,
|
||||
getUserYouTubeSettings,
|
||||
updateUserYouTubeSettings,
|
||||
getUploadHistory,
|
||||
SCOPES,
|
||||
|
||||
// Legacy 함수들 (기존 코드 호환)
|
||||
getAuthenticatedClient,
|
||||
uploadVideo,
|
||||
getPlaylists,
|
||||
createPlaylist,
|
||||
};
|
||||
Reference in new issue
Block a user