finished test for instagram
This commit is contained in:
1 parent
08d47a6990
commit
eff711e03e
38 files changed
+175
-9284
No files matched your search
@@ -5,6 +5,8 @@ from app.database.session import engine
|
||||
from app.home.api.home_admin import ImageAdmin, ProjectAdmin
|
||||
from app.lyric.api.lyrics_admin import LyricAdmin
|
||||
from app.song.api.song_admin import SongAdmin
|
||||
from app.sns.api.sns_admin import SNSUploadTaskAdmin
|
||||
from app.user.api.user_admin import RefreshTokenAdmin, SocialAccountAdmin, UserAdmin
|
||||
from app.video.api.video_admin import VideoAdmin
|
||||
from config import prj_settings
|
||||
|
||||
@@ -35,4 +37,12 @@ def init_admin(
|
||||
# 영상 관리
|
||||
admin.add_view(VideoAdmin)
|
||||
|
||||
# 사용자 관리
|
||||
admin.add_view(UserAdmin)
|
||||
admin.add_view(RefreshTokenAdmin)
|
||||
admin.add_view(SocialAccountAdmin)
|
||||
|
||||
# SNS 관리
|
||||
admin.add_view(SNSUploadTaskAdmin)
|
||||
|
||||
return admin
|
||||
@@ -77,6 +77,7 @@ async def create_db_tables():
|
||||
from app.lyric.models import Lyric # noqa: F401
|
||||
from app.song.models import Song, SongTimestamp # noqa: F401
|
||||
from app.video.models import Video # noqa: F401
|
||||
from app.sns.models import SNSUploadTask # noqa: F401
|
||||
|
||||
# 생성할 테이블 목록
|
||||
tables_to_create = [
|
||||
@@ -89,6 +90,7 @@ async def create_db_tables():
|
||||
Song.__table__,
|
||||
SongTimestamp.__table__,
|
||||
Video.__table__,
|
||||
SNSUploadTask.__table__,
|
||||
]
|
||||
|
||||
logger.info("Creating database tables...")
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
from sqladmin import ModelView
|
||||
|
||||
from app.sns.models import SNSUploadTask
|
||||
|
||||
|
||||
class SNSUploadTaskAdmin(ModelView, model=SNSUploadTask):
|
||||
name = "SNS 업로드 작업"
|
||||
name_plural = "SNS 업로드 작업 목록"
|
||||
icon = "fa-solid fa-share-from-square"
|
||||
category = "SNS 관리"
|
||||
page_size = 20
|
||||
|
||||
column_list = [
|
||||
"id",
|
||||
"user_uuid",
|
||||
"task_id",
|
||||
"social_account_id",
|
||||
"is_scheduled",
|
||||
"status",
|
||||
"scheduled_at",
|
||||
"uploaded_at",
|
||||
"created_at",
|
||||
]
|
||||
|
||||
column_details_list = [
|
||||
"id",
|
||||
"user_uuid",
|
||||
"task_id",
|
||||
"social_account_id",
|
||||
"is_scheduled",
|
||||
"scheduled_at",
|
||||
"url",
|
||||
"caption",
|
||||
"status",
|
||||
"uploaded_at",
|
||||
"created_at",
|
||||
]
|
||||
|
||||
form_excluded_columns = ["created_at", "user", "social_account"]
|
||||
|
||||
column_searchable_list = [
|
||||
SNSUploadTask.user_uuid,
|
||||
SNSUploadTask.task_id,
|
||||
SNSUploadTask.status,
|
||||
]
|
||||
|
||||
column_default_sort = (SNSUploadTask.created_at, True)
|
||||
|
||||
column_sortable_list = [
|
||||
SNSUploadTask.id,
|
||||
SNSUploadTask.user_uuid,
|
||||
SNSUploadTask.social_account_id,
|
||||
SNSUploadTask.is_scheduled,
|
||||
SNSUploadTask.status,
|
||||
SNSUploadTask.scheduled_at,
|
||||
SNSUploadTask.uploaded_at,
|
||||
SNSUploadTask.created_at,
|
||||
]
|
||||
|
||||
column_labels = {
|
||||
"id": "ID",
|
||||
"user_uuid": "사용자 UUID",
|
||||
"task_id": "작업 ID",
|
||||
"social_account_id": "소셜 계정 ID",
|
||||
"is_scheduled": "예약 여부",
|
||||
"scheduled_at": "예약 일시",
|
||||
"url": "미디어 URL",
|
||||
"caption": "캡션",
|
||||
"status": "상태",
|
||||
"uploaded_at": "업로드 일시",
|
||||
"created_at": "생성일시",
|
||||
}
|
||||
+15
-11
@@ -160,16 +160,17 @@ class SocialAccountAdmin(ModelView, model=SocialAccount):
|
||||
|
||||
column_list = [
|
||||
"id",
|
||||
"user_id",
|
||||
"user_uuid",
|
||||
"platform",
|
||||
"platform_username",
|
||||
"is_active",
|
||||
"connected_at",
|
||||
"is_deleted",
|
||||
"created_at",
|
||||
]
|
||||
|
||||
column_details_list = [
|
||||
"id",
|
||||
"user_id",
|
||||
"user_uuid",
|
||||
"platform",
|
||||
"platform_user_id",
|
||||
"platform_username",
|
||||
@@ -177,32 +178,34 @@ class SocialAccountAdmin(ModelView, model=SocialAccount):
|
||||
"scope",
|
||||
"token_expires_at",
|
||||
"is_active",
|
||||
"connected_at",
|
||||
"is_deleted",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
]
|
||||
|
||||
form_excluded_columns = ["connected_at", "updated_at", "user"]
|
||||
form_excluded_columns = ["created_at", "updated_at", "user"]
|
||||
|
||||
column_searchable_list = [
|
||||
SocialAccount.user_id,
|
||||
SocialAccount.user_uuid,
|
||||
SocialAccount.platform,
|
||||
SocialAccount.platform_user_id,
|
||||
SocialAccount.platform_username,
|
||||
]
|
||||
|
||||
column_default_sort = (SocialAccount.connected_at, True)
|
||||
column_default_sort = (SocialAccount.created_at, True)
|
||||
|
||||
column_sortable_list = [
|
||||
SocialAccount.id,
|
||||
SocialAccount.user_id,
|
||||
SocialAccount.user_uuid,
|
||||
SocialAccount.platform,
|
||||
SocialAccount.is_active,
|
||||
SocialAccount.connected_at,
|
||||
SocialAccount.is_deleted,
|
||||
SocialAccount.created_at,
|
||||
]
|
||||
|
||||
column_labels = {
|
||||
"id": "ID",
|
||||
"user_id": "사용자 ID",
|
||||
"user_uuid": "사용자 UUID",
|
||||
"platform": "플랫폼",
|
||||
"platform_user_id": "플랫폼 사용자 ID",
|
||||
"platform_username": "플랫폼 사용자명",
|
||||
@@ -210,6 +213,7 @@ class SocialAccountAdmin(ModelView, model=SocialAccount):
|
||||
"scope": "권한 범위",
|
||||
"token_expires_at": "토큰 만료일시",
|
||||
"is_active": "활성화",
|
||||
"connected_at": "연동일시",
|
||||
"is_deleted": "삭제됨",
|
||||
"created_at": "생성일시",
|
||||
"updated_at": "수정일시",
|
||||
}
|
||||
@@ -23,7 +23,7 @@ class SocialAccountCreateRequest(BaseModel):
|
||||
refresh_token: Optional[str] = Field(None, description="OAuth 리프레시 토큰")
|
||||
token_expires_at: Optional[datetime] = Field(None, description="토큰 만료 일시")
|
||||
scope: Optional[str] = Field(None, description="허용된 권한 범위")
|
||||
platform_user_id: str = Field(..., min_length=1, description="플랫폼 내 사용자 고유 ID")
|
||||
platform_user_id: Optional[str] = Field(None, description="플랫폼 내 사용자 고유 ID")
|
||||
platform_username: Optional[str] = Field(None, description="플랫폼 내 사용자명/핸들")
|
||||
platform_data: Optional[dict[str, Any]] = Field(None, description="플랫폼별 추가 정보")
|
||||
|
||||
@@ -33,14 +33,11 @@ class SocialAccountCreateRequest(BaseModel):
|
||||
"platform": "instagram",
|
||||
"access_token": "IGQWRPcG...",
|
||||
"refresh_token": None,
|
||||
"token_expires_at": "2026-03-15T10:30:00",
|
||||
"scope": "instagram_basic,instagram_content_publish",
|
||||
"platform_user_id": "17841400000000000",
|
||||
"platform_username": "my_instagram_account",
|
||||
"platform_data": {
|
||||
"business_account_id": "17841400000000000",
|
||||
"facebook_page_id": "123456789"
|
||||
}
|
||||
"token_expires_at": None,
|
||||
"scope": None,
|
||||
"platform_user_id": None,
|
||||
"platform_username": None,
|
||||
"platform_data": None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -76,7 +73,7 @@ class SocialAccountResponse(BaseModel):
|
||||
|
||||
account_id: int = Field(..., validation_alias="id", description="소셜 계정 ID")
|
||||
platform: Platform = Field(..., description="플랫폼 구분")
|
||||
platform_user_id: str = Field(..., description="플랫폼 내 사용자 고유 ID")
|
||||
platform_user_id: Optional[str] = Field(None, description="플랫폼 내 사용자 고유 ID")
|
||||
platform_username: Optional[str] = Field(None, description="플랫폼 내 사용자명/핸들")
|
||||
platform_data: Optional[dict[str, Any]] = Field(None, description="플랫폼별 추가 정보")
|
||||
scope: Optional[str] = Field(None, description="허용된 권한 범위")
|
||||
|
||||
@@ -32,6 +32,7 @@ URL 경로 형식:
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import re
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
@@ -129,6 +130,33 @@ class AzureBlobUploader:
|
||||
"""마지막 업로드의 공개 URL (SAS 토큰 제외)"""
|
||||
return self._last_public_url
|
||||
|
||||
def _sanitize_filename(self, file_name: str) -> str:
|
||||
"""파일명에서 공백/특수문자 제거, 한글/영문/숫자만 허용
|
||||
|
||||
Args:
|
||||
file_name: 원본 파일명
|
||||
|
||||
Returns:
|
||||
str: 정리된 파일명 (한글, 영문, 숫자만 포함)
|
||||
|
||||
Example:
|
||||
>>> self._sanitize_filename("my file (1).mp4")
|
||||
'myfile1.mp4'
|
||||
>>> self._sanitize_filename("테스트 파일!@#.png")
|
||||
'테스트파일.png'
|
||||
"""
|
||||
stem = Path(file_name).stem
|
||||
suffix = Path(file_name).suffix
|
||||
|
||||
# 한글(가-힣), 영문(a-zA-Z), 숫자(0-9)만 남기고 제거
|
||||
sanitized = re.sub(r'[^가-힣a-zA-Z0-9]', '', stem)
|
||||
|
||||
# 빈 문자열이면 기본값 사용
|
||||
if not sanitized:
|
||||
sanitized = "file"
|
||||
|
||||
return f"{sanitized}{suffix}"
|
||||
|
||||
def _build_upload_url(self, category: str, file_name: str) -> str:
|
||||
"""업로드 URL 생성 (SAS 토큰 포함)"""
|
||||
# SAS 토큰 앞뒤의 ?, ', " 제거
|
||||
@@ -238,8 +266,8 @@ class AzureBlobUploader:
|
||||
Returns:
|
||||
bool: 업로드 성공 여부
|
||||
"""
|
||||
# 파일 경로에서 파일명 추출
|
||||
file_name = Path(file_path).name
|
||||
# 파일 경로에서 파일명 추출 후 정리 (공백/특수문자 제거)
|
||||
file_name = self._sanitize_filename(Path(file_path).name)
|
||||
|
||||
upload_url = self._build_upload_url(category, file_name)
|
||||
self._last_public_url = self._build_public_url(category, file_name)
|
||||
@@ -301,7 +329,8 @@ class AzureBlobUploader:
|
||||
success = await uploader.upload_music_bytes(audio_bytes, "my_song")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
# 확장자가 없으면 .mp3 추가
|
||||
# 파일명 정리 (공백/특수문자 제거) 후 확장자가 없으면 .mp3 추가
|
||||
file_name = self._sanitize_filename(file_name)
|
||||
if not Path(file_name).suffix:
|
||||
file_name = f"{file_name}.mp3"
|
||||
|
||||
@@ -363,7 +392,8 @@ class AzureBlobUploader:
|
||||
success = await uploader.upload_video_bytes(video_bytes, "my_video")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
# 확장자가 없으면 .mp4 추가
|
||||
# 파일명 정리 (공백/특수문자 제거) 후 확장자가 없으면 .mp4 추가
|
||||
file_name = self._sanitize_filename(file_name)
|
||||
if not Path(file_name).suffix:
|
||||
file_name = f"{file_name}.mp4"
|
||||
|
||||
@@ -430,9 +460,13 @@ class AzureBlobUploader:
|
||||
success = await uploader.upload_image_bytes(content, "my_image.png")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
# Content-Type 결정을 위해 먼저 확장자 추출
|
||||
extension = Path(file_name).suffix.lower()
|
||||
content_type = self.IMAGE_CONTENT_TYPES.get(extension, "image/jpeg")
|
||||
|
||||
# 파일명 정리 (공백/특수문자 제거)
|
||||
file_name = self._sanitize_filename(file_name)
|
||||
|
||||
upload_url = self._build_upload_url("image", file_name)
|
||||
self._last_public_url = self._build_public_url("image", file_name)
|
||||
log_prefix = "upload_image_bytes"
|
||||
|
||||
@@ -551,23 +551,15 @@ async def get_video_status(
|
||||
|
||||
if video and video.status != "completed":
|
||||
# 이미 완료된 경우 백그라운드 작업 중복 실행 방지
|
||||
# task_id로 Project 조회하여 store_name 가져오기
|
||||
project_result = await session.execute(
|
||||
select(Project).where(Project.id == video.project_id)
|
||||
)
|
||||
project = project_result.scalar_one_or_none()
|
||||
|
||||
store_name = project.store_name if project else "video"
|
||||
|
||||
# 백그라운드 태스크로 MP4 다운로드 → Blob 업로드 → DB 업데이트 → 임시 파일 삭제
|
||||
logger.info(
|
||||
f"[get_video_status] Background task args - task_id: {video.task_id}, video_url: {video_url}, store_name: {store_name}"
|
||||
f"[get_video_status] Background task args - task_id: {video.task_id}, video_url: {video_url}, creatomate_render_id: {creatomate_render_id}"
|
||||
)
|
||||
background_tasks.add_task(
|
||||
download_and_upload_video_to_blob,
|
||||
task_id=video.task_id,
|
||||
video_url=video_url,
|
||||
store_name=store_name,
|
||||
creatomate_render_id=creatomate_render_id,
|
||||
user_uuid=current_user.user_uuid,
|
||||
)
|
||||
elif video and video.status == "completed":
|
||||
|
||||
@@ -105,27 +105,25 @@ async def _download_video(url: str, task_id: str) -> bytes:
|
||||
async def download_and_upload_video_to_blob(
|
||||
task_id: str,
|
||||
video_url: str,
|
||||
store_name: str,
|
||||
creatomate_render_id: str,
|
||||
user_uuid: str,
|
||||
) -> None:
|
||||
"""백그라운드에서 영상을 다운로드하고 Azure Blob Storage에 업로드한 뒤 Video 테이블을 업데이트합니다.
|
||||
|
||||
파일명은 creatomate_render_id를 사용하여 고유성을 보장합니다.
|
||||
|
||||
Args:
|
||||
task_id: 프로젝트 task_id
|
||||
video_url: 다운로드할 영상 URL
|
||||
store_name: 저장할 파일명에 사용할 업체명
|
||||
creatomate_render_id: Creatomate API 렌더 ID (파일명으로 사용)
|
||||
user_uuid: 사용자 UUID (Azure Blob Storage 경로에 사용)
|
||||
"""
|
||||
logger.info(f"[download_and_upload_video_to_blob] START - task_id: {task_id}, store_name: {store_name}")
|
||||
logger.info(f"[download_and_upload_video_to_blob] START - task_id: {task_id}, creatomate_render_id: {creatomate_render_id}")
|
||||
temp_file_path: Path | None = None
|
||||
|
||||
try:
|
||||
# 파일명에 사용할 수 없는 문자 제거
|
||||
safe_store_name = "".join(
|
||||
c for c in store_name if c.isalnum() or c in (" ", "_", "-")
|
||||
).strip()
|
||||
safe_store_name = safe_store_name or "video"
|
||||
file_name = f"{safe_store_name}.mp4"
|
||||
# creatomate_render_id를 파일명으로 사용 (고유 ID이므로 sanitize 불필요)
|
||||
file_name = f"{creatomate_render_id}.mp4"
|
||||
|
||||
# 임시 저장 경로 생성
|
||||
temp_dir = Path("media") / "temp" / task_id
|
||||
@@ -191,18 +189,18 @@ async def download_and_upload_video_to_blob(
|
||||
async def download_and_upload_video_by_creatomate_render_id(
|
||||
creatomate_render_id: str,
|
||||
video_url: str,
|
||||
store_name: str,
|
||||
user_uuid: str,
|
||||
) -> None:
|
||||
"""creatomate_render_id로 Video를 조회하여 영상을 다운로드하고 Azure Blob Storage에 업로드한 뒤 Video 테이블을 업데이트합니다.
|
||||
|
||||
파일명은 creatomate_render_id를 사용하여 고유성을 보장합니다.
|
||||
|
||||
Args:
|
||||
creatomate_render_id: Creatomate API 렌더 ID
|
||||
creatomate_render_id: Creatomate API 렌더 ID (파일명으로도 사용)
|
||||
video_url: 다운로드할 영상 URL
|
||||
store_name: 저장할 파일명에 사용할 업체명
|
||||
user_uuid: 사용자 UUID (Azure Blob Storage 경로에 사용)
|
||||
"""
|
||||
logger.info(f"[download_and_upload_video_by_creatomate_render_id] START - creatomate_render_id: {creatomate_render_id}, store_name: {store_name}")
|
||||
logger.info(f"[download_and_upload_video_by_creatomate_render_id] START - creatomate_render_id: {creatomate_render_id}")
|
||||
temp_file_path: Path | None = None
|
||||
task_id: str | None = None
|
||||
|
||||
@@ -224,12 +222,8 @@ async def download_and_upload_video_by_creatomate_render_id(
|
||||
task_id = video.task_id
|
||||
logger.info(f"[download_and_upload_video_by_creatomate_render_id] Video found - creatomate_render_id: {creatomate_render_id}, task_id: {task_id}")
|
||||
|
||||
# 파일명에 사용할 수 없는 문자 제거
|
||||
safe_store_name = "".join(
|
||||
c for c in store_name if c.isalnum() or c in (" ", "_", "-")
|
||||
).strip()
|
||||
safe_store_name = safe_store_name or "video"
|
||||
file_name = f"{safe_store_name}.mp4"
|
||||
# creatomate_render_id를 파일명으로 사용 (고유 ID이므로 sanitize 불필요)
|
||||
file_name = f"{creatomate_render_id}.mp4"
|
||||
|
||||
# 임시 저장 경로 생성
|
||||
temp_dir = Path("media") / "temp" / task_id
|
||||
|
||||
Reference in new issue
Block a user