init commit from ado4

This commit is contained in:
jaehwang committed 2025-12-08 13:27:07 +09:00
commit d820394ccc
126 files changed
+51929

No files matched your search

+243
View File
@@ -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}")
+558
View File
@@ -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")
+425
View File
@@ -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
)
+9
View File
@@ -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 # 환경변수 로드