Compare commits
23 Commits
6c31b96be6
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 583ba8dbcf | |||
| 25688db376 | |||
| 31aaaaf8e9 | |||
| 677baf662e | |||
| 4e0401c95f | |||
| fcee5a5919 | |||
| cf4f7ab7b4 | |||
| 7abaaa8d38 | |||
| 74655b31df | |||
| b22e544f0b | |||
| 4200f48ec0 | |||
| f01f41499c | |||
| ecc16520be | |||
| 59b7715a93 | |||
| 50982f19b0 | |||
| 41c7fa456e | |||
| 69a0fe0078 | |||
| 535a0ca3f9 | |||
| 9b3f4f72bd | |||
| 8e3594386d | |||
| 02d26a104d | |||
| 1175acd16e | |||
| 783b44b6b6 |
78
README.md
78
README.md
@@ -8,6 +8,9 @@
|
||||
## 🚀 주요 기능 (Key Features)
|
||||
|
||||
* **다중 사이트 지원**: Ohli24, Anilife, Linkkf 등 다양한 소스에서 영상 검색 및 다운로드.
|
||||
* **자막 최적화**:
|
||||
* **자막 전용 다운로드 (Linkkf)**: 영상 없이 자막(VTT)만 별도로 추출하여 SRT로 변환 후 다운로드할 수 있습니다.
|
||||
* **자막 합침 (Muxing)**: 다운로드된 외부 자막(SRT)을 MP4 컨테이너에 자동으로 삽입하여 범용성을 높입니다.
|
||||
* **강력한 우회 기술 (Anti-Bot Bypass)**:
|
||||
* **TLS Fingerprint 변조**: `curl_cffi`를 사용하여 실제 Chrome 브라우저처럼 위장, Cloudflare 및 각종 봇 차단을 무력화합니다.
|
||||
* **CDN 자동 감지**: 스트리밍 서버(CDN)의 도메인이 수시로 변경되더라도 자동으로 감지하여 대응합니다. (예: 14B 가짜 파일 문제 해결)
|
||||
@@ -80,6 +83,81 @@
|
||||
---
|
||||
|
||||
## 📝 변경 이력 (Changelog)
|
||||
|
||||
### v0.7.7 (2026-01-19)
|
||||
- **Linkkf 추출 핵심 보강 및 Anilife 고속화**:
|
||||
- **전용 헤더 처리**: Linkkf 스트리밍 영상(m3u8) 추출 시 Referer 헤더가 유실되던 문제를 CDP 타입 래핑(`zd.cdp.network.Headers()`)으로 완벽 해결.
|
||||
- **Anilife 퍼포먼스**: 애니라이프 영상 추출 시 불필요한 대기 시간을 제거하고 네비게이션 전략을 최적화하여 추출 속도를 개선했습니다.
|
||||
- **GDM 연동 안정성**: yt-dlp 호출 시 `--add-header` 옵션을 통해 모든 보안 파라미터를 정확히 전달하도록 보강했습니다.
|
||||
|
||||
### v0.7.6 (2026-01-12)
|
||||
- **모바일 상단 메뉴 스크롤 힌트 도입**:
|
||||
- 메뉴가 가로로 길어질 때 우측에 은은한 페이드 효과를 추가하여 '더 많은 메뉴'가 있음을 직관적으로 알 수 있도록 개선했습니다.
|
||||
- 아주 가늘고 투명한 스크롤바 가이드를 추가하여 모던한 감성을 더했습니다.
|
||||
- CSS 구문 최적화 및 미디어 쿼리 중복을 정리했습니다.
|
||||
|
||||
### v0.7.5 (2026-01-12)
|
||||
- **모바일 레이아웃 가로 핏 완벽 최적화**:
|
||||
- 화면이 70%만 보이고 오른쪽으로 밀리던 현상을 해결하기 위해 전역적인 너비 정규화(`width: 100%`)와 오버플로우 차단을 적용했습니다.
|
||||
- 모바일 브라우저 렌더링 오류를 유발하는 `background-attachment: fixed` 속성을 모바일 한정으로 해제했습니다.
|
||||
- 모든 요소에 `box-sizing: border-box`를 강제하여 패딩으로 인한 너비 확장을 방지했습니다.
|
||||
- 에피소드 그리드를 모바일 1열 배치로 최적화하여 오버플로우를 원천 차단했습니다.
|
||||
|
||||
### v0.7.4 (2026-01-12)
|
||||
- **모바일 레이아웃 시프트 최종 수정**:
|
||||
- 부트스트랩 `row`의 음수 마진으로 인해 화면이 오른쪽으로 밀려 보이던 현상을 정규화 작업을 통해 해결했습니다.
|
||||
- `html`, `body` 레벨에서 가로 오버플로우를 차단하고 전역적인 단위 대응(`100vw`)을 적용하여 안정적인 가로 핏을 구현했습니다.
|
||||
- 상단 메뉴(브레드크럼)가 부모 너비를 확장시키지 않도록 `display` 속성을 개선했습니다.
|
||||
|
||||
### v0.7.3 (2026-01-12)
|
||||
- **Anilife 모바일 UI 최적화 (프리미엄 개편)**:
|
||||
- **분석 페이지**: 가로 여백을 최소화(15px -> 2px)하여 모바일 가독성 증대.
|
||||
- **큐 페이지**: 기존 테이블 레이아웃을 모바일 전용 **카드형 레이아웃**으로 전면 교체. 파일명과 진행률 바를 강조하고 2단 정보 그리드를 도입하여 가시성 확보.
|
||||
- **오버플로우 수정**: 상단 메뉴(브레드크럼) 가로 스크롤 적용 및 액션 버튼 자동 줄바꿈 배치를 통해 화면 넘침 해결.
|
||||
- **Linkkf 안정화 및 자막 연동**:
|
||||
- **자막 자동화**: GDM(v0.2.30+) 연동을 통해 비디오와 자막을 동시에 안전하게 다운로드.
|
||||
- **경로 정규화**: 저장 경로 내 중복 구분자(`//./`) 발생 문제를 원천 해결.
|
||||
- **추출 성능**: 비디오 URL 추출 시 타임아웃 및 예외 처리를 강화하여 UI 프리징 방지.
|
||||
|
||||
### v0.7.2 (2026-01-11)
|
||||
- **Linkkf 자막 전용 다운로드 지원**:
|
||||
- 에피소드 분석 페이지에 **"자막만 다운로드"** 버튼 추가. (VTT 추출 및 SRT 자동 변환)
|
||||
- 백그라운드 스레드 처리를 통해 대량의 자막을 끊김 없이 다운로드 가능.
|
||||
- **Linkkf 목록-분석 연동 강화**:
|
||||
- 목록(`list`) 페이지 카드에 **"작품소개"** 버튼 추가하여 원클릭 분석 지원.
|
||||
- URL 파라미터(`code`)를 통한 자동 분석 로직 개선으로 연동 편의성 증대.
|
||||
- **플러그인 핫 리로드 안정화**:
|
||||
- Linkkf, AniLife, Ohli24 모든 모듈의 DB 모델에 `extend_existing: True` 옵션 적용.
|
||||
- 플러그인 자가 업데이트 시 DB 모델 제약으로 인한 리로드 실패 문제 해결.
|
||||
- **UI/UX 보안**:
|
||||
- 분석 페이지의 AJAX 요청 결과 핸들링을 강화하여 사용자에게 정확한 성공/실패 알림 제공.
|
||||
|
||||
### v0.7.1 (2026-01-11)
|
||||
- **GDM 통합 버그 수정 (Hotfix)**:
|
||||
- **UI 필드 매핑 수정**: 큐 페이지에서 GDM 작업의 상태, 진행률 등이 'undefined'로 표시되던 필드명 불일치 문제 해결.
|
||||
- **실시간 업데이트(Socket) 강화**: GDM 전용 소켓 이벤트 리스너를 추가하여, 수동 새로고침 없이도 다운로드 상태가 실시간으로 반영되도록 개선.
|
||||
- **모든 모듈 적용**: Linkkf뿐만 아니라 AniLife, Ohli24 큐 페이지에도 동일한 수정 사항 반영.
|
||||
|
||||
### v0.7.0 (2026-01-11)
|
||||
- **GDM(Gommi Downloader Manager) 통합 고도화**:
|
||||
- **통합 큐 페이지**: 링크애니, 애니라이프, 오클리24의 큐 페이지에서 GDM 작업을 실시간으로 확인 및 중지/삭제 가능하도록 통합.
|
||||
- **상태 자동 동기화**: GDM 다운로드 완료 시 콜백을 통해 로컬 DB 상태를 자동으로 '컴플리트'로 업데이트하여 목록 페이지(`list`)에 즉시 반영.
|
||||
- **GDM 작업 매핑**: GDM의 다양한 상태 코드 및 진행률을 각 플러그인 UI 형식에 맞게 변환 처리.
|
||||
- **안정성 강화**:
|
||||
- **백그라운드 DB 안정화**: 스케줄러 및 비동기 작업 중 데이터베이스 접근 시 `app_context` 오류 방지를 위해 전역적인 컨텍스트 래핑 적용.
|
||||
- **자동 다운로드 로직 개선**: 링크애니 '전체(all)' 모드 모니터링 및 자동 에피소드 등록 로직 보강.
|
||||
- **알림 시스템**: 링크애니 새 에피소드 감지 시 Discord/Telegram 알림 기능 및 설정 UI 추가.
|
||||
|
||||
### v0.6.25 (2026-01-09)
|
||||
- **자가 업데이트 기능 추가**: 모든 설정 페이지 (Ohli24, Anilife, Linkkf)에서 "업데이트" 버튼 클릭으로 Git Pull 및 플러그인 핫 리로드 지원
|
||||
- **버전 체크 API**: GitHub에서 최신 버전 정보를 가져와 업데이트 알림 표시 (1시간 캐싱)
|
||||
- **공통 베이스 통합**: `AnimeModuleBase`에 `get_update_info`, `reload_plugin` 메서드 추가로 모든 모듈에서 자동 사용 가능
|
||||
|
||||
### v0.6.24 (2026-01-08)
|
||||
- **Ohli24 GDM 연동 버그 수정**:
|
||||
- **썸네일 누락 해결**: GDM 위임 시 `image` 키를 `thumbnail`로 올바르게 매핑하여 목록에서 이미지가 보이도록 수정.
|
||||
- **소스 타입 통일**: GDM 측 명칭 변경에 맞춰 `ani24` 대신 `ohli24`를 기본값으로 사용 (하위 호환 유지).
|
||||
- **검색 결과 썸네일**: 일부 환경에서 썸네일 URL이 누락되던 필드 보강.
|
||||
|
||||
### v0.6.23 (2026-01-08)
|
||||
- **Linkkf 다운로드 완전 복구**:
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
title: "애니 다운로더"
|
||||
version: 0.6.23
|
||||
version: 0.7.17
|
||||
package_name: "anime_downloader"
|
||||
developer: "projectdx"
|
||||
description: "anime downloader"
|
||||
|
||||
11
lib/util.py
11
lib/util.py
@@ -32,10 +32,8 @@ def download(url, file_name):
|
||||
def read_file(filename):
|
||||
try:
|
||||
import codecs
|
||||
ifp = codecs.open(filename, 'r', encoding='utf8')
|
||||
data = ifp.read()
|
||||
ifp.close()
|
||||
return data
|
||||
with codecs.open(filename, 'r', encoding='utf8') as ifp:
|
||||
return ifp.read()
|
||||
except Exception as exception:
|
||||
logger.error('Exception:%s', exception)
|
||||
logger.error(traceback.format_exc())
|
||||
@@ -79,9 +77,8 @@ class Util(object):
|
||||
def write_file(data, filename):
|
||||
try:
|
||||
import codecs
|
||||
ofp = codecs.open(filename, 'w', encoding='utf8')
|
||||
ofp.write(data)
|
||||
ofp.close()
|
||||
with codecs.open(filename, 'w', encoding='utf8') as ofp:
|
||||
ofp.write(data)
|
||||
except Exception as exception:
|
||||
logger.debug('Exception:%s', exception)
|
||||
logger.debug(traceback.format_exc())
|
||||
|
||||
@@ -17,20 +17,28 @@ from http.server import HTTPServer, BaseHTTPRequestHandler
|
||||
from threading import Thread, Lock
|
||||
from typing import Any, Optional, Dict, List, Type, cast
|
||||
import zendriver as zd
|
||||
import datetime # Added for datetime.now()
|
||||
import logging # Added for logging setup
|
||||
|
||||
# 터미널 및 파일로 로그 출력 설정
|
||||
LOG_FILE: str = "/tmp/zendriver_daemon.log"
|
||||
|
||||
def log_debug(msg: str) -> None:
|
||||
"""타임스탬프와 함께 로그 출력 및 파일 저장"""
|
||||
timestamp: str = time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
formatted_msg: str = f"[{timestamp}] {msg}"
|
||||
print(formatted_msg, file=sys.stderr)
|
||||
try:
|
||||
with open(LOG_FILE, "a", encoding="utf-8") as f:
|
||||
f.write(formatted_msg + "\n")
|
||||
except Exception:
|
||||
pass
|
||||
# 로그 설정
|
||||
def log_debug(msg):
|
||||
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
log_msg = f"[{timestamp}] {msg}"
|
||||
print(log_msg)
|
||||
with open(LOG_FILE, "a", encoding="utf-8") as f:
|
||||
f.write(log_msg + "\n")
|
||||
|
||||
# Zendriver 내부 로그 연동
|
||||
class ZendriverLogHandler(logging.Handler):
|
||||
def emit(self, record):
|
||||
log_debug(f"[ZendriverLib] {record.levelname}: {record.getMessage()}")
|
||||
|
||||
zd_logger = logging.getLogger("zendriver")
|
||||
zd_logger.setLevel(logging.DEBUG)
|
||||
zd_logger.addHandler(ZendriverLogHandler())
|
||||
|
||||
DAEMON_PORT: int = 19876
|
||||
browser: Optional[Any] = None
|
||||
@@ -121,7 +129,8 @@ class ZendriverHandler(BaseHTTPRequestHandler):
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
fetch_with_browser(url, timeout, headers), loop
|
||||
)
|
||||
result: Dict[str, Any] = future.result(timeout=timeout + 15)
|
||||
# 시놀로지 등 느린 환경을 위해 타임아웃 마진을 15초 -> 45초로 확장
|
||||
result: Dict[str, Any] = future.result(timeout=timeout + 45)
|
||||
self._send_json(200, result)
|
||||
else:
|
||||
self._send_json(500, {"success": False, "error": "Event loop not ready"})
|
||||
@@ -187,18 +196,18 @@ async def ensure_browser() -> Any:
|
||||
|
||||
# 사용자 데이터 디렉토리 설정 (Mac/Root 권한 이슈 대응)
|
||||
import tempfile
|
||||
import platform
|
||||
uid = os.getuid() if hasattr(os, 'getuid') else 'win'
|
||||
|
||||
log_debug(f"[ZendriverDaemon] Environment: Python {sys.version.split()[0]} on {platform.system()} (UID: {uid})")
|
||||
|
||||
browser_args = [
|
||||
"--no-sandbox",
|
||||
"--disable-setuid-sandbox",
|
||||
"--disable-dev-shm-usage",
|
||||
"--disable-gpu",
|
||||
"--no-first-run",
|
||||
"--no-service-autorun",
|
||||
"--password-store=basic",
|
||||
"--mute-audio",
|
||||
"--disable-notifications",
|
||||
"--disable-setuid-sandbox",
|
||||
"--disable-dev-shm-usage",
|
||||
"--disable-gpu",
|
||||
"--disable-software-rasterizer",
|
||||
"--remote-allow-origins=*",
|
||||
"--disable-background-networking",
|
||||
"--disable-background-timer-throttling",
|
||||
"--disable-backgrounding-occluded-windows",
|
||||
@@ -227,18 +236,44 @@ async def ensure_browser() -> Any:
|
||||
# Note: zendriver supports direct CDP commands
|
||||
|
||||
for exec_path in candidates:
|
||||
user_data_dir = os.path.join(tempfile.gettempdir(), f"zd_daemon_{uid}_{os.path.basename(exec_path).replace(' ', '_')}")
|
||||
# 프로세스별/시간별 고유한 프로필 디렉토리 생성 (SingletonLock 충돌 원천 차단)
|
||||
unique_id = f"{uid}_{int(time.time())}"
|
||||
user_data_dir = os.path.join(tempfile.gettempdir(), f"zd_daemon_{unique_id}_{os.path.basename(exec_path).replace(' ', '_')}")
|
||||
|
||||
# 기존 락(Lock) 파일이나 깨진 프로필이 있으면 제거 (중요: 시놀로지 도커 SingletonLock 대응)
|
||||
if os.path.exists(user_data_dir):
|
||||
try:
|
||||
import shutil
|
||||
# 안전장치: 경로가 임시 디렉토리에 있고 zd_daemon_ 접두사를 포함하는지 확인
|
||||
temp_dir = tempfile.gettempdir()
|
||||
if user_data_dir.startswith(temp_dir) and "zd_daemon_" in user_data_dir:
|
||||
shutil.rmtree(user_data_dir, ignore_errors=True)
|
||||
|
||||
# 리눅스에서 SingletonLock이 끈질기게 남는 경우 대응
|
||||
if platform.system() == "Linux":
|
||||
# 명령어 주입 방지를 위해 경로를 인자로 전달하지 않고 직접 문자열 검증 후 실행
|
||||
os.system(f"rm -rf '{user_data_dir}'")
|
||||
|
||||
log_debug(f"[ZendriverDaemon] Cleaned up existing profile dir: {user_data_dir}")
|
||||
else:
|
||||
log_debug(f"[ZendriverDaemon] Skip cleanup: Path safety check failed ({user_data_dir})")
|
||||
except Exception as rm_e:
|
||||
log_debug(f"[ZendriverDaemon] Failed to clean profile dir: {rm_e}")
|
||||
|
||||
os.makedirs(user_data_dir, exist_ok=True)
|
||||
|
||||
try:
|
||||
log_debug(f"[ZendriverDaemon] Trying browser at: {exec_path}")
|
||||
start_time_init = time.time()
|
||||
log_debug(f"[ZendriverDaemon] Launching browser: {exec_path} (Sandbox: False, Timeout: 1.0s, Tries: 30)")
|
||||
browser = await zd.start(
|
||||
headless=True,
|
||||
browser_executable_path=exec_path,
|
||||
no_sandbox=True,
|
||||
sandbox=False,
|
||||
user_data_dir=user_data_dir,
|
||||
browser_args=browser_args
|
||||
browser_args=browser_args,
|
||||
browser_connection_timeout=1.0,
|
||||
browser_connection_max_tries=30
|
||||
)
|
||||
log_debug(f"[ZendriverDaemon] Browser started successfully in {time.time() - start_time_init:.2f}s using: {exec_path}")
|
||||
return browser
|
||||
@@ -284,8 +319,28 @@ async def fetch_with_browser(url: str, timeout: int = 30, headers: Optional[Dict
|
||||
|
||||
# 페이지 로드 시도
|
||||
try:
|
||||
# 탭(페이지) 열기 (브라우저가 없으면 생성)
|
||||
page = await browser.get("about:blank") # 새 탭 열기 대신 기존 탭 재활용 혹은 about:blank 이동
|
||||
# zendriver/core/browser.py:304 에서 self.targets가 비어있을 때 StopIteration 발생 가능
|
||||
# 이를 방지하기 위해 tabs가 생길 때까지 잠시 대기하거나 직접 생성 시도
|
||||
|
||||
# 탭(페이지) 확보
|
||||
page = None
|
||||
for attempt in range(5):
|
||||
try:
|
||||
if browser.tabs:
|
||||
page = browser.tabs[0]
|
||||
log_debug(f"[ZendriverDaemon] Using existing tab (Attempt {attempt+1})")
|
||||
break
|
||||
else:
|
||||
log_debug(f"[ZendriverDaemon] No tabs found, trying browser.get('about:blank') (Attempt {attempt+1})")
|
||||
page = await browser.get("about:blank")
|
||||
break
|
||||
except (StopIteration, RuntimeError, Exception) as tab_e:
|
||||
log_debug(f"[ZendriverDaemon] Tab acquisition failed: {tab_e}. Retrying...")
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
if not page:
|
||||
result["error"] = "Failed to acquire browser tab"
|
||||
return result
|
||||
|
||||
# 헤더 설정 (CDP 사용)
|
||||
if headers:
|
||||
@@ -371,9 +426,15 @@ async def fetch_with_browser(url: str, timeout: int = 30, headers: Optional[Dict
|
||||
})
|
||||
log_debug(f"[ZendriverDaemon] Success in {total_elapsed:.2f}s (Nav: {nav_elapsed:.2f}s, Poll: {poll_elapsed:.2f}s, Length: {len(html_content)})")
|
||||
else:
|
||||
result["error"] = f"Short response: {len(html_content) if html_content else 0} bytes"
|
||||
length = len(html_content) if html_content else 0
|
||||
result["error"] = f"Short response: {length} bytes"
|
||||
result["elapsed"] = round(total_elapsed, 2)
|
||||
log_debug(f"[ZendriverDaemon] Fetch failure: Short response ({len(html_content) if html_content else 0} bytes)")
|
||||
log_debug(f"[ZendriverDaemon] Fetch failure: Short response ({length} bytes)")
|
||||
|
||||
# 0바이트거나 너무 짧으면 브라우저/렌더러가 죽었을 가능성이 큼 -> 다음 번엔 강제 재시작
|
||||
if length < 100:
|
||||
log_debug("[ZendriverDaemon] Response extremely short, forcing browser reset for next request")
|
||||
browser = None
|
||||
|
||||
# 탭 정리: 닫지 말고 about:blank로 리셋 (최소 1개 탭 유지 필요)
|
||||
if page:
|
||||
|
||||
434
mod_anilife.py
434
mod_anilife.py
@@ -216,19 +216,58 @@ class LogicAniLife(AnimeModuleBase):
|
||||
def process_command(self, command, arg1, arg2, arg3, req):
|
||||
try:
|
||||
if command == "list":
|
||||
# 1. 자체 큐 목록 가져오기
|
||||
ret = self.queue.get_entity_list() if self.queue else []
|
||||
|
||||
# 2. GDM 태스크 가져오기 (설치된 경우)
|
||||
try:
|
||||
from gommi_downloader_manager.mod_queue import ModuleQueue
|
||||
if ModuleQueue:
|
||||
gdm_tasks = ModuleQueue.get_all_downloads()
|
||||
# 이 모듈(anilife)이 추가한 작업만 필터링
|
||||
anilife_tasks = [t for t in gdm_tasks if t.caller_plugin == f"{P.package_name}_{self.name}"]
|
||||
|
||||
for task in anilife_tasks:
|
||||
# 템플릿 호환 형식으로 변환
|
||||
gdm_item = self._convert_gdm_task_to_queue_item(task)
|
||||
ret.append(gdm_item)
|
||||
except Exception as e:
|
||||
logger.debug(f"GDM tasks fetch error: {e}")
|
||||
|
||||
return jsonify(ret)
|
||||
elif command == "stop":
|
||||
entity_id = int(arg1) if arg1 else -1
|
||||
result = self.queue.command("cancel", entity_id) if self.queue else {"ret": "error"}
|
||||
return jsonify(result)
|
||||
elif command == "remove":
|
||||
entity_id = int(arg1) if arg1 else -1
|
||||
result = self.queue.command("remove", entity_id) if self.queue else {"ret": "error"}
|
||||
return jsonify(result)
|
||||
elif command in ["reset", "delete_completed"]:
|
||||
result = self.queue.command(command, 0) if self.queue else {"ret": "error"}
|
||||
|
||||
elif command in ["stop", "remove", "cancel"]:
|
||||
entity_id = arg1
|
||||
if entity_id and str(entity_id).startswith("dl_"):
|
||||
# GDM 작업 처리
|
||||
try:
|
||||
from gommi_downloader_manager.mod_queue import ModuleQueue
|
||||
if ModuleQueue:
|
||||
if command == "stop" or command == "cancel":
|
||||
task = ModuleQueue.get_download(entity_id)
|
||||
if task:
|
||||
task.cancel()
|
||||
return jsonify({"ret": "success", "log": "GDM 작업을 중지하였습니다."})
|
||||
elif command == "remove" or command == "delete":
|
||||
# GDM에서 삭제 처리
|
||||
class DummyReq:
|
||||
def __init__(self, id):
|
||||
self.form = {"id": id}
|
||||
ModuleQueue.process_ajax("delete", DummyReq(entity_id))
|
||||
return jsonify({"ret": "success", "log": "GDM 작업을 삭제하였습니다."})
|
||||
except Exception as e:
|
||||
logger.error(f"GDM command error: {e}")
|
||||
return jsonify({"ret": "error", "log": f"GDM 명령 실패: {e}"})
|
||||
|
||||
# 자체 큐 처리
|
||||
entity_id = int(arg1) if arg1 and str(arg1).isdigit() else -1
|
||||
command_to_call = "cancel" if command == "stop" else command
|
||||
if self.queue:
|
||||
result = self.queue.command(command_to_call, entity_id)
|
||||
else:
|
||||
result = {"ret": "error", "log": "Queue not initialized"}
|
||||
return jsonify(result)
|
||||
|
||||
elif command == "merge_subtitle":
|
||||
# AniUtil already imported at module level
|
||||
db_id = int(arg1)
|
||||
@@ -248,6 +287,78 @@ class LogicAniLife(AnimeModuleBase):
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
return jsonify({'ret': 'fail', 'log': str(e)})
|
||||
|
||||
def _convert_gdm_task_to_queue_item(self, task):
|
||||
"""GDM DownloadTask 객체를 FfmpegQueueEntity.as_dict() 호환 형식으로 변환"""
|
||||
status_kor_map = {
|
||||
"pending": "대기중",
|
||||
"extracting": "분석중",
|
||||
"downloading": "다운로드중",
|
||||
"paused": "일시정지",
|
||||
"completed": "완료",
|
||||
"error": "실패",
|
||||
"cancelled": "취소됨"
|
||||
}
|
||||
|
||||
status_str_map = {
|
||||
"pending": "WAITING",
|
||||
"extracting": "ANALYZING",
|
||||
"downloading": "DOWNLOADING",
|
||||
"paused": "PAUSED",
|
||||
"completed": "COMPLETED",
|
||||
"error": "FAILED",
|
||||
"cancelled": "FAILED"
|
||||
}
|
||||
|
||||
t_dict = task.as_dict()
|
||||
|
||||
return {
|
||||
"entity_id": t_dict["id"],
|
||||
"url": t_dict["url"],
|
||||
"filename": t_dict["filename"] or t_dict["title"],
|
||||
"status_kor": status_kor_map.get(t_dict["status"], "알수없음"),
|
||||
"percent": t_dict["progress"],
|
||||
"created_time": t_dict["created_time"],
|
||||
"current_speed": t_dict["speed"] or "0 B/s",
|
||||
"download_time": t_dict["eta"] or "-",
|
||||
"status_str": status_str_map.get(t_dict["status"], "WAITING"),
|
||||
"idx": t_dict["id"],
|
||||
"callback_id": "anilife",
|
||||
"start_time": t_dict["start_time"] or t_dict["created_time"],
|
||||
"save_fullpath": t_dict["filepath"],
|
||||
"duration_str": "GDM",
|
||||
"current_pf_count": 0,
|
||||
"duration": "-",
|
||||
"current_duration": "-",
|
||||
"current_bitrate": "-",
|
||||
"max_pf_count": 0,
|
||||
"is_gdm": True
|
||||
}
|
||||
|
||||
def plugin_callback(self, data):
|
||||
"""GDM 모듈로부터 다운로드 상태 업데이트 수신"""
|
||||
try:
|
||||
callback_id = data.get('callback_id')
|
||||
status = data.get('status')
|
||||
|
||||
logger.info(f"[AniLife] Received GDM callback: id={callback_id}, status={status}")
|
||||
|
||||
if callback_id:
|
||||
from framework import F
|
||||
with F.app.app_context():
|
||||
db_item = ModelAniLifeItem.get_by_anilife_id(callback_id)
|
||||
if db_item:
|
||||
if status == "completed":
|
||||
db_item.status = "completed"
|
||||
db_item.completed_time = datetime.now()
|
||||
db_item.filepath = data.get('filepath')
|
||||
db_item.save()
|
||||
logger.info(f"[AniLife] Updated DB item {db_item.id} to COMPLETED via GDM callback")
|
||||
elif status == "error":
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.error(f"[AniLife] Callback processing error: {e}")
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
# @staticmethod
|
||||
def get_html(
|
||||
self,
|
||||
@@ -971,6 +1082,35 @@ class LogicAniLife(AnimeModuleBase):
|
||||
logger.error(f"reset_db error: {e}")
|
||||
return jsonify({"ret": "error", "msg": str(e)})
|
||||
|
||||
elif sub == "add_schedule":
|
||||
# 스케쥴 등록 (자동 다운로드 목록에 코드 추가)
|
||||
try:
|
||||
code = request.form.get("code", "")
|
||||
title = request.form.get("title", "")
|
||||
logger.debug(f"add_schedule: code={code}, title={title}")
|
||||
|
||||
if not code:
|
||||
return jsonify({"ret": "error", "msg": "코드가 없습니다."})
|
||||
|
||||
# 기존 whitelist 가져오기
|
||||
whitelist = P.ModelSetting.get("anilife_auto_code_list") or ""
|
||||
code_list = [c.strip() for c in whitelist.replace("\n", "|").split("|") if c.strip()]
|
||||
|
||||
if code in code_list:
|
||||
return jsonify({"ret": "exist", "msg": "이미 등록되어 있습니다."})
|
||||
|
||||
# 코드 추가
|
||||
code_list.append(code)
|
||||
new_whitelist = "|".join(code_list)
|
||||
P.ModelSetting.set("anilife_auto_code_list", new_whitelist)
|
||||
|
||||
logger.info(f"[Anilife] Schedule added: {code} ({title})")
|
||||
return jsonify({"ret": "success", "msg": f"스케쥴 등록 완료: {title}"})
|
||||
except Exception as e:
|
||||
logger.error(f"add_schedule error: {e}")
|
||||
logger.error(traceback.format_exc())
|
||||
return jsonify({"ret": "error", "msg": str(e)})
|
||||
|
||||
# Fallback to base class for common subs (queue_command, entity_list, browse_dir, command, etc.)
|
||||
return super().process_ajax(sub, req)
|
||||
|
||||
@@ -1087,12 +1227,73 @@ class LogicAniLife(AnimeModuleBase):
|
||||
return False
|
||||
|
||||
def scheduler_function(self):
|
||||
logger.debug(f"ohli24 scheduler_function::=========================")
|
||||
|
||||
content_code_list = P.ModelSetting.get_list("anilife_auto_code_list", "|")
|
||||
url = f'{P.ModelSetting.get("anilife_url")}/dailyani'
|
||||
if "all" in content_code_list:
|
||||
ret_data = LogicAniLife.get_auto_anime_info(self, url=url)
|
||||
"""스케줄러 함수 - anilife 자동 다운로드 처리"""
|
||||
logger.info("anilife scheduler_function::=========================")
|
||||
|
||||
try:
|
||||
content_code_list = P.ModelSetting.get_list("anilife_auto_code_list", "|")
|
||||
auto_mode_all = P.ModelSetting.get_bool("anilife_auto_mode_all")
|
||||
|
||||
logger.info(f"Auto-download codes: {content_code_list}")
|
||||
logger.info(f"Auto mode all episodes: {auto_mode_all}")
|
||||
|
||||
if not content_code_list:
|
||||
logger.info("[Scheduler] No auto-download codes configured")
|
||||
return
|
||||
|
||||
# 각 작품 코드별 처리
|
||||
for code in content_code_list:
|
||||
code = code.strip()
|
||||
if not code:
|
||||
continue
|
||||
|
||||
if code.lower() == "all":
|
||||
# TODO: 전체 최신 에피소드 스캔 로직 (추후 구현)
|
||||
logger.info("[Scheduler] 'all' mode - skipping for now")
|
||||
continue
|
||||
|
||||
logger.info(f"[Scheduler] Processing code: {code}")
|
||||
|
||||
try:
|
||||
# 작품 정보 조회
|
||||
series_info = self.get_series_info(code)
|
||||
|
||||
if not series_info or "episode" not in series_info:
|
||||
logger.warning(f"[Scheduler] No episode info for: {code}")
|
||||
continue
|
||||
|
||||
episodes = series_info.get("episode", [])
|
||||
logger.info(f"[Scheduler] Found {len(episodes)} episodes for: {series_info.get('title', code)}")
|
||||
|
||||
# 에피소드 순회 및 자동 등록
|
||||
added_count = 0
|
||||
for episode_info in episodes:
|
||||
try:
|
||||
result = self.add(episode_info)
|
||||
if result and result.startswith("enqueue"):
|
||||
added_count += 1
|
||||
logger.info(f"[Scheduler] Auto-enqueued: {episode_info.get('title', 'Unknown')}")
|
||||
self.socketio_callback("list_refresh", "")
|
||||
|
||||
# auto_mode_all이 False면 최신 1개만 (리스트가 최신순이라고 가정)
|
||||
if not auto_mode_all and added_count > 0:
|
||||
logger.info(f"[Scheduler] Auto mode: latest only - stopping after 1 episode")
|
||||
break
|
||||
|
||||
except Exception as ep_err:
|
||||
logger.error(f"[Scheduler] Episode add error: {ep_err}")
|
||||
continue
|
||||
|
||||
logger.info(f"[Scheduler] Completed {code}: added {added_count} episodes")
|
||||
|
||||
except Exception as code_err:
|
||||
logger.error(f"[Scheduler] Error processing {code}: {code_err}")
|
||||
logger.error(traceback.format_exc())
|
||||
continue
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[Scheduler] Fatal error: {e}")
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
def reset_db(self):
|
||||
db.session.query(ModelAniLifeItem).delete()
|
||||
@@ -2027,7 +2228,7 @@ class AniLifeQueueEntity(FfmpegQueueEntity):
|
||||
|
||||
class ModelAniLifeItem(db.Model):
|
||||
__tablename__ = "{package_name}_anilife_item".format(package_name=P.package_name)
|
||||
__table_args__ = {"mysql_collate": "utf8_general_ci"}
|
||||
__table_args__ = {"mysql_collate": "utf8_general_ci", "extend_existing": True}
|
||||
__bind_key__ = P.package_name
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
created_time = db.Column(db.DateTime)
|
||||
@@ -2073,118 +2274,137 @@ class ModelAniLifeItem(db.Model):
|
||||
return ret
|
||||
|
||||
def save(self):
|
||||
db.session.add(self)
|
||||
db.session.commit()
|
||||
from framework import F
|
||||
with F.app.app_context():
|
||||
db.session.add(self)
|
||||
db.session.commit()
|
||||
|
||||
@classmethod
|
||||
def get_by_id(cls, idx):
|
||||
return db.session.query(cls).filter_by(id=idx).first()
|
||||
from framework import F
|
||||
with F.app.app_context():
|
||||
return db.session.query(cls).filter_by(id=idx).first()
|
||||
|
||||
@classmethod
|
||||
def get_by_anilife_id(cls, anilife_id):
|
||||
return db.session.query(cls).filter_by(anilife_id=anilife_id).first()
|
||||
from framework import F
|
||||
with F.app.app_context():
|
||||
return db.session.query(cls).filter_by(anilife_id=anilife_id).first()
|
||||
|
||||
@classmethod
|
||||
def delete_by_id(cls, idx):
|
||||
try:
|
||||
logger.debug(f"delete_by_id: {idx} (type: {type(idx)})")
|
||||
if isinstance(idx, str) and ',' in idx:
|
||||
id_list = [int(x.strip()) for x in idx.split(',') if x.strip()]
|
||||
logger.debug(f"Batch delete: {id_list}")
|
||||
count = db.session.query(cls).filter(cls.id.in_(id_list)).delete(synchronize_session='fetch')
|
||||
logger.debug(f"Deleted count: {count}")
|
||||
else:
|
||||
db.session.query(cls).filter_by(id=int(idx)).delete()
|
||||
logger.debug(f"Single delete: {idx}")
|
||||
db.session.commit()
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Exception: {str(e)}")
|
||||
logger.error(traceback.format_exc())
|
||||
return False
|
||||
from framework import F
|
||||
with F.app.app_context():
|
||||
try:
|
||||
logger.debug(f"delete_by_id: {idx} (type: {type(idx)})")
|
||||
if isinstance(idx, str) and ',' in idx:
|
||||
id_list = [int(x.strip()) for x in idx.split(',') if x.strip()]
|
||||
logger.debug(f"Batch delete: {id_list}")
|
||||
count = db.session.query(cls).filter(cls.id.in_(id_list)).delete(synchronize_session='fetch')
|
||||
logger.debug(f"Deleted count: {count}")
|
||||
else:
|
||||
db.session.query(cls).filter_by(id=int(idx)).delete()
|
||||
logger.debug(f"Single delete: {idx}")
|
||||
db.session.commit()
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Exception: {str(e)}")
|
||||
# logger.error(traceback.format_exc())
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def delete_all(cls):
|
||||
try:
|
||||
db.session.query(cls).delete()
|
||||
db.session.commit()
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Exception: {str(e)}")
|
||||
logger.error(traceback.format_exc())
|
||||
return False
|
||||
from framework import F
|
||||
with F.app.app_context():
|
||||
try:
|
||||
db.session.query(cls).delete()
|
||||
db.session.commit()
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Exception: {str(e)}")
|
||||
# logger.error(traceback.format_exc())
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def web_list(cls, req):
|
||||
ret = {}
|
||||
page = int(req.form["page"]) if "page" in req.form else 1
|
||||
page_size = 30
|
||||
job_id = ""
|
||||
search = req.form["search_word"] if "search_word" in req.form else ""
|
||||
option = req.form["option"] if "option" in req.form else "all"
|
||||
order = req.form["order"] if "order" in req.form else "desc"
|
||||
query = cls.make_query(search=search, order=order, option=option)
|
||||
count = query.count()
|
||||
query = query.limit(page_size).offset((page - 1) * page_size)
|
||||
lists = query.all()
|
||||
ret["list"] = [item.as_dict() for item in lists]
|
||||
ret["paging"] = Util.get_paging_info(count, page, page_size)
|
||||
return ret
|
||||
from framework import F
|
||||
with F.app.app_context():
|
||||
ret = {}
|
||||
page = int(req.form["page"]) if "page" in req.form else 1
|
||||
page_size = 30
|
||||
job_id = ""
|
||||
search = req.form["search_word"] if "search_word" in req.form else ""
|
||||
option = req.form["option"] if "option" in req.form else "all"
|
||||
order = req.form["order"] if "order" in req.form else "desc"
|
||||
query = cls.make_query(search=search, order=order, option=option)
|
||||
count = query.count()
|
||||
query = query.limit(page_size).offset((page - 1) * page_size)
|
||||
lists = query.all()
|
||||
ret["list"] = [item.as_dict() for item in lists]
|
||||
ret["paging"] = Util.get_paging_info(count, page, page_size)
|
||||
return ret
|
||||
|
||||
@classmethod
|
||||
def make_query(cls, search="", order="desc", option="all"):
|
||||
query = db.session.query(cls)
|
||||
if search is not None and search != "":
|
||||
if search.find("|") != -1:
|
||||
tmp = search.split("|")
|
||||
conditions = []
|
||||
for tt in tmp:
|
||||
if tt != "":
|
||||
conditions.append(cls.filename.like("%" + tt.strip() + "%"))
|
||||
query = query.filter(or_(*conditions))
|
||||
elif search.find(",") != -1:
|
||||
tmp = search.split(",")
|
||||
for tt in tmp:
|
||||
if tt != "":
|
||||
query = query.filter(cls.filename.like("%" + tt.strip() + "%"))
|
||||
else:
|
||||
query = query.filter(cls.filename.like("%" + search + "%"))
|
||||
if option == "completed":
|
||||
query = query.filter(cls.status == "completed")
|
||||
from framework import F
|
||||
with F.app.app_context():
|
||||
query = db.session.query(cls)
|
||||
if search is not None and search != "":
|
||||
if search.find("|") != -1:
|
||||
tmp = search.split("|")
|
||||
conditions = []
|
||||
for tt in tmp:
|
||||
if tt != "":
|
||||
conditions.append(cls.filename.like("%" + tt.strip() + "%"))
|
||||
query = query.filter(or_(*conditions))
|
||||
elif search.find(",") != -1:
|
||||
tmp = search.split(",")
|
||||
for tt in tmp:
|
||||
if tt != "":
|
||||
query = query.filter(cls.filename.like("%" + tt.strip() + "%"))
|
||||
else:
|
||||
query = query.filter(cls.filename.like("%" + search + "%"))
|
||||
if option == "completed":
|
||||
query = query.filter(cls.status == "completed")
|
||||
|
||||
query = (
|
||||
query.order_by(desc(cls.id)) if order == "desc" else query.order_by(cls.id)
|
||||
)
|
||||
return query
|
||||
query = (
|
||||
query.order_by(desc(cls.id)) if order == "desc" else query.order_by(cls.id)
|
||||
)
|
||||
return query
|
||||
|
||||
@classmethod
|
||||
def get_list_uncompleted(cls):
|
||||
return db.session.query(cls).filter(cls.status != "completed").all()
|
||||
from framework import F
|
||||
with F.app.app_context():
|
||||
return db.session.query(cls).filter(cls.status != "completed").all()
|
||||
|
||||
@classmethod
|
||||
def append(cls, q):
|
||||
# 중복 체크
|
||||
existing = cls.get_by_anilife_id(q["_id"])
|
||||
if existing:
|
||||
logger.debug(f"Item already exists in DB: {q['_id']}")
|
||||
return existing
|
||||
|
||||
item = ModelAniLifeItem()
|
||||
item.content_code = q["content_code"]
|
||||
item.season = q["season"]
|
||||
item.episode_no = q.get("epi_queue")
|
||||
item.title = q["content_title"]
|
||||
item.episode_title = q["title"]
|
||||
item.anilife_va = q.get("va")
|
||||
item.anilife_vi = q.get("_vi")
|
||||
item.anilife_id = q["_id"]
|
||||
item.quality = q["quality"]
|
||||
item.filepath = q.get("filepath")
|
||||
item.filename = q.get("filename")
|
||||
item.savepath = q.get("savepath")
|
||||
item.video_url = q.get("url")
|
||||
item.vtt_url = q.get("vtt")
|
||||
item.thumbnail = q.get("thumbnail")
|
||||
item.status = "wait"
|
||||
item.anilife_info = q.get("anilife_info")
|
||||
item.save()
|
||||
from framework import F
|
||||
with F.app.app_context():
|
||||
# 중복 체크
|
||||
existing = cls.get_by_anilife_id(q["_id"])
|
||||
if existing:
|
||||
logger.debug(f"Item already exists in DB: {q['_id']}")
|
||||
return existing
|
||||
|
||||
item = ModelAniLifeItem()
|
||||
item.content_code = q["content_code"]
|
||||
item.season = q["season"]
|
||||
item.episode_no = q.get("epi_queue")
|
||||
item.title = q["content_title"]
|
||||
item.episode_title = q["title"]
|
||||
item.anilife_va = q.get("va")
|
||||
item.anilife_vi = q.get("_vi")
|
||||
item.anilife_id = q["_id"]
|
||||
item.quality = q["quality"]
|
||||
item.filepath = q.get("filepath")
|
||||
item.filename = q.get("filename")
|
||||
item.savepath = q.get("savepath")
|
||||
item.video_url = q.get("url")
|
||||
item.vtt_url = q.get("vtt")
|
||||
item.thumbnail = q.get("image", "")
|
||||
item.status = "wait"
|
||||
item.anilife_info = q["anilife_info"]
|
||||
item.save()
|
||||
return item
|
||||
|
||||
155
mod_base.py
155
mod_base.py
@@ -5,6 +5,10 @@ import os, traceback, time, json
|
||||
from datetime import datetime
|
||||
|
||||
class AnimeModuleBase(PluginModuleBase):
|
||||
# 업데이트 체크 캐싱 (클래스 레벨)
|
||||
_last_update_check = 0
|
||||
_latest_version = None
|
||||
|
||||
def __init__(self, P, setup_default=None, **kwargs):
|
||||
super(AnimeModuleBase, self).__init__(P, **kwargs)
|
||||
self.P = P # Ensure P is available via self.P
|
||||
@@ -131,6 +135,59 @@ class AnimeModuleBase(PluginModuleBase):
|
||||
arg3 = request.form.get('arg3') or request.args.get('arg3')
|
||||
return self.process_command(command, arg1, arg2, arg3, req)
|
||||
|
||||
elif sub == 'self_update':
|
||||
# 자가 업데이트 (Git Pull) 및 모듈 리로드
|
||||
try:
|
||||
import subprocess
|
||||
plugin_path = os.path.dirname(__file__)
|
||||
self.P.logger.info(f"애니 다운로더 자가 업데이트 시작: {plugin_path}")
|
||||
|
||||
# 먼저 변경될 파일 목록 확인 (model 파일 변경 감지)
|
||||
diff_cmd = ['git', '-C', plugin_path, 'diff', '--name-only', 'HEAD', 'origin/main']
|
||||
subprocess.run(['git', '-C', plugin_path, 'fetch'], capture_output=True) # fetch first
|
||||
diff_result = subprocess.run(diff_cmd, capture_output=True, text=True)
|
||||
changed_files = diff_result.stdout.strip().split('\n') if diff_result.stdout.strip() else []
|
||||
|
||||
# 모델 파일 변경 여부 확인
|
||||
model_patterns = ['model', 'db', 'migration']
|
||||
needs_restart = any(
|
||||
any(pattern in f.lower() for pattern in model_patterns)
|
||||
for f in changed_files if f
|
||||
)
|
||||
|
||||
# Git Pull 실행
|
||||
cmd = ['git', '-C', plugin_path, 'pull']
|
||||
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
stdout, stderr = process.communicate()
|
||||
|
||||
if process.returncode != 0:
|
||||
raise Exception(f"Git pull 실패: {stderr}")
|
||||
|
||||
self.P.logger.info(f"Git pull 결과: {stdout}")
|
||||
|
||||
# 모델 변경 없으면 리로드 시도
|
||||
if not needs_restart:
|
||||
self.reload_plugin()
|
||||
msg = f"업데이트 완료! 새로고침하세요.<br><pre>{stdout}</pre>"
|
||||
else:
|
||||
self.P.logger.warning("모델 파일 변경 감지 - 서버 재시작 필요")
|
||||
msg = f"<strong>모델 변경 감지!</strong> 서버 재시작이 필요합니다.<br><pre>{stdout}</pre>"
|
||||
|
||||
return jsonify({
|
||||
'ret': 'success',
|
||||
'msg': msg,
|
||||
'data': stdout,
|
||||
'needs_restart': needs_restart
|
||||
})
|
||||
except Exception as e:
|
||||
self.P.logger.error(f"자가 업데이트 중 오류: {str(e)}")
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
return jsonify({'ret': 'danger', 'msg': f"업데이트 실패: {str(e)}"})
|
||||
|
||||
elif sub == 'check_update':
|
||||
force = req.form.get('force') == 'true'
|
||||
return jsonify({'ret': 'success', 'data': self.get_update_info(force=force)})
|
||||
|
||||
return jsonify({'ret': 'fail', 'log': f"Unknown sub: {sub}"})
|
||||
|
||||
except Exception as e:
|
||||
@@ -198,3 +255,101 @@ class AnimeModuleBase(PluginModuleBase):
|
||||
except Exception as e:
|
||||
return {'ret': 'fail', 'msg': str(e)}
|
||||
|
||||
def get_update_info(self, force=False):
|
||||
"""GitHub에서 최신 버전 정보 가져오기 (캐싱 활용)"""
|
||||
import requests
|
||||
now = time.time()
|
||||
|
||||
# 실제 로컬 파일에서 현재 버전 읽기
|
||||
current_version = self.P.plugin_info.get('version', '0.0.0')
|
||||
try:
|
||||
info_path = os.path.join(os.path.dirname(__file__), 'info.yaml')
|
||||
if os.path.exists(info_path):
|
||||
import yaml
|
||||
with open(info_path, 'r', encoding='utf-8') as f:
|
||||
local_info = yaml.safe_load(f)
|
||||
current_version = str(local_info.get('version', current_version))
|
||||
except: pass
|
||||
|
||||
# 1시간마다 체크 (force=True면 즉시)
|
||||
if not force and AnimeModuleBase._latest_version and (now - AnimeModuleBase._last_update_check < 3600):
|
||||
return {
|
||||
'current': current_version,
|
||||
'latest': AnimeModuleBase._latest_version,
|
||||
'has_update': self._is_newer(AnimeModuleBase._latest_version, current_version)
|
||||
}
|
||||
|
||||
try:
|
||||
url = "https://raw.githubusercontent.com/projectdx75/anime_downloader/master/info.yaml"
|
||||
res = requests.get(url, timeout=5)
|
||||
if res.status_code == 200:
|
||||
import yaml
|
||||
data = yaml.safe_load(res.text)
|
||||
AnimeModuleBase._latest_version = str(data.get('version', ''))
|
||||
AnimeModuleBase._last_update_check = now
|
||||
|
||||
return {
|
||||
'current': current_version,
|
||||
'latest': AnimeModuleBase._latest_version,
|
||||
'has_update': self._is_newer(AnimeModuleBase._latest_version, current_version)
|
||||
}
|
||||
except Exception as e:
|
||||
self.P.logger.error(f"Update check failed: {e}")
|
||||
|
||||
return {
|
||||
'current': current_version,
|
||||
'latest': AnimeModuleBase._latest_version or current_version,
|
||||
'has_update': False
|
||||
}
|
||||
|
||||
def _is_newer(self, latest, current):
|
||||
"""버전 비교 (0.7.8 vs 0.7.7)"""
|
||||
if not latest or not current: return False
|
||||
try:
|
||||
l_parts = [int(p) for p in latest.split('.')]
|
||||
c_parts = [int(p) for p in current.split('.')]
|
||||
return l_parts > c_parts
|
||||
except:
|
||||
return latest != current
|
||||
|
||||
def reload_plugin(self):
|
||||
"""플러그인 모듈 핫 리로드"""
|
||||
import sys
|
||||
import importlib
|
||||
|
||||
try:
|
||||
package_name = self.P.package_name
|
||||
self.P.logger.info(f"플러그인 리로드 시작: {package_name}")
|
||||
|
||||
# 리로드에서 제외할 패턴 (모델/DB 관련 - SQLAlchemy 충돌 방지)
|
||||
skip_patterns = ['model', 'db', 'migration', 'setup', 'create_plugin']
|
||||
|
||||
# 관련 모듈 찾기 및 리로드
|
||||
modules_to_reload = []
|
||||
for module_name in list(sys.modules.keys()):
|
||||
if module_name.startswith(package_name):
|
||||
# 모델 관련 모듈은 건너뛰기
|
||||
should_skip = any(pattern in module_name.lower() for pattern in skip_patterns)
|
||||
if not should_skip:
|
||||
modules_to_reload.append(module_name)
|
||||
|
||||
# 의존성 역순으로 정렬 (깊은 모듈 먼저)
|
||||
modules_to_reload.sort(key=lambda x: x.count('.'), reverse=True)
|
||||
|
||||
reloaded_count = 0
|
||||
for module_name in modules_to_reload:
|
||||
try:
|
||||
module = sys.modules[module_name]
|
||||
importlib.reload(module)
|
||||
self.P.logger.debug(f"Reloaded: {module_name}")
|
||||
reloaded_count += 1
|
||||
except Exception as e:
|
||||
self.P.logger.warning(f"Skip reload {module_name}: {e}")
|
||||
|
||||
self.P.logger.info(f"플러그인 [{package_name}] 리로드 완료: {reloaded_count}개 모듈")
|
||||
self.P.logger.info("템플릿/정적 파일은 새로고침 시 자동 적용됩니다.")
|
||||
return True
|
||||
except Exception as e:
|
||||
self.P.logger.error(f"모듈 리로드 중 실패: {str(e)}")
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
return False
|
||||
|
||||
662
mod_linkkf.py
662
mod_linkkf.py
@@ -107,9 +107,13 @@ class LogicLinkkf(AnimeModuleBase):
|
||||
"linkkf_uncompleted_auto_enqueue": "False",
|
||||
"linkkf_image_url_prefix_series": "",
|
||||
"linkkf_image_url_prefix_episode": "",
|
||||
"linkkf_discord_notify": "True",
|
||||
"linkkf_download_method": "ffmpeg", # ffmpeg, ytdlp, aria2c
|
||||
"linkkf_download_threads": "16", # yt-dlp/aria2c 병렬 쓰레드 수
|
||||
# 알림 설정
|
||||
"linkkf_notify_enabled": "False",
|
||||
"linkkf_discord_webhook_url": "",
|
||||
"linkkf_telegram_bot_token": "",
|
||||
"linkkf_telegram_chat_id": "",
|
||||
}
|
||||
# default_route_socketio(P, self)
|
||||
self.web_list_model = ModelLinkkfItem
|
||||
@@ -248,6 +252,69 @@ class LogicLinkkf(AnimeModuleBase):
|
||||
ret["ret"] = "error"
|
||||
ret["log"] = str(e)
|
||||
return jsonify(ret)
|
||||
elif sub == "add_sub_queue_checked_list":
|
||||
# 선택된 에피소드 자막만 일괄 다운로드 (백그라운드 스레드로 처리)
|
||||
import threading
|
||||
from flask import current_app
|
||||
|
||||
logger.info("========= add_sub_queue_checked_list START =========")
|
||||
ret = {"ret": "success", "message": "백그라운드에서 자막 다운로드 중..."}
|
||||
try:
|
||||
form_data = request.form.get("data")
|
||||
if not form_data:
|
||||
ret["ret"] = "error"
|
||||
ret["log"] = "No data received"
|
||||
return jsonify(ret)
|
||||
|
||||
episode_list = json.loads(form_data)
|
||||
logger.info(f"Received {len(episode_list)} episodes to download subtitles in background")
|
||||
|
||||
# Flask app 참조 저장
|
||||
app = current_app._get_current_object()
|
||||
|
||||
def download_subtitles_background(flask_app, episode_list):
|
||||
added = 0
|
||||
skipped = 0
|
||||
with flask_app.app_context():
|
||||
for episode_info in episode_list:
|
||||
try:
|
||||
# LinkkfQueueEntity를 사용하여 자막 URL 추출 (prepare_extra 활용)
|
||||
entity = LinkkfQueueEntity(P, self, episode_info)
|
||||
entity.prepare_extra()
|
||||
|
||||
if entity.vtt:
|
||||
# 자막 다운로드 및 변환
|
||||
# entity.filepath는 prepare_extra에서 설정됨 (기본 저장 경로 + 파일명)
|
||||
res = Util.download_subtitle(entity.vtt, entity.filepath, headers=entity.headers)
|
||||
if res:
|
||||
added += 1
|
||||
logger.debug(f"Downloaded subtitle for {episode_info.get('title')}")
|
||||
else:
|
||||
skipped += 1
|
||||
logger.info(f"Failed to download subtitle for {episode_info.get('title')}")
|
||||
else:
|
||||
skipped += 1
|
||||
logger.info(f"No subtitle found for {episode_info.get('title')}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error in download_subtitles_background for one episode: {e}")
|
||||
skipped += 1
|
||||
|
||||
logger.info(f"add_sub_queue_checked_list completed: downloaded={added}, skipped={skipped}")
|
||||
|
||||
thread = threading.Thread(
|
||||
target=download_subtitles_background,
|
||||
args=(app, episode_list)
|
||||
)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
ret["count"] = len(episode_list)
|
||||
except Exception as e:
|
||||
logger.error(f"add_sub_queue_checked_list error: {e}")
|
||||
logger.error(traceback.format_exc())
|
||||
ret["ret"] = "error"
|
||||
ret["log"] = str(e)
|
||||
return jsonify(ret)
|
||||
elif sub == "web_list":
|
||||
ret = ModelLinkkfItem.web_list(req)
|
||||
return jsonify(ret)
|
||||
@@ -470,6 +537,32 @@ class LogicLinkkf(AnimeModuleBase):
|
||||
logger.error(f"browse_dir error: {e}")
|
||||
return jsonify({"ret": "error", "error": str(e)}), 500
|
||||
|
||||
elif sub == "test_notification":
|
||||
# 테스트 알림 전송
|
||||
try:
|
||||
discord_url = P.ModelSetting.get("linkkf_discord_webhook_url")
|
||||
telegram_token = P.ModelSetting.get("linkkf_telegram_bot_token")
|
||||
telegram_chat_id = P.ModelSetting.get("linkkf_telegram_chat_id")
|
||||
|
||||
if not discord_url and not (telegram_token and telegram_chat_id):
|
||||
return jsonify({"ret": "error", "msg": "Discord Webhook URL 또는 Telegram 설정을 입력하세요."})
|
||||
|
||||
test_message = "🔔 **테스트 알림**\nLinkkf 알림 설정이 완료되었습니다!\n\n알림이 정상적으로 수신되고 있습니다."
|
||||
sent_to = []
|
||||
|
||||
if discord_url:
|
||||
self.send_discord_notification(discord_url, "테스트", test_message)
|
||||
sent_to.append("Discord")
|
||||
|
||||
if telegram_token and telegram_chat_id:
|
||||
self.send_telegram_notification(telegram_token, telegram_chat_id, test_message)
|
||||
sent_to.append("Telegram")
|
||||
|
||||
return jsonify({"ret": "success", "msg": f"{', '.join(sent_to)}으로 알림 전송 완료!"})
|
||||
except Exception as e:
|
||||
logger.error(f"test_notification error: {e}")
|
||||
return jsonify({"ret": "error", "msg": str(e)})
|
||||
|
||||
return super().process_ajax(sub, req)
|
||||
|
||||
except Exception as e:
|
||||
@@ -477,6 +570,153 @@ class LogicLinkkf(AnimeModuleBase):
|
||||
P.logger.error(traceback.format_exc())
|
||||
return jsonify({"ret": "error", "log": str(e)})
|
||||
|
||||
def process_command(self, command, arg1, arg2, arg3, req):
|
||||
try:
|
||||
if command == "list":
|
||||
# 1. 자체 큐 목록 가져오기
|
||||
ret = self.queue.get_entity_list() if self.queue else []
|
||||
|
||||
# 2. GDM 태스크 가져오기 (설치된 경우)
|
||||
try:
|
||||
from gommi_downloader_manager.mod_queue import ModuleQueue
|
||||
if ModuleQueue:
|
||||
gdm_tasks = ModuleQueue.get_all_downloads()
|
||||
# 이 모듈(linkkf)이 추가한 작업만 필터링
|
||||
linkkf_tasks = [t for t in gdm_tasks if t.caller_plugin == f"{P.package_name}_{self.name}"]
|
||||
|
||||
for task in linkkf_tasks:
|
||||
# 템플릿 호환 형식으로 변환
|
||||
gdm_item = self._convert_gdm_task_to_queue_item(task)
|
||||
ret.append(gdm_item)
|
||||
except Exception as e:
|
||||
logger.debug(f"GDM tasks fetch error: {e}")
|
||||
|
||||
return jsonify(ret)
|
||||
|
||||
elif command in ["stop", "remove", "cancel"]:
|
||||
entity_id = arg1
|
||||
if entity_id and str(entity_id).startswith("dl_"):
|
||||
# GDM 작업 처리
|
||||
try:
|
||||
from gommi_downloader_manager.mod_queue import ModuleQueue
|
||||
if ModuleQueue:
|
||||
if command == "stop" or command == "cancel":
|
||||
task = ModuleQueue.get_download(entity_id)
|
||||
if task:
|
||||
task.cancel()
|
||||
return jsonify({"ret": "success", "log": "GDM 작업을 중지하였습니다."})
|
||||
elif command == "remove":
|
||||
# GDM에서 삭제 처리 (명령어 'delete' 사용)
|
||||
# process_ajax의 delete 로직 참고
|
||||
class DummyReq:
|
||||
def __init__(self, id):
|
||||
self.form = {"id": id}
|
||||
ModuleQueue.process_ajax("delete", DummyReq(entity_id))
|
||||
return jsonify({"ret": "success", "log": "GDM 작업을 삭제하였습니다."})
|
||||
except Exception as e:
|
||||
logger.error(f"GDM command error: {e}")
|
||||
return jsonify({"ret": "error", "log": f"GDM 명령 실패: {e}"})
|
||||
|
||||
# 자체 큐 처리
|
||||
return super().process_command(command, arg1, arg2, arg3, req)
|
||||
|
||||
return super().process_command(command, arg1, arg2, arg3, req)
|
||||
except Exception as e:
|
||||
logger.error(f"process_command Error: {e}")
|
||||
logger.error(traceback.format_exc())
|
||||
return jsonify({'ret': 'fail', 'log': str(e)})
|
||||
|
||||
def _convert_gdm_task_to_queue_item(self, task):
|
||||
"""GDM DownloadTask 객체를 FfmpegQueueEntity.as_dict() 호환 형식으로 변환"""
|
||||
# 상태 맵핑
|
||||
status_kor_map = {
|
||||
"pending": "대기중",
|
||||
"extracting": "분석중",
|
||||
"downloading": "다운로드중",
|
||||
"paused": "일시정지",
|
||||
"completed": "완료",
|
||||
"error": "실패",
|
||||
"cancelled": "취소됨"
|
||||
}
|
||||
|
||||
status_str_map = {
|
||||
"pending": "WAITING",
|
||||
"extracting": "ANALYZING",
|
||||
"downloading": "DOWNLOADING",
|
||||
"paused": "PAUSED",
|
||||
"completed": "COMPLETED",
|
||||
"error": "FAILED",
|
||||
"cancelled": "FAILED"
|
||||
}
|
||||
|
||||
# GDM task는 as_dict()를 제공함
|
||||
t_dict = task.as_dict()
|
||||
|
||||
return {
|
||||
"entity_id": t_dict["id"],
|
||||
"url": t_dict["url"],
|
||||
"filename": t_dict["filename"] or t_dict["title"],
|
||||
"status_kor": status_kor_map.get(t_dict["status"], "알수없음"),
|
||||
"percent": t_dict["progress"],
|
||||
"created_time": t_dict["created_time"],
|
||||
"current_speed": t_dict["speed"] or "0 B/s",
|
||||
"download_time": t_dict["eta"] or "-",
|
||||
"status_str": status_str_map.get(t_dict["status"], "WAITING"),
|
||||
"idx": t_dict["id"],
|
||||
"callback_id": "linkkf",
|
||||
"start_time": t_dict["start_time"] or t_dict["created_time"],
|
||||
"save_fullpath": t_dict["filepath"],
|
||||
"duration_str": "GDM",
|
||||
"current_pf_count": 0,
|
||||
"duration": "-",
|
||||
"current_duration": "-",
|
||||
"current_bitrate": "-",
|
||||
"max_pf_count": 0,
|
||||
"is_gdm": True
|
||||
}
|
||||
|
||||
def plugin_callback(self, data):
|
||||
"""
|
||||
GDM 모듈로부터 다운로드 상태 업데이트 수신
|
||||
data = {
|
||||
'callback_id': self.callback_id,
|
||||
'status': self.status,
|
||||
'filepath': self.filepath,
|
||||
'filename': os.path.basename(self.filepath) if self.filepath else '',
|
||||
'error': self.error_message
|
||||
}
|
||||
"""
|
||||
try:
|
||||
callback_id = data.get('callback_id')
|
||||
status = data.get('status')
|
||||
|
||||
logger.info(f"[Linkkf] Received GDM callback: id={callback_id}, status={status}")
|
||||
|
||||
# DB 상태 업데이트
|
||||
if callback_id:
|
||||
from framework import F
|
||||
with F.app.app_context():
|
||||
db_item = ModelLinkkfItem.get_by_linkkf_id(callback_id)
|
||||
if db_item:
|
||||
if status == "completed":
|
||||
db_item.status = "completed"
|
||||
db_item.completed_time = datetime.now()
|
||||
# 경로 정규화 후 저장
|
||||
new_filepath = data.get('filepath')
|
||||
if new_filepath:
|
||||
db_item.filepath = os.path.normpath(new_filepath)
|
||||
db_item.save()
|
||||
logger.info(f"[Linkkf] Successfully updated DB item {db_item.id} (Linkkf ID: {callback_id}) to COMPLETED via GDM callback")
|
||||
logger.info(f"[Linkkf] Final filepath in DB: {db_item.filepath}")
|
||||
|
||||
# 알림 전송 (필요 시)
|
||||
# self.socketio_callback("list_refresh", "")
|
||||
elif status == "error":
|
||||
# 필요 시 에러 처리
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.error(f"[Linkkf] Callback processing error: {e}")
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
def socketio_callback(self, refresh_type, data):
|
||||
"""
|
||||
@@ -685,9 +925,9 @@ class LogicLinkkf(AnimeModuleBase):
|
||||
logger.info(f"Extracting video URL from: {playid_url}")
|
||||
|
||||
# Step 1: playid 페이지에서 iframe src 추출 (cloudscraper 사용)
|
||||
html_content = LogicLinkkf.get_html(playid_url)
|
||||
html_content = LogicLinkkf.get_html(playid_url, timeout=15)
|
||||
if not html_content:
|
||||
logger.error(f"Failed to fetch playid page: {playid_url}")
|
||||
logger.error(f"Failed to fetch playid page (Timeout or Error): {playid_url}")
|
||||
return None, None, None
|
||||
|
||||
soup = BeautifulSoup(html_content, "html.parser")
|
||||
@@ -719,9 +959,9 @@ class LogicLinkkf(AnimeModuleBase):
|
||||
logger.info(f"Found player iframe: {iframe_src}")
|
||||
|
||||
# Step 2: iframe 페이지에서 m3u8 URL과 vtt URL 추출
|
||||
iframe_content = LogicLinkkf.get_html(iframe_src)
|
||||
iframe_content = LogicLinkkf.get_html(iframe_src, timeout=15)
|
||||
if not iframe_content:
|
||||
logger.error(f"Failed to fetch iframe content: {iframe_src}")
|
||||
logger.error(f"Failed to fetch iframe content (Timeout or Error): {iframe_src}")
|
||||
return None, iframe_src, None
|
||||
|
||||
# m3u8 URL 패턴 찾기 (더 정밀하게)
|
||||
@@ -1454,14 +1694,14 @@ class LogicLinkkf(AnimeModuleBase):
|
||||
|
||||
if P.ModelSetting.get("linkkf_auto_make_folder") == "True":
|
||||
program_path = os.path.join(tmp_save_path, entity["save_folder"])
|
||||
entity["save_path"] = program_path
|
||||
entity["save_path"] = os.path.normpath(program_path)
|
||||
if P.ModelSetting.get("linkkf_auto_make_season_folder"):
|
||||
entity["save_path"] = os.path.join(
|
||||
entity["save_path"] = os.path.normpath(os.path.join(
|
||||
entity["save_path"], "Season %s" % int(entity["season"])
|
||||
)
|
||||
))
|
||||
else:
|
||||
# 기본 경로 설정
|
||||
entity["save_path"] = tmp_save_path
|
||||
entity["save_path"] = os.path.normpath(tmp_save_path)
|
||||
|
||||
entity["image"] = data["poster_url"]
|
||||
# filename 생성 시 숫자만 전달 ("01화" 아님)
|
||||
@@ -1470,7 +1710,7 @@ class LogicLinkkf(AnimeModuleBase):
|
||||
)
|
||||
|
||||
# Check for existing file (for Play button)
|
||||
entity["filepath"] = os.path.join(entity["save_path"], entity["filename"])
|
||||
entity["filepath"] = os.path.normpath(os.path.join(entity["save_path"], entity["filename"]))
|
||||
if os.path.exists(entity["filepath"]):
|
||||
entity["exist_video"] = True
|
||||
if "first_exist_filepath" not in data:
|
||||
@@ -1644,12 +1884,14 @@ class LogicLinkkf(AnimeModuleBase):
|
||||
|
||||
# 3. Early file existence check - filepath is already in episode_info from get_series_info
|
||||
filepath = episode_info.get("filepath")
|
||||
if filepath:
|
||||
filepath = os.path.normpath(filepath)
|
||||
|
||||
# 미완성 다운로드 감지 (Frag 파일, .ytdl 파일, .part 파일이 있으면 재다운로드 허용)
|
||||
has_incomplete_files = False
|
||||
if filepath:
|
||||
import glob
|
||||
dirname = os.path.dirname(filepath)
|
||||
dirname = os.path.normpath(os.path.dirname(filepath))
|
||||
has_ytdl = os.path.exists(filepath + ".ytdl")
|
||||
has_part = os.path.exists(filepath + ".part")
|
||||
has_frag = False
|
||||
@@ -1710,7 +1952,7 @@ class LogicLinkkf(AnimeModuleBase):
|
||||
# Prepare GDM options
|
||||
gdm_options = {
|
||||
"url": entity.url,
|
||||
"save_path": entity.savepath,
|
||||
"save_path": os.path.normpath(entity.savepath),
|
||||
"filename": entity.filename,
|
||||
"source_type": gdm_source_type,
|
||||
"caller_plugin": f"{P.package_name}_{self.name}",
|
||||
@@ -1724,7 +1966,7 @@ class LogicLinkkf(AnimeModuleBase):
|
||||
"source": "linkkf"
|
||||
},
|
||||
"headers": entity.headers,
|
||||
"subtitles": entity.vtt,
|
||||
"subtitles": getattr(entity, 'vtt', None),
|
||||
"connections": download_threads,
|
||||
}
|
||||
|
||||
@@ -1780,6 +2022,29 @@ class LogicLinkkf(AnimeModuleBase):
|
||||
def plugin_load(self):
|
||||
try:
|
||||
logger.debug("%s plugin_load", P.package_name)
|
||||
|
||||
# 새 설정 초기화 (기존 설치에서 누락된 설정 추가)
|
||||
new_settings = {
|
||||
"linkkf_notify_enabled": "False",
|
||||
"linkkf_discord_webhook_url": "",
|
||||
"linkkf_telegram_bot_token": "",
|
||||
"linkkf_telegram_chat_id": "",
|
||||
}
|
||||
for key, default_value in new_settings.items():
|
||||
if P.ModelSetting.get(key) is None:
|
||||
P.ModelSetting.set(key, default_value)
|
||||
logger.info(f"[Linkkf] Initialized new setting: {key}")
|
||||
|
||||
# 추가 설정: 자동 다운로드 vs 알림만
|
||||
if P.ModelSetting.get("linkkf_auto_download_new") is None:
|
||||
P.ModelSetting.set("linkkf_auto_download_new", "True")
|
||||
logger.info("[Linkkf] Initialized setting: linkkf_auto_download_new")
|
||||
|
||||
# 모니터링 주기 설정 (기본 10분)
|
||||
if P.ModelSetting.get("linkkf_monitor_interval") is None:
|
||||
P.ModelSetting.set("linkkf_monitor_interval", "10")
|
||||
logger.info("[Linkkf] Initialized setting: linkkf_monitor_interval")
|
||||
|
||||
# 클래스 레벨 큐 초기화
|
||||
if LogicLinkkf.queue is None:
|
||||
LogicLinkkf.queue = FfmpegQueue(
|
||||
@@ -1806,6 +2071,229 @@ class LogicLinkkf(AnimeModuleBase):
|
||||
def plugin_unload(self):
|
||||
pass
|
||||
|
||||
def scheduler_function(self):
|
||||
"""스케줄러 함수 - linkkf 자동 다운로드 처리"""
|
||||
from framework import F
|
||||
logger.info("linkkf scheduler_function::=========================")
|
||||
|
||||
# Flask 앱 컨텍스트 내에서 실행 (스케줄러는 별도 스레드)
|
||||
with F.app.app_context():
|
||||
try:
|
||||
content_code_list = P.ModelSetting.get_list("linkkf_auto_code_list", "|")
|
||||
auto_mode_all = P.ModelSetting.get_bool("linkkf_auto_mode_all")
|
||||
|
||||
logger.info(f"Auto-download codes: {content_code_list}")
|
||||
logger.info(f"Auto mode all episodes: {auto_mode_all}")
|
||||
|
||||
if not content_code_list:
|
||||
logger.info("[Scheduler] No auto-download codes configured")
|
||||
return
|
||||
|
||||
# 각 작품 코드별 처리
|
||||
for code in content_code_list:
|
||||
code = code.strip()
|
||||
if not code:
|
||||
continue
|
||||
|
||||
if code.lower() == "all":
|
||||
# 사이트 전체 최신 에피소드 스캔
|
||||
logger.info("[Scheduler] 'all' mode - scanning latest episodes from site")
|
||||
self.scan_latest_episodes(auto_mode_all)
|
||||
continue
|
||||
|
||||
logger.info(f"[Scheduler] Processing code: {code}")
|
||||
|
||||
try:
|
||||
# 작품 정보 조회
|
||||
series_info = self.get_series_info(code)
|
||||
|
||||
if not series_info or "episode" not in series_info:
|
||||
logger.warning(f"[Scheduler] No episode info for: {code}")
|
||||
continue
|
||||
|
||||
episodes = series_info.get("episode", [])
|
||||
logger.info(f"[Scheduler] Found {len(episodes)} episodes for: {series_info.get('title', code)}")
|
||||
|
||||
# 에피소드 순회 및 자동 등록
|
||||
added_count = 0
|
||||
added_episodes = []
|
||||
for episode_info in episodes:
|
||||
try:
|
||||
result = self.add(episode_info)
|
||||
if result and result.startswith("enqueue"):
|
||||
added_count += 1
|
||||
added_episodes.append(episode_info.get('title', 'Unknown'))
|
||||
logger.info(f"[Scheduler] Auto-enqueued: {episode_info.get('title', 'Unknown')}")
|
||||
self.socketio_callback("list_refresh", "")
|
||||
|
||||
# auto_mode_all이 False면 최신 1개만 (리스트가 최신순이라고 가정)
|
||||
if not auto_mode_all and added_count > 0:
|
||||
logger.info(f"[Scheduler] Auto mode: latest only - stopping after 1 episode")
|
||||
break
|
||||
|
||||
except Exception as ep_err:
|
||||
logger.error(f"[Scheduler] Episode add error: {ep_err}")
|
||||
continue
|
||||
|
||||
# 새 에피소드 추가됨 → 알림 전송
|
||||
if added_count > 0:
|
||||
self.send_notification(
|
||||
title=series_info.get('title', code),
|
||||
episodes=added_episodes,
|
||||
count=added_count
|
||||
)
|
||||
|
||||
logger.info(f"[Scheduler] Completed {code}: added {added_count} episodes")
|
||||
|
||||
except Exception as code_err:
|
||||
logger.error(f"[Scheduler] Error processing {code}: {code_err}")
|
||||
logger.error(traceback.format_exc())
|
||||
continue
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[Scheduler] Fatal error: {e}")
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
def send_notification(self, title, episodes, count):
|
||||
"""Discord/Telegram 알림 전송"""
|
||||
if not P.ModelSetting.get_bool("linkkf_notify_enabled"):
|
||||
return
|
||||
|
||||
# 메시지 생성
|
||||
episode_list = "\n".join([f"• {ep}" for ep in episodes[:5]])
|
||||
if count > 5:
|
||||
episode_list += f"\n... 외 {count - 5}개"
|
||||
|
||||
message = f"🎬 **{title}**\n새 에피소드 {count}개가 다운로드 큐에 추가되었습니다!\n\n{episode_list}"
|
||||
|
||||
# Discord Webhook
|
||||
discord_url = P.ModelSetting.get("linkkf_discord_webhook_url")
|
||||
if discord_url:
|
||||
self.send_discord_notification(discord_url, title, message)
|
||||
|
||||
# Telegram Bot
|
||||
telegram_token = P.ModelSetting.get("linkkf_telegram_bot_token")
|
||||
telegram_chat_id = P.ModelSetting.get("linkkf_telegram_chat_id")
|
||||
if telegram_token and telegram_chat_id:
|
||||
self.send_telegram_notification(telegram_token, telegram_chat_id, message)
|
||||
|
||||
def scan_latest_episodes(self, auto_mode_all):
|
||||
"""사이트에서 최신 에피소드 목록을 스캔하고 새 에피소드 감지"""
|
||||
try:
|
||||
auto_download = P.ModelSetting.get_bool("linkkf_auto_download_new")
|
||||
|
||||
# 최신 방영 목록 가져오기 (1페이지만 - 가장 최신)
|
||||
latest_data = self.get_anime_info("ing", 1)
|
||||
|
||||
if not latest_data or "episode" not in latest_data:
|
||||
logger.warning("[Scheduler] Failed to fetch latest anime list")
|
||||
return
|
||||
|
||||
items = latest_data.get("episode", [])
|
||||
logger.info(f"[Scheduler] Scanned {len(items)} items from 'ing' page")
|
||||
|
||||
total_added = 0
|
||||
all_new_episodes = []
|
||||
|
||||
# 각 작품의 최신 에피소드 확인
|
||||
for item in items[:20]: # 상위 20개만 처리 (성능 고려)
|
||||
try:
|
||||
code = item.get("code")
|
||||
if not code:
|
||||
continue
|
||||
|
||||
# 해당 작품의 에피소드 목록 조회
|
||||
series_info = self.get_series_info(code)
|
||||
if not series_info or "episode" not in series_info:
|
||||
continue
|
||||
|
||||
episodes = series_info.get("episode", [])
|
||||
series_title = series_info.get("title", code)
|
||||
|
||||
# 새 에피소드만 추가 (add 메서드가 중복 체크함)
|
||||
for ep in episodes[:5]: # 최신 5개만 확인
|
||||
try:
|
||||
if auto_download:
|
||||
result = self.add(ep)
|
||||
if result and result.startswith("enqueue"):
|
||||
total_added += 1
|
||||
all_new_episodes.append(f"{series_title} - {ep.get('title', '')}")
|
||||
self.socketio_callback("list_refresh", "")
|
||||
else:
|
||||
# 알림만 (다운로드 안함) - DB 체크로 새 에피소드인지 확인
|
||||
ep_code = ep.get("code", "")
|
||||
existing = ModelLinkkfItem.get_by_code(ep_code) if ep_code else None
|
||||
if not existing:
|
||||
all_new_episodes.append(f"{series_title} - {ep.get('title', '')}")
|
||||
|
||||
if not auto_mode_all and total_added > 0:
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
if not auto_mode_all and total_added > 0:
|
||||
break
|
||||
|
||||
except Exception as e:
|
||||
logger.debug(f"[Scheduler] Error scanning {item.get('code', 'unknown')}: {e}")
|
||||
continue
|
||||
|
||||
# 결과 알림
|
||||
if all_new_episodes:
|
||||
mode_text = "자동 다운로드" if auto_download else "새 에피소드 감지"
|
||||
self.send_notification(
|
||||
title=f"[{mode_text}] 사이트 모니터링",
|
||||
episodes=all_new_episodes,
|
||||
count=len(all_new_episodes)
|
||||
)
|
||||
logger.info(f"[Scheduler] 'all' mode completed: {len(all_new_episodes)} new episodes found")
|
||||
else:
|
||||
logger.info("[Scheduler] 'all' mode: No new episodes found")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[Scheduler] scan_latest_episodes error: {e}")
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
def send_discord_notification(self, webhook_url, title, message):
|
||||
"""Discord Webhook으로 알림 전송"""
|
||||
try:
|
||||
payload = {
|
||||
"embeds": [{
|
||||
"title": f"📺 Linkkf 자동 다운로드",
|
||||
"description": message,
|
||||
"color": 0x10B981, # 초록색
|
||||
"footer": {"text": "FlaskFarm Anime Downloader"}
|
||||
}]
|
||||
}
|
||||
response = requests.post(webhook_url, json=payload, timeout=10)
|
||||
if response.status_code in [200, 204]:
|
||||
logger.info(f"[Notify] Discord 알림 전송 성공: {title}")
|
||||
else:
|
||||
logger.warning(f"[Notify] Discord 알림 실패: {response.status_code}")
|
||||
except Exception as e:
|
||||
logger.error(f"[Notify] Discord 알림 오류: {e}")
|
||||
|
||||
def send_telegram_notification(self, bot_token, chat_id, message):
|
||||
"""Telegram Bot API로 알림 전송"""
|
||||
try:
|
||||
# Markdown 형식으로 변환 (** -> *)
|
||||
telegram_message = message.replace("**", "*")
|
||||
|
||||
url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
|
||||
payload = {
|
||||
"chat_id": chat_id,
|
||||
"text": telegram_message,
|
||||
"parse_mode": "Markdown"
|
||||
}
|
||||
response = requests.post(url, json=payload, timeout=10)
|
||||
result = response.json()
|
||||
if result.get("ok"):
|
||||
logger.info(f"[Notify] Telegram 알림 전송 성공")
|
||||
else:
|
||||
logger.warning(f"[Notify] Telegram 알림 실패: {result.get('description', 'Unknown')}")
|
||||
except Exception as e:
|
||||
logger.error(f"[Notify] Telegram 알림 오류: {e}")
|
||||
|
||||
def download_thread_function(self):
|
||||
while True:
|
||||
try:
|
||||
@@ -1856,13 +2344,13 @@ class LinkkfQueueEntity(FfmpegQueueEntity):
|
||||
|
||||
if default_path:
|
||||
save_folder = info.get("save_folder", "Unknown")
|
||||
self.savepath = os.path.join(default_path, save_folder)
|
||||
self.savepath = os.path.normpath(os.path.join(default_path, save_folder))
|
||||
else:
|
||||
self.savepath = "/tmp/anime_downloads"
|
||||
logger.info(f"[DEBUG] Final savepath set to: '{self.savepath}'")
|
||||
|
||||
# filepath = savepath + filename (전체 경로)
|
||||
self.filepath = os.path.join(self.savepath, self.filename) if self.filename else self.savepath
|
||||
self.filepath = os.path.normpath(os.path.join(self.savepath, self.filename)) if self.filename else self.savepath
|
||||
logger.info(f"[DEBUG] filepath set to: '{self.filepath}'")
|
||||
|
||||
# playid URL에서 실제 비디오 URL과 자막 URL 추출은 prepare_extra에서 수행합니다.
|
||||
@@ -2107,7 +2595,7 @@ class LinkkfQueueEntity(FfmpegQueueEntity):
|
||||
|
||||
class ModelLinkkfItem(db.Model):
|
||||
__tablename__ = "{package_name}_linkkf_item".format(package_name=P.package_name)
|
||||
__table_args__ = {"mysql_collate": "utf8_general_ci"}
|
||||
__table_args__ = {"mysql_collate": "utf8_general_ci", "extend_existing": True}
|
||||
__bind_key__ = P.package_name
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
created_time = db.Column(db.DateTime)
|
||||
@@ -2148,39 +2636,47 @@ class ModelLinkkfItem(db.Model):
|
||||
return ret
|
||||
|
||||
def save(self):
|
||||
db.session.add(self)
|
||||
db.session.commit()
|
||||
from framework import F
|
||||
with F.app.app_context():
|
||||
db.session.add(self)
|
||||
db.session.commit()
|
||||
|
||||
@classmethod
|
||||
def get_by_id(cls, idx):
|
||||
return db.session.query(cls).filter_by(id=idx).first()
|
||||
from framework import F
|
||||
with F.app.app_context():
|
||||
return db.session.query(cls).filter_by(id=idx).first()
|
||||
|
||||
@classmethod
|
||||
def get_by_linkkf_id(cls, linkkf_id):
|
||||
return db.session.query(cls).filter_by(linkkf_id=linkkf_id).first()
|
||||
from framework import F
|
||||
with F.app.app_context():
|
||||
return db.session.query(cls).filter_by(linkkf_id=linkkf_id).first()
|
||||
|
||||
@classmethod
|
||||
def append(cls, q):
|
||||
logger.debug(q)
|
||||
item = ModelLinkkfItem()
|
||||
item.content_code = q["program_code"]
|
||||
item.season = q["season"]
|
||||
item.episode_no = q["epi_queue"]
|
||||
item.title = q["content_title"]
|
||||
item.episode_title = q["title"]
|
||||
# item.linkkf_va = q["va"]
|
||||
item.linkkf_code = q["code"]
|
||||
item.linkkf_id = q["_id"]
|
||||
item.quality = q["quality"]
|
||||
item.filepath = q["filepath"]
|
||||
item.filename = q["filename"]
|
||||
item.savepath = q["savepath"]
|
||||
item.video_url = q["url"]
|
||||
item.vtt_url = q["vtt"]
|
||||
item.thumbnail = q.get("image", "")
|
||||
item.status = "wait"
|
||||
item.linkkf_info = q["linkkf_info"]
|
||||
item.save()
|
||||
from framework import F
|
||||
with F.app.app_context():
|
||||
logger.debug(q)
|
||||
item = ModelLinkkfItem()
|
||||
item.content_code = q["program_code"]
|
||||
item.season = q["season"]
|
||||
item.episode_no = q["epi_queue"]
|
||||
item.title = q["content_title"]
|
||||
item.episode_title = q["title"]
|
||||
# item.linkkf_va = q["va"]
|
||||
item.linkkf_code = q["code"]
|
||||
item.linkkf_id = q["_id"]
|
||||
item.quality = q["quality"]
|
||||
item.filepath = q["filepath"]
|
||||
item.filename = q["filename"]
|
||||
item.savepath = q["savepath"]
|
||||
item.video_url = q["url"]
|
||||
item.vtt_url = q["vtt"]
|
||||
item.thumbnail = q.get("image", "")
|
||||
item.status = "wait"
|
||||
item.linkkf_info = q["linkkf_info"]
|
||||
item.save()
|
||||
|
||||
@classmethod
|
||||
def get_paging_info(cls, count, page, page_size):
|
||||
@@ -2208,51 +2704,57 @@ class ModelLinkkfItem(db.Model):
|
||||
|
||||
@classmethod
|
||||
def delete_by_id(cls, idx):
|
||||
db.session.query(cls).filter_by(id=idx).delete()
|
||||
db.session.commit()
|
||||
from framework import F
|
||||
with F.app.app_context():
|
||||
db.session.query(cls).filter_by(id=idx).delete()
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def web_list(cls, req):
|
||||
ret = {}
|
||||
page = int(req.form["page"]) if "page" in req.form else 1
|
||||
page_size = 30
|
||||
job_id = ""
|
||||
search = req.form["search_word"] if "search_word" in req.form else ""
|
||||
option = req.form["option"] if "option" in req.form else "all"
|
||||
order = req.form["order"] if "order" in req.form else "desc"
|
||||
query = cls.make_query(search=search, order=order, option=option)
|
||||
count = query.count()
|
||||
query = query.limit(page_size).offset((page - 1) * page_size)
|
||||
lists = query.all()
|
||||
ret["list"] = [item.as_dict() for item in lists]
|
||||
ret["paging"] = cls.get_paging_info(count, page, page_size)
|
||||
return ret
|
||||
from framework import F
|
||||
with F.app.app_context():
|
||||
ret = {}
|
||||
page = int(req.form["page"]) if "page" in req.form else 1
|
||||
page_size = 30
|
||||
job_id = ""
|
||||
search = req.form["search_word"] if "search_word" in req.form else ""
|
||||
option = req.form["option"] if "option" in req.form else "all"
|
||||
order = req.form["order"] if "order" in req.form else "desc"
|
||||
query = cls.make_query(search=search, order=order, option=option)
|
||||
count = query.count()
|
||||
query = query.limit(page_size).offset((page - 1) * page_size)
|
||||
lists = query.all()
|
||||
ret["list"] = [item.as_dict() for item in lists]
|
||||
ret["paging"] = cls.get_paging_info(count, page, page_size)
|
||||
return ret
|
||||
|
||||
@classmethod
|
||||
def make_query(cls, search="", order="desc", option="all"):
|
||||
query = db.session.query(cls)
|
||||
if search is not None and search != "":
|
||||
if search.find("|") != -1:
|
||||
tmp = search.split("|")
|
||||
conditions = []
|
||||
for tt in tmp:
|
||||
if tt != "":
|
||||
conditions.append(cls.filename.like("%" + tt.strip() + "%"))
|
||||
query = query.filter(or_(*conditions))
|
||||
elif search.find(",") != -1:
|
||||
tmp = search.split(",")
|
||||
for tt in tmp:
|
||||
if tt != "":
|
||||
query = query.filter(cls.filename.like("%" + tt.strip() + "%"))
|
||||
else:
|
||||
query = query.filter(cls.filename.like("%" + search + f"%"))
|
||||
|
||||
if option == "completed":
|
||||
query = query.filter(cls.status == "completed")
|
||||
from framework import F
|
||||
with F.app.app_context():
|
||||
query = db.session.query(cls)
|
||||
if search is not None and search != "":
|
||||
if search.find("|") != -1:
|
||||
tmp = search.split("|")
|
||||
conditions = []
|
||||
for tt in tmp:
|
||||
if tt != "":
|
||||
conditions.append(cls.filename.like("%" + tt.strip() + "%"))
|
||||
query = query.filter(or_(*conditions))
|
||||
elif search.find(",") != -1:
|
||||
tmp = search.split(",")
|
||||
for tt in tmp:
|
||||
if tt != "":
|
||||
query = query.filter(cls.filename.like("%" + tt.strip() + "%"))
|
||||
else:
|
||||
query = query.filter(cls.filename.like("%" + search + f"%"))
|
||||
|
||||
if order == "desc":
|
||||
query = query.order_by(desc(cls.id))
|
||||
else:
|
||||
query = query.order_by(cls.id)
|
||||
return query
|
||||
if option == "completed":
|
||||
query = query.filter(cls.status == "completed")
|
||||
|
||||
if order == "desc":
|
||||
query = query.order_by(desc(cls.id))
|
||||
else:
|
||||
query = query.order_by(cls.id)
|
||||
return query
|
||||
|
||||
249
mod_ohli24.py
249
mod_ohli24.py
@@ -632,8 +632,29 @@ class LogicOhli24(AnimeModuleBase):
|
||||
|
||||
if ModuleQueue:
|
||||
if command == "stop" or command == "cancel":
|
||||
ModuleQueue.process_ajax('cancel', req)
|
||||
return jsonify({'ret':'success'})
|
||||
# Create a mock request object for GDM cancel as req.form is often immutable
|
||||
class MockRequest:
|
||||
def __init__(self, form_data):
|
||||
self.form = form_data
|
||||
|
||||
mock_req = MockRequest({"id": entity_id})
|
||||
|
||||
try:
|
||||
# Try to call process_ajax on what we have
|
||||
ret = ModuleQueue.process_ajax('cancel', mock_req)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to delegate cancel to ModuleQueue: {e}")
|
||||
# Fallback: Find the instance via P if available
|
||||
try:
|
||||
from gommi_downloader_manager.setup import P as GDM_P
|
||||
if GDM_P and hasattr(GDM_P, 'module_list'):
|
||||
for m in GDM_P.module_list:
|
||||
if m.name == 'queue':
|
||||
ret = m.process_ajax('cancel', mock_req)
|
||||
break
|
||||
except: pass
|
||||
|
||||
return jsonify({'ret':'success', 'data': {'idx': entity_id, 'status_str': 'STOP', 'status_kor': '중지'}})
|
||||
elif command == "reset":
|
||||
# Ohli24 모듈의 다운로드만 취소 (다른 플러그인 항목은 그대로)
|
||||
caller_id = f"{P.package_name}_{self.name}"
|
||||
@@ -641,7 +662,8 @@ class LogicOhli24(AnimeModuleBase):
|
||||
for task_id, task in list(ModuleQueue._downloads.items()):
|
||||
if task.caller_plugin == caller_id:
|
||||
task.cancel()
|
||||
del ModuleQueue._downloads[task_id]
|
||||
# GDM 내부 클린업은 cancel()이 담당하므로 여기서 del은 신중해야 함
|
||||
# 하지만 강제 초기화이므로 제거 시도
|
||||
cancelled_count += 1
|
||||
|
||||
# Ohli24 DB도 정리
|
||||
@@ -652,7 +674,7 @@ class LogicOhli24(AnimeModuleBase):
|
||||
F.db.session.commit()
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to clear Ohli24 DB: {e}")
|
||||
return jsonify({'ret':'notify', 'log':f'{cancelled_count}개 Ohli24 항목이 초기화되었습니다.'})
|
||||
return jsonify({'ret':'success', 'log':f'{cancelled_count}개 Ohli24 항목이 초기화되었습니다.'})
|
||||
elif command == "delete_completed":
|
||||
# 완료 항목만 삭제
|
||||
try:
|
||||
@@ -1186,31 +1208,154 @@ class LogicOhli24(AnimeModuleBase):
|
||||
self, command: str, arg1: str, arg2: str, arg3: str, req: Any
|
||||
) -> Any:
|
||||
"""커맨드 처리."""
|
||||
ret: Dict[str, Any] = {"ret": "success"}
|
||||
try:
|
||||
if command == "list":
|
||||
# 1. 자체 큐 목록 가져오기
|
||||
ret = self.queue.get_entity_list() if self.queue else []
|
||||
|
||||
# 2. GDM 태스크 가져오기 (설치된 경우)
|
||||
try:
|
||||
from gommi_downloader_manager.mod_queue import ModuleQueue
|
||||
if ModuleQueue:
|
||||
gdm_tasks = ModuleQueue.get_all_downloads()
|
||||
# 이 모듈(ohli24)이 추가한 작업만 필터링
|
||||
ohli24_tasks = [t for t in gdm_tasks if t.caller_plugin == f"{P.package_name}_{self.name}"]
|
||||
|
||||
for task in ohli24_tasks:
|
||||
# 템플릿 호환 형식으로 변환
|
||||
gdm_item = self._convert_gdm_task_to_queue_item(task)
|
||||
ret.append(gdm_item)
|
||||
except Exception as e:
|
||||
logger.debug(f"GDM tasks fetch error: {e}")
|
||||
|
||||
return jsonify(ret)
|
||||
|
||||
elif command in ["stop", "remove", "cancel"]:
|
||||
entity_id = arg1
|
||||
if entity_id and str(entity_id).startswith("dl_"):
|
||||
# GDM 작업 처리
|
||||
try:
|
||||
from gommi_downloader_manager.mod_queue import ModuleQueue
|
||||
if ModuleQueue:
|
||||
if command == "stop" or command == "cancel":
|
||||
task = ModuleQueue.get_download(entity_id)
|
||||
if task:
|
||||
task.cancel()
|
||||
return jsonify({"ret": "success", "log": "GDM 작업을 중지하였습니다."})
|
||||
elif command == "remove" or command == "delete":
|
||||
# GDM에서 삭제 처리
|
||||
class DummyReq:
|
||||
def __init__(self, id):
|
||||
self.form = {"id": id}
|
||||
ModuleQueue.process_ajax("delete", DummyReq(entity_id))
|
||||
return jsonify({"ret": "success", "log": "GDM 작업을 삭제하였습니다."})
|
||||
except Exception as e:
|
||||
logger.error(f"GDM command error: {e}")
|
||||
return jsonify({"ret": "error", "log": f"GDM 명령 실패: {e}"})
|
||||
|
||||
# 자체 큐 처리
|
||||
return super().process_command(command, arg1, arg2, arg3, req)
|
||||
|
||||
if command == "download_program":
|
||||
_pass = arg2
|
||||
db_item = ModelOhli24Program.get(arg1)
|
||||
if _pass == "false" and db_item is not None:
|
||||
ret["ret"] = "warning"
|
||||
ret["msg"] = "이미 DB에 있는 항목 입니다."
|
||||
elif (
|
||||
_pass == "true"
|
||||
and db_item is not None
|
||||
and ModelOhli24Program.get_by_id_in_queue(db_item.id) is not None
|
||||
):
|
||||
ret["ret"] = "warning"
|
||||
ret["msg"] = "이미 큐에 있는 항목 입니다."
|
||||
else:
|
||||
if db_item is None:
|
||||
db_item = ModelOhli24Program(arg1, self.get_episode(arg1))
|
||||
db_item.save()
|
||||
db_item.init_for_queue()
|
||||
self.download_queue.put(db_item)
|
||||
ret["msg"] = "다운로드를 추가 하였습니다."
|
||||
return jsonify(ret)
|
||||
if command == "download_program":
|
||||
ret: Dict[str, Any] = {"ret": "success"}
|
||||
_pass = arg2
|
||||
db_item = ModelOhli24Program.get(arg1)
|
||||
if _pass == "false" and db_item is not None:
|
||||
ret["ret"] = "warning"
|
||||
ret["msg"] = "이미 DB에 있는 항목 입니다."
|
||||
elif (
|
||||
_pass == "true"
|
||||
and db_item is not None
|
||||
and ModelOhli24Program.get_by_id_in_queue(db_item.id) is not None
|
||||
):
|
||||
ret["ret"] = "warning"
|
||||
ret["msg"] = "이미 큐에 있는 항목 입니다."
|
||||
else:
|
||||
if db_item is None:
|
||||
db_item = ModelOhli24Program(arg1, self.get_episode(arg1))
|
||||
db_item.save()
|
||||
db_item.init_for_queue()
|
||||
self.download_queue.put(db_item)
|
||||
ret["msg"] = "다운로드를 추가 하였습니다."
|
||||
return jsonify(ret)
|
||||
|
||||
return super().process_command(command, arg1, arg2, arg3, req)
|
||||
return super().process_command(command, arg1, arg2, arg3, req)
|
||||
except Exception as e:
|
||||
logger.error(f"process_command Error: {e}")
|
||||
logger.error(traceback.format_exc())
|
||||
return jsonify({'ret': 'fail', 'log': str(e)})
|
||||
|
||||
def _convert_gdm_task_to_queue_item(self, task):
|
||||
"""GDM DownloadTask 객체를 FfmpegQueueEntity.as_dict() 호환 형식으로 변환"""
|
||||
status_kor_map = {
|
||||
"pending": "대기중",
|
||||
"extracting": "분석중",
|
||||
"downloading": "다운로드중",
|
||||
"paused": "일시정지",
|
||||
"completed": "완료",
|
||||
"error": "실패",
|
||||
"cancelled": "취소됨"
|
||||
}
|
||||
|
||||
status_str_map = {
|
||||
"pending": "WAITING",
|
||||
"extracting": "ANALYZING",
|
||||
"downloading": "DOWNLOADING",
|
||||
"paused": "PAUSED",
|
||||
"completed": "COMPLETED",
|
||||
"error": "FAILED",
|
||||
"cancelled": "FAILED"
|
||||
}
|
||||
|
||||
t_dict = task.as_dict()
|
||||
|
||||
return {
|
||||
"entity_id": t_dict["id"],
|
||||
"url": t_dict["url"],
|
||||
"filename": t_dict["filename"] or t_dict["title"],
|
||||
"status_kor": status_kor_map.get(t_dict["status"], "알수없음"),
|
||||
"percent": t_dict["progress"],
|
||||
"created_time": t_dict["created_time"],
|
||||
"current_speed": t_dict["speed"] or "0 B/s",
|
||||
"download_time": t_dict["eta"] or "-",
|
||||
"status_str": status_str_map.get(t_dict["status"], "WAITING"),
|
||||
"idx": t_dict["id"],
|
||||
"callback_id": "ohli24",
|
||||
"start_time": t_dict["start_time"] or t_dict["created_time"],
|
||||
"save_fullpath": t_dict["filepath"],
|
||||
"duration_str": "GDM",
|
||||
"current_pf_count": 0,
|
||||
"duration": "-",
|
||||
"current_duration": "-",
|
||||
"current_bitrate": "-",
|
||||
"max_pf_count": 0,
|
||||
"is_gdm": True
|
||||
}
|
||||
|
||||
def plugin_callback(self, data):
|
||||
"""GDM 모듈로부터 다운로드 상태 업데이트 수신"""
|
||||
try:
|
||||
callback_id = data.get('callback_id')
|
||||
status = data.get('status')
|
||||
|
||||
logger.info(f"[Ohli24] Received GDM callback: id={callback_id}, status={status}")
|
||||
|
||||
if callback_id:
|
||||
from framework import F
|
||||
with F.app.app_context():
|
||||
db_item = ModelOhli24Item.get_by_ohli24_id(callback_id)
|
||||
if db_item:
|
||||
if status == "completed":
|
||||
db_item.status = "completed"
|
||||
db_item.completed_time = datetime.now()
|
||||
db_item.filepath = data.get('filepath')
|
||||
db_item.save()
|
||||
logger.info(f"[Ohli24] Updated DB item {db_item.id} to COMPLETED via GDM callback")
|
||||
elif status == "error":
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.error(f"[Ohli24] Callback processing error: {e}")
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
@staticmethod
|
||||
def add_whitelist(*args: str) -> Dict[str, Any]:
|
||||
@@ -1497,6 +1642,15 @@ class LogicOhli24(AnimeModuleBase):
|
||||
m = hashlib.md5(ep_title.encode("utf-8"))
|
||||
_vi = m.hexdigest()
|
||||
|
||||
# Parse episode number for UI badge
|
||||
epi_no = None
|
||||
ep_match = re.search(r"(\d+(?:\.\d+)?)[\s\.\…화회]*$", ep_title)
|
||||
if ep_match:
|
||||
try:
|
||||
epi_val = float(ep_match.group(1))
|
||||
epi_no = int(epi_val) if epi_val.is_integer() else epi_val
|
||||
except: pass
|
||||
|
||||
episodes.append({
|
||||
"title": ep_title,
|
||||
"link": href,
|
||||
@@ -1507,6 +1661,7 @@ class LogicOhli24(AnimeModuleBase):
|
||||
"va": href,
|
||||
"_vi": _vi,
|
||||
"content_code": code,
|
||||
"epi_no": epi_no,
|
||||
})
|
||||
except Exception as ep_err:
|
||||
logger.warning(f"Episode parse error: {ep_err}")
|
||||
@@ -2303,7 +2458,7 @@ class LogicOhli24(AnimeModuleBase):
|
||||
|
||||
# GDM 소스 타입 결정 (멀티쓰레드/aria2c 사용 여부에 따라)
|
||||
# GDM의 'general'은 yt-dlp + aria2c를 사용함
|
||||
gdm_source_type = "ani24"
|
||||
gdm_source_type = "ohli24"
|
||||
if download_method in ['ytdlp', 'aria2c']:
|
||||
gdm_source_type = "general"
|
||||
|
||||
@@ -2315,7 +2470,7 @@ class LogicOhli24(AnimeModuleBase):
|
||||
"caller_plugin": f"{P.package_name}_{self.name}",
|
||||
"callback_id": episode_info["_id"],
|
||||
"title": entity.filename or episode_info.get('title'),
|
||||
"thumbnail": episode_info.get('image'),
|
||||
"thumbnail": episode_info.get('thumbnail') or episode_info.get('image'),
|
||||
"meta": {
|
||||
"series": entity.content_title,
|
||||
"season": entity.season,
|
||||
@@ -2373,7 +2528,17 @@ class LogicOhli24(AnimeModuleBase):
|
||||
|
||||
if P.ModelSetting.get_bool("ohli24_auto_make_folder"):
|
||||
day = episode_info.get("day", "")
|
||||
|
||||
# Robust extraction logic (Sync with Ohli24QueueEntity.parse_metadata)
|
||||
content_title_clean = match.group("title").strip() if match else title
|
||||
if not match:
|
||||
# Fallback for truncated titles (e.g. "Long Title 6…")
|
||||
fallback_match = re.search(r"(?P<title>.*?)\s*(?P<epi_no>\d+(?:\.\d+)?)(?:\.+|…)?\s*[^\d]*$", title.strip())
|
||||
if fallback_match:
|
||||
content_title_clean = fallback_match.group("title").strip().rstrip('-').strip()
|
||||
else:
|
||||
content_title_clean = title
|
||||
|
||||
if "완결" in day:
|
||||
folder_name = "%s %s" % (P.ModelSetting.get("ohli24_finished_insert"), content_title_clean)
|
||||
else:
|
||||
@@ -2746,15 +2911,27 @@ class Ohli24QueueEntity(AnimeQueueEntity):
|
||||
if not title_full:
|
||||
return
|
||||
|
||||
match = re.compile(r"(?P<title>.*?)\s*((?P<season>\d+)기)?\s*((?P<epi_no>\d+)화)").search(title_full)
|
||||
# Improved Regex: Handle optional [-(, optional season, and various episode suffixes
|
||||
regex_main = re.compile(r"(?P<title>.*?)\s*(?:[\-\(\[])?\s*((?P<season>\d+)기)?\s*(?P<epi_no>\d+(?:\.\d+)?)\s*(?:화|회|part|part\s*\d+)?\s*(?:\(完\))?\s*(?:[\)\]])?$")
|
||||
match = regex_main.search(title_full.strip())
|
||||
|
||||
if match:
|
||||
self.content_title = match.group("title").strip()
|
||||
self.content_title = match.group("title").strip().rstrip('-').strip()
|
||||
if match.group("season"):
|
||||
self.season = int(match.group("season"))
|
||||
self.epi_queue = int(match.group("epi_no"))
|
||||
self.epi_queue = float(match.group("epi_no"))
|
||||
if self.epi_queue.is_integer():
|
||||
self.epi_queue = int(self.epi_queue)
|
||||
else:
|
||||
self.content_title = title_full
|
||||
self.epi_queue = 1
|
||||
# Fallback for truncated titles or unusual suffixes (e.g. "Title 6…")
|
||||
fallback_match = re.search(r"(?P<title>.*?)\s*(?P<epi_no>\d+(?:\.\d+)?)(?:\.+|…)?\s*[^\d]*$", title_full.strip())
|
||||
if fallback_match:
|
||||
self.content_title = fallback_match.group("title").strip().rstrip('-').strip()
|
||||
epi_val = float(fallback_match.group("epi_no"))
|
||||
self.epi_queue = int(epi_val) if epi_val.is_integer() else epi_val
|
||||
else:
|
||||
self.content_title = title_full
|
||||
self.epi_queue = 1
|
||||
|
||||
# Predict initial filename/filepath for UI
|
||||
epi_no = self.epi_queue
|
||||
@@ -3324,7 +3501,7 @@ class Ohli24QueueEntity(AnimeQueueEntity):
|
||||
class ModelOhli24Item(ModelBase):
|
||||
P = P
|
||||
__tablename__ = "{package_name}_ohli24_item".format(package_name=P.package_name)
|
||||
__table_args__ = {"mysql_collate": "utf8_general_ci"}
|
||||
__table_args__ = {"mysql_collate": "utf8_general_ci", "extend_existing": True}
|
||||
__bind_key__ = P.package_name
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
created_time = db.Column(db.DateTime)
|
||||
@@ -3480,7 +3657,7 @@ class ModelOhli24Item(ModelBase):
|
||||
class ModelOhli24Program(ModelBase):
|
||||
P = P
|
||||
__tablename__ = f"{P.package_name}_{name}_program"
|
||||
__table_args__ = {"mysql_collate": "utf8_general_ci"}
|
||||
__table_args__ = {"mysql_collate": "utf8_general_ci", "extend_existing": True}
|
||||
__bind_key__ = P.package_name
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
|
||||
@@ -14,6 +14,12 @@ body {
|
||||
color: #e0e7ff !important;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
body {
|
||||
background-attachment: scroll !important; /* Fixed background causes shift on some mobile browsers */
|
||||
}
|
||||
}
|
||||
|
||||
/* Common Layout Wrapper - Responsive */
|
||||
.anilife-common-wrapper {
|
||||
max-width: 100%;
|
||||
|
||||
@@ -54,82 +54,125 @@
|
||||
font-weight: 600 !important;
|
||||
}
|
||||
|
||||
/* Common Mobile Responsive Fixes */
|
||||
/* Common Mobile Responsive Fixes - Comprehensive Normalization */
|
||||
@media (max-width: 768px) {
|
||||
body {
|
||||
padding-top: 5px !important;
|
||||
*, ::before, ::after {
|
||||
box-sizing: border-box !important;
|
||||
}
|
||||
|
||||
html, body {
|
||||
width: 100% !important;
|
||||
max-width: 100% !important;
|
||||
margin: 0 !important;
|
||||
padding: 0 !important;
|
||||
overflow-x: hidden !important;
|
||||
position: relative !important;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
touch-action: manipulation;
|
||||
}
|
||||
|
||||
/* Layout Expansion on Mobile - Critical Fix for Horizontal Shift */
|
||||
.container, .container-fluid, #main_container {
|
||||
width: 100% !important;
|
||||
max-width: 100% !important;
|
||||
min-width: 0 !important;
|
||||
padding-left: 5px !important;
|
||||
padding-right: 5px !important;
|
||||
margin-left: 0 !important;
|
||||
margin-right: 0 !important;
|
||||
box-sizing: border-box !important;
|
||||
overflow-x: hidden !important;
|
||||
}
|
||||
|
||||
/* Compact Navbar */
|
||||
.row {
|
||||
margin-left: 0 !important;
|
||||
margin-right: 0 !important;
|
||||
width: 100% !important;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
[class*="col-"] {
|
||||
padding-left: 4px !important;
|
||||
padding-right: 4px !important;
|
||||
min-width: 0 !important;
|
||||
}
|
||||
|
||||
/* Compact Navbar Fix */
|
||||
.navbar {
|
||||
width: 100% !important;
|
||||
max-width: 100% !important;
|
||||
padding-top: 0.25rem !important;
|
||||
padding-bottom: 0.25rem !important;
|
||||
margin: 0 !important;
|
||||
}
|
||||
|
||||
/* Global Navigation Pills Fix & Premium Styling */
|
||||
/* Scroll Hint Container Fix */
|
||||
#menu_module_div, #menu_page_div {
|
||||
position: relative;
|
||||
width: 100% !important;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Gradient Hint to indicate more items (Scroll Hint) */
|
||||
#menu_module_div::after, #menu_page_div::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 4px; bottom: 4px; right: 0;
|
||||
width: 40px;
|
||||
background: linear-gradient(to right, transparent, rgba(30, 41, 59, 0.9));
|
||||
pointer-events: none;
|
||||
z-index: 10;
|
||||
border-top-right-radius: 8px;
|
||||
border-bottom-right-radius: 8px;
|
||||
}
|
||||
|
||||
/* Navigation Pills Styling */
|
||||
ul.nav.nav-pills.bg-light {
|
||||
background-color: rgba(30, 41, 59, 0.6) !important;
|
||||
backdrop-filter: blur(10px);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
border-radius: 50rem !important; /* Pill shape container */
|
||||
padding: 6px !important;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2) !important;
|
||||
display: inline-flex !important; /* Fit content */
|
||||
flex-wrap: wrap; /* allow wrap on small screens */
|
||||
justify-content: center;
|
||||
width: auto !important; /* Prevent full width */
|
||||
margin-top: 2px !important; /* Reduced for modularity */
|
||||
border-radius: 8px !important;
|
||||
padding: 4px !important;
|
||||
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2) !important;
|
||||
display: flex !important;
|
||||
flex-wrap: nowrap !important;
|
||||
overflow-x: auto !important;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
width: 100% !important;
|
||||
max-width: 100% !important;
|
||||
box-sizing: border-box !important;
|
||||
margin-top: 2px !important;
|
||||
justify-content: flex-start !important;
|
||||
scrollbar-width: thin; /* Firefox */
|
||||
}
|
||||
|
||||
/* Override for the fallback above to be tighter */
|
||||
ul.nav.nav-pills.bg-light {
|
||||
margin-top: 4px !important;
|
||||
/* Subtle scrollbar hint for mobile */
|
||||
ul.nav.nav-pills.bg-light::-webkit-scrollbar {
|
||||
height: 3px;
|
||||
}
|
||||
|
||||
/* Tighten spacing between 2nd and 3rd level menus */
|
||||
#menu_module_div ul.nav.nav-pills.bg-light {
|
||||
margin-bottom: 2px !important;
|
||||
}
|
||||
|
||||
#menu_page_div ul.nav.nav-pills.bg-light {
|
||||
margin-top: -4px !important;
|
||||
margin-bottom: 12px !important;
|
||||
ul.nav.nav-pills.bg-light::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
ul.nav.nav-pills .nav-item {
|
||||
margin: 0 2px;
|
||||
flex: 0 0 auto !important;
|
||||
}
|
||||
|
||||
ul.nav.nav-pills .nav-link {
|
||||
border-radius: 50rem !important;
|
||||
padding: 6px 16px !important;
|
||||
color: #94a3b8 !important; /* Muted text */
|
||||
border-radius: 6px !important;
|
||||
padding: 6px 14px !important;
|
||||
color: #94a3b8 !important;
|
||||
font-weight: 600;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
ul.nav.nav-pills .nav-link:hover {
|
||||
background-color: rgba(255, 255, 255, 0.1);
|
||||
color: #fff !important;
|
||||
transform: translateY(-1px);
|
||||
white-space: nowrap !important;
|
||||
font-size: 11px !important;
|
||||
}
|
||||
|
||||
ul.nav.nav-pills .nav-link.active {
|
||||
background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%) !important;
|
||||
color: #fff !important;
|
||||
box-shadow: 0 4px 12px rgba(37, 99, 235, 0.4);
|
||||
}
|
||||
|
||||
/* Layout Expansion on Mobile */
|
||||
.container, .container-fluid, .row, form, #main_container {
|
||||
width: 100% !important;
|
||||
max-width: 100% !important;
|
||||
padding-left: 8px !important;
|
||||
padding-right: 8px !important;
|
||||
margin-left: 0 !important;
|
||||
margin-right: 0 !important;
|
||||
box-sizing: border-box !important;
|
||||
}
|
||||
|
||||
/* Card/Table Container Fix */
|
||||
@@ -137,7 +180,7 @@
|
||||
width: 100% !important;
|
||||
margin-left: 0 !important;
|
||||
margin-right: 0 !important;
|
||||
border-radius: 12px !important;
|
||||
border-radius: 8px !important;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,8 +40,8 @@ body {
|
||||
|
||||
/* General Layout Fixes */
|
||||
.container-fluid {
|
||||
padding-left: 8px !important;
|
||||
padding-right: 8px !important;
|
||||
padding-left: 5px !important;
|
||||
padding-right: 5px !important;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
|
||||
@@ -77,6 +77,56 @@
|
||||
object-fit: cover !important;
|
||||
}
|
||||
|
||||
/* Artplayer Container */
|
||||
#artplayer-container {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-height: 400px;
|
||||
}
|
||||
#artplayer-container.art-zoomed .art-video {
|
||||
object-fit: cover !important;
|
||||
}
|
||||
|
||||
/* Plyr Container */
|
||||
#plyr-container {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
#plyr-container .plyr {
|
||||
height: 100%;
|
||||
}
|
||||
#plyr-container .plyr--video {
|
||||
height: 100%;
|
||||
}
|
||||
#plyr-container video.vjs-zoomed {
|
||||
object-fit: cover !important;
|
||||
}
|
||||
|
||||
/* Player Select Dropdown in Header */
|
||||
#player-select {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
color: white;
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
border-radius: 6px;
|
||||
padding: 6px 12px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
#player-select:hover {
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
border-color: rgba(255, 255, 255, 0.3);
|
||||
}
|
||||
#player-select:focus {
|
||||
outline: none;
|
||||
border-color: #3b82f6;
|
||||
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.3);
|
||||
}
|
||||
#player-select option {
|
||||
background: #1e293b;
|
||||
color: #f1f5f9;
|
||||
}
|
||||
|
||||
/* Zoom Button */
|
||||
.video-zoom-btn {
|
||||
position: absolute;
|
||||
|
||||
@@ -1,12 +1,3 @@
|
||||
/**
|
||||
* Video Modal Component JavaScript
|
||||
* Reusable video player modal for Anime Downloader
|
||||
*
|
||||
* Usage:
|
||||
* VideoModal.init({ package_name: 'anime_downloader', sub: 'ohli24' });
|
||||
* VideoModal.openWithPath('/path/to/video.mp4');
|
||||
*/
|
||||
|
||||
var VideoModal = (function() {
|
||||
'use strict';
|
||||
|
||||
@@ -15,28 +6,45 @@ var VideoModal = (function() {
|
||||
sub: 'ohli24'
|
||||
};
|
||||
|
||||
var videoPlayer = null;
|
||||
var videoPlayer = null; // Video.js instance
|
||||
var artPlayer = null; // Artplayer instance
|
||||
var plyrPlayer = null; // Plyr instance
|
||||
var currentPlayer = 'videojs'; // 'videojs', 'artplayer', 'plyr'
|
||||
var playlist = [];
|
||||
var currentPlaylistIndex = 0;
|
||||
var currentPlayingPath = '';
|
||||
var currentStreamUrl = '';
|
||||
var isVideoZoomed = false;
|
||||
|
||||
/**
|
||||
* Initialize the video modal
|
||||
* @param {Object} options - Configuration options
|
||||
* @param {string} options.package_name - Package name (default: 'anime_downloader')
|
||||
* @param {string} options.sub - Sub-module name (e.g., 'ohli24', 'linkkf')
|
||||
*/
|
||||
function init(options) {
|
||||
config = Object.assign(config, options || {});
|
||||
|
||||
// Load saved player preference
|
||||
var savedPlayer = localStorage.getItem('anime_downloader_preferred_player');
|
||||
if (savedPlayer && ['videojs', 'artplayer', 'plyr'].indexOf(savedPlayer) >= 0) {
|
||||
currentPlayer = savedPlayer;
|
||||
$('#player-select').val(currentPlayer);
|
||||
}
|
||||
|
||||
bindEvents();
|
||||
console.log('[VideoModal] Initialized with config:', config);
|
||||
console.log('[VideoModal] Initialized with player:', currentPlayer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind all event handlers
|
||||
*/
|
||||
function bindEvents() {
|
||||
// Player selector change
|
||||
$('#player-select').off('change').on('change', function() {
|
||||
var newPlayer = $(this).val();
|
||||
if (newPlayer !== currentPlayer) {
|
||||
switchPlayer(newPlayer);
|
||||
}
|
||||
});
|
||||
|
||||
// Dropdown episode selection
|
||||
$('#episode-dropdown').off('change').on('change', function() {
|
||||
var index = parseInt($(this).val());
|
||||
@@ -50,10 +58,12 @@ var VideoModal = (function() {
|
||||
$('#btn-video-zoom').off('click').on('click', function() {
|
||||
isVideoZoomed = !isVideoZoomed;
|
||||
if (isVideoZoomed) {
|
||||
$('#video-player').addClass('vjs-zoomed');
|
||||
$('#video-player, #plyr-player').addClass('vjs-zoomed');
|
||||
$('#artplayer-container').addClass('art-zoomed');
|
||||
$(this).addClass('active').find('i').removeClass('fa-expand').addClass('fa-compress');
|
||||
} else {
|
||||
$('#video-player').removeClass('vjs-zoomed');
|
||||
$('#video-player, #plyr-player').removeClass('vjs-zoomed');
|
||||
$('#artplayer-container').removeClass('art-zoomed');
|
||||
$(this).removeClass('active').find('i').removeClass('fa-compress').addClass('fa-expand');
|
||||
}
|
||||
});
|
||||
@@ -64,87 +74,81 @@ var VideoModal = (function() {
|
||||
});
|
||||
|
||||
$('#videoModal').off('hide.bs.modal').on('hide.bs.modal', function() {
|
||||
if (videoPlayer) {
|
||||
videoPlayer.pause();
|
||||
}
|
||||
pauseAllPlayers();
|
||||
});
|
||||
|
||||
$('#videoModal').off('hidden.bs.modal').on('hidden.bs.modal', function() {
|
||||
$('body').removeClass('modal-video-open');
|
||||
if (isVideoZoomed) {
|
||||
isVideoZoomed = false;
|
||||
$('#video-player').removeClass('vjs-zoomed');
|
||||
$('#video-player, #plyr-player').removeClass('vjs-zoomed');
|
||||
$('#artplayer-container').removeClass('art-zoomed');
|
||||
$('#btn-video-zoom').removeClass('active').find('i').removeClass('fa-compress').addClass('fa-expand');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Open modal with a file path (fetches playlist from server)
|
||||
* @param {string} filePath - Path to the video file
|
||||
* Switch between players
|
||||
*/
|
||||
function openWithPath(filePath) {
|
||||
$.ajax({
|
||||
url: '/' + config.package_name + '/ajax/' + config.sub + '/get_playlist?path=' + encodeURIComponent(filePath),
|
||||
type: 'GET',
|
||||
dataType: 'json',
|
||||
success: function(data) {
|
||||
playlist = data.playlist || [];
|
||||
currentPlaylistIndex = data.current_index || 0;
|
||||
currentPlayingPath = filePath;
|
||||
|
||||
var streamUrl = '/' + config.package_name + '/ajax/' + config.sub + '/stream_video?path=' + encodeURIComponent(filePath);
|
||||
initPlayer(streamUrl);
|
||||
updatePlaylistUI();
|
||||
$('#videoModal').modal('show');
|
||||
},
|
||||
error: function() {
|
||||
// Fallback: single file
|
||||
playlist = [{ name: filePath.split('/').pop(), path: filePath }];
|
||||
currentPlaylistIndex = 0;
|
||||
var streamUrl = '/' + config.package_name + '/ajax/' + config.sub + '/stream_video?path=' + encodeURIComponent(filePath);
|
||||
initPlayer(streamUrl);
|
||||
updatePlaylistUI();
|
||||
$('#videoModal').modal('show');
|
||||
}
|
||||
});
|
||||
function switchPlayer(newPlayer) {
|
||||
pauseAllPlayers();
|
||||
|
||||
currentPlayer = newPlayer;
|
||||
localStorage.setItem('anime_downloader_preferred_player', newPlayer);
|
||||
|
||||
// Hide all player containers
|
||||
$('#videojs-container').hide();
|
||||
$('#artplayer-container').hide();
|
||||
$('#plyr-container').hide();
|
||||
|
||||
// Show selected player and reinitialize with current URL
|
||||
if (currentStreamUrl) {
|
||||
initPlayerWithUrl(currentStreamUrl);
|
||||
}
|
||||
|
||||
console.log('[VideoModal] Switched to:', newPlayer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Open modal with a direct stream URL
|
||||
* @param {string} streamUrl - Direct URL to stream
|
||||
* @param {string} title - Optional title
|
||||
* Pause all players
|
||||
*/
|
||||
function openWithUrl(streamUrl, title) {
|
||||
playlist = [{ name: title || 'Video', path: streamUrl }];
|
||||
currentPlaylistIndex = 0;
|
||||
initPlayer(streamUrl);
|
||||
updatePlaylistUI();
|
||||
$('#videoModal').modal('show');
|
||||
function pauseAllPlayers() {
|
||||
try {
|
||||
if (videoPlayer) videoPlayer.pause();
|
||||
} catch(e) {}
|
||||
try {
|
||||
if (artPlayer) artPlayer.pause();
|
||||
} catch(e) {}
|
||||
try {
|
||||
if (plyrPlayer) plyrPlayer.pause();
|
||||
} catch(e) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Open modal with a playlist array
|
||||
* @param {Array} playlistData - Array of {name, path} objects
|
||||
* @param {number} startIndex - Index to start playing from
|
||||
* Initialize player with URL based on current player selection
|
||||
*/
|
||||
function openWithPlaylist(playlistData, startIndex) {
|
||||
playlist = playlistData || [];
|
||||
currentPlaylistIndex = startIndex || 0;
|
||||
if (playlist.length > 0) {
|
||||
var filePath = playlist[currentPlaylistIndex].path;
|
||||
var streamUrl = '/' + config.package_name + '/ajax/' + config.sub + '/stream_video?path=' + encodeURIComponent(filePath);
|
||||
initPlayer(streamUrl);
|
||||
updatePlaylistUI();
|
||||
$('#videoModal').modal('show');
|
||||
function initPlayerWithUrl(streamUrl) {
|
||||
currentStreamUrl = streamUrl;
|
||||
|
||||
if (currentPlayer === 'videojs') {
|
||||
initVideoJS(streamUrl);
|
||||
} else if (currentPlayer === 'artplayer') {
|
||||
initArtplayer(streamUrl);
|
||||
} else if (currentPlayer === 'plyr') {
|
||||
initPlyr(streamUrl);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize or update Video.js player
|
||||
* @param {string} streamUrl - URL to play
|
||||
* Initialize Video.js player
|
||||
*/
|
||||
function initPlayer(streamUrl) {
|
||||
function initVideoJS(streamUrl) {
|
||||
// Hide other containers
|
||||
$('#artplayer-container').hide();
|
||||
$('#plyr-container').hide();
|
||||
$('#videojs-container').show();
|
||||
|
||||
if (!videoPlayer) {
|
||||
videoPlayer = videojs('video-player', {
|
||||
controls: true,
|
||||
@@ -157,22 +161,84 @@ var VideoModal = (function() {
|
||||
}
|
||||
});
|
||||
|
||||
// Auto-next on video end
|
||||
videoPlayer.on('ended', function() {
|
||||
var autoNextEnabled = $('#auto-next-checkbox').is(':checked');
|
||||
if (autoNextEnabled && currentPlaylistIndex < playlist.length - 1) {
|
||||
currentPlaylistIndex++;
|
||||
playVideoAtIndex(currentPlaylistIndex);
|
||||
}
|
||||
});
|
||||
videoPlayer.on('ended', handleVideoEnded);
|
||||
}
|
||||
|
||||
videoPlayer.src({ type: 'video/mp4', src: streamUrl });
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize Artplayer
|
||||
*/
|
||||
function initArtplayer(streamUrl) {
|
||||
// Hide other containers
|
||||
$('#videojs-container').hide();
|
||||
$('#plyr-container').hide();
|
||||
$('#artplayer-container').show().empty();
|
||||
|
||||
if (artPlayer) {
|
||||
artPlayer.destroy();
|
||||
artPlayer = null;
|
||||
}
|
||||
|
||||
artPlayer = new Artplayer({
|
||||
container: '#artplayer-container',
|
||||
url: streamUrl,
|
||||
autoplay: false,
|
||||
pip: true,
|
||||
screenshot: true,
|
||||
setting: true,
|
||||
playbackRate: true,
|
||||
aspectRatio: true,
|
||||
fullscreen: true,
|
||||
fullscreenWeb: true,
|
||||
theme: '#3b82f6'
|
||||
});
|
||||
|
||||
artPlayer.on('video:ended', handleVideoEnded);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize Plyr player
|
||||
*/
|
||||
function initPlyr(streamUrl) {
|
||||
// Hide other containers
|
||||
$('#videojs-container').hide();
|
||||
$('#artplayer-container').hide();
|
||||
$('#plyr-container').show();
|
||||
|
||||
// Set source
|
||||
$('#plyr-player').attr('src', streamUrl);
|
||||
|
||||
if (!plyrPlayer) {
|
||||
plyrPlayer = new Plyr('#plyr-player', {
|
||||
controls: ['play-large', 'play', 'progress', 'current-time', 'mute', 'volume', 'settings', 'pip', 'fullscreen'],
|
||||
settings: ['quality', 'speed'],
|
||||
speed: { selected: 1, options: [0.5, 0.75, 1, 1.25, 1.5, 2] }
|
||||
});
|
||||
|
||||
plyrPlayer.on('ended', handleVideoEnded);
|
||||
} else {
|
||||
plyrPlayer.source = {
|
||||
type: 'video',
|
||||
sources: [{ src: streamUrl, type: 'video/mp4' }]
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle video ended event (auto-next)
|
||||
*/
|
||||
function handleVideoEnded() {
|
||||
var autoNextEnabled = $('#auto-next-checkbox').is(':checked');
|
||||
if (autoNextEnabled && currentPlaylistIndex < playlist.length - 1) {
|
||||
currentPlaylistIndex++;
|
||||
playVideoAtIndex(currentPlaylistIndex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Play video at specific playlist index
|
||||
* @param {number} index - Playlist index
|
||||
*/
|
||||
function playVideoAtIndex(index) {
|
||||
if (index < 0 || index >= playlist.length) return;
|
||||
@@ -180,14 +246,73 @@ var VideoModal = (function() {
|
||||
var item = playlist[index];
|
||||
var streamUrl = '/' + config.package_name + '/ajax/' + config.sub + '/stream_video?path=' + encodeURIComponent(item.path);
|
||||
|
||||
if (videoPlayer) {
|
||||
videoPlayer.src({ type: 'video/mp4', src: streamUrl });
|
||||
videoPlayer.play();
|
||||
}
|
||||
initPlayerWithUrl(streamUrl);
|
||||
|
||||
// Try to auto-play
|
||||
setTimeout(function() {
|
||||
if (currentPlayer === 'videojs' && videoPlayer) videoPlayer.play();
|
||||
else if (currentPlayer === 'artplayer' && artPlayer) artPlayer.play = true;
|
||||
else if (currentPlayer === 'plyr' && plyrPlayer) plyrPlayer.play();
|
||||
}, 100);
|
||||
|
||||
updatePlaylistUI();
|
||||
}
|
||||
|
||||
/**
|
||||
* Open modal with a file path (fetches playlist from server)
|
||||
*/
|
||||
function openWithPath(filePath) {
|
||||
$.ajax({
|
||||
url: '/' + config.package_name + '/ajax/' + config.sub + '/get_playlist?path=' + encodeURIComponent(filePath),
|
||||
type: 'GET',
|
||||
dataType: 'json',
|
||||
success: function(data) {
|
||||
playlist = data.playlist || [];
|
||||
currentPlaylistIndex = data.current_index || 0;
|
||||
currentPlayingPath = filePath;
|
||||
|
||||
var streamUrl = '/' + config.package_name + '/ajax/' + config.sub + '/stream_video?path=' + encodeURIComponent(filePath);
|
||||
initPlayerWithUrl(streamUrl);
|
||||
updatePlaylistUI();
|
||||
$('#videoModal').modal('show');
|
||||
},
|
||||
error: function() {
|
||||
playlist = [{ name: filePath.split('/').pop(), path: filePath }];
|
||||
currentPlaylistIndex = 0;
|
||||
var streamUrl = '/' + config.package_name + '/ajax/' + config.sub + '/stream_video?path=' + encodeURIComponent(filePath);
|
||||
initPlayerWithUrl(streamUrl);
|
||||
updatePlaylistUI();
|
||||
$('#videoModal').modal('show');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Open modal with a direct stream URL
|
||||
*/
|
||||
function openWithUrl(streamUrl, title) {
|
||||
playlist = [{ name: title || 'Video', path: streamUrl }];
|
||||
currentPlaylistIndex = 0;
|
||||
initPlayerWithUrl(streamUrl);
|
||||
updatePlaylistUI();
|
||||
$('#videoModal').modal('show');
|
||||
}
|
||||
|
||||
/**
|
||||
* Open modal with a playlist array
|
||||
*/
|
||||
function openWithPlaylist(playlistData, startIndex) {
|
||||
playlist = playlistData || [];
|
||||
currentPlaylistIndex = startIndex || 0;
|
||||
if (playlist.length > 0) {
|
||||
var filePath = playlist[currentPlaylistIndex].path;
|
||||
var streamUrl = '/' + config.package_name + '/ajax/' + config.sub + '/stream_video?path=' + encodeURIComponent(filePath);
|
||||
initPlayerWithUrl(streamUrl);
|
||||
updatePlaylistUI();
|
||||
$('#videoModal').modal('show');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update playlist UI (dropdown, external player buttons)
|
||||
*/
|
||||
|
||||
@@ -5,21 +5,44 @@
|
||||
<link href="https://vjs.zencdn.net/8.10.0/video-js.css" rel="stylesheet" />
|
||||
<script src="https://vjs.zencdn.net/8.10.0/video.min.js"></script>
|
||||
|
||||
<!-- Artplayer CDN -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.js"></script>
|
||||
|
||||
<!-- Plyr CDN -->
|
||||
<link rel="stylesheet" href="https://cdn.plyr.io/3.7.8/plyr.css" />
|
||||
<script src="https://cdn.plyr.io/3.7.8/plyr.js"></script>
|
||||
|
||||
<!-- Video Player Modal -->
|
||||
<div class="modal fade" id="videoModal" tabindex="-1" role="dialog" aria-labelledby="videoModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-xl" role="document">
|
||||
<div class="modal-content" style="background: #0f172a; border-radius: 12px;">
|
||||
<div class="modal-header" style="border-bottom: 1px solid rgba(255,255,255,0.1);">
|
||||
<h5 class="modal-title" id="videoModalLabel" style="color: #f1f5f9;">비디오 플레이어</h5>
|
||||
<button type="button" class="close" data-dismiss="modal" aria-label="Close" style="color: #f1f5f9;">
|
||||
<span aria-hidden="true">×</span>
|
||||
</button>
|
||||
<div class="ml-auto d-flex align-items-center">
|
||||
<select id="player-select" class="form-control form-control-sm mr-3" style="width: auto; background: rgba(255,255,255,0.1); color: white; border: 1px solid rgba(255,255,255,0.2);">
|
||||
<option value="videojs">VideoJS</option>
|
||||
<option value="artplayer">Artplayer</option>
|
||||
<option value="plyr">Plyr</option>
|
||||
</select>
|
||||
<button type="button" class="close" data-dismiss="modal" aria-label="Close" style="color: #f1f5f9;">
|
||||
<span aria-hidden="true">×</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-body" style="padding: 0;">
|
||||
<div class="video-container">
|
||||
<video id="video-player" class="video-js vjs-big-play-centered vjs-theme-fantasy m-auto" controls preload="auto" playsinline webkit-playsinline>
|
||||
<p class="vjs-no-js">JavaScript가 필요합니다.</p>
|
||||
</video>
|
||||
<!-- Video.js Player -->
|
||||
<div id="videojs-container" style="width: 100%; height: 100%;">
|
||||
<video id="video-player" class="video-js vjs-big-play-centered vjs-theme-fantasy m-auto" controls preload="auto" playsinline webkit-playsinline>
|
||||
<p class="vjs-no-js">JavaScript가 필요합니다.</p>
|
||||
</video>
|
||||
</div>
|
||||
<!-- Artplayer Container -->
|
||||
<div id="artplayer-container" style="display: none; width: 100%; height: 100%; min-height: 450px;"></div>
|
||||
<!-- Plyr Container -->
|
||||
<div id="plyr-container" style="display: none; width: 100%; height: 100%;">
|
||||
<video id="plyr-player" playsinline controls style="width: 100%; height: 100%;"></video>
|
||||
</div>
|
||||
<!-- 화면 꽉 채우기 토글 버튼 (모바일용) -->
|
||||
<button id="btn-video-zoom" class="video-zoom-btn" title="화면 비율 조절">
|
||||
<i class="fa fa-expand"></i>
|
||||
|
||||
@@ -1,410 +1,536 @@
|
||||
{% extends "base.html" %}
|
||||
{% block content %}
|
||||
<link rel="stylesheet" href="{{ url_for('.static', filename='css/mobile_custom.css') }}"/>
|
||||
<link rel="stylesheet" href="{{ url_for('.static', filename='css/' ~ arg['sub'] ~ '.css') }}"/>
|
||||
<link rel="stylesheet" href="{{ url_for('.static', filename='css/mobile_custom.css') }}"/>
|
||||
<link rel="stylesheet" href="{{ url_for('.static', filename='css/' ~ arg['sub'] ~ '.css') }}"/>
|
||||
|
||||
<div class="content-cloak">
|
||||
<div class="d-flex justify-content-start align-items-center gap-2 mb-4">
|
||||
<button id="reset_btn" class="btn custom-btn btn-reset-queue"><i class="fa fa-refresh mr-2"></i> 초기화</button>
|
||||
<button id="delete_completed_btn" class="btn custom-btn btn-delete-completed"><i class="fa fa-trash-o mr-2"></i> 완료 삭제</button>
|
||||
<button id="go_gdm_btn" class="btn custom-btn btn-gdm"><i class="fa fa-download mr-2"></i> Go GDM</button>
|
||||
</div>
|
||||
</div>
|
||||
<style>
|
||||
.queue-header-container {
|
||||
display: flex; justify-content: space-between; align-items: flex-end;
|
||||
margin-bottom: 20px; border-bottom: 1px solid rgba(16, 185, 129, 0.2); padding-bottom: 10px;
|
||||
}
|
||||
.queue-title { color: var(--forest-accent); font-weight: 700; margin: 0; }
|
||||
.queue-meta { font-size: 12px; color: #6ee7b7; opacity: 0.6; }
|
||||
|
||||
.custom-queue-table {
|
||||
background: rgba(6, 78, 59, 0.2); border-collapse: separate; border-spacing: 0 4px; color: #ecfdf5;
|
||||
}
|
||||
.custom-queue-table thead th {
|
||||
background: rgba(2, 44, 34, 0.8) !important; color: #6ee7b7; font-size: 13px;
|
||||
text-transform: uppercase; border: none !important; padding: 12px 8px !important;
|
||||
text-align: center;
|
||||
}
|
||||
.custom-queue-table tbody tr {
|
||||
background: rgba(6, 78, 59, 0.3); transition: all 0.2s;
|
||||
}
|
||||
.custom-queue-table tbody tr:hover { background: rgba(6, 78, 59, 0.5) !important; }
|
||||
.custom-queue-table td { border: none !important; vertical-align: middle !important; padding: 14px 8px !important; }
|
||||
|
||||
/* Badges & Status */
|
||||
.badge-status {
|
||||
padding: 4px 10px; border-radius: 6px; font-size: 11px; font-weight: 700;
|
||||
display: inline-block; min-width: 60px; text-align: center;
|
||||
}
|
||||
.status-downloading { background: rgba(16, 185, 129, 0.2); color: #34d399; border: 1px solid rgba(16, 185, 129, 0.3); }
|
||||
.status-wait { background: rgba(251, 191, 36, 0.1); color: #fbbf24; border: 1px solid rgba(251, 191, 36, 0.2); }
|
||||
.status-completed { background: rgba(59, 130, 246, 0.2); color: #60a5fa; border: 1px solid rgba(59, 130, 246, 0.3); }
|
||||
.status-fail { background: rgba(239, 68, 68, 0.2); color: #f87171; border: 1px solid rgba(239, 68, 68, 0.3); }
|
||||
|
||||
/* Progress Bar */
|
||||
.custom-progress { height: 18px; background: rgba(0,0,0,0.4); border-radius: 9px; overflow: hidden; border: 1px solid rgba(16, 185, 129, 0.1); }
|
||||
.custom-progress .progress-bar {
|
||||
background: linear-gradient(90deg, #10b981, #059669) !important;
|
||||
font-weight: 700; font-size: 11px;
|
||||
transition: width 0.4s ease-out;
|
||||
box-shadow: inset 0 1px 2px rgba(0,0,0,0.1);
|
||||
}
|
||||
|
||||
/* Action Buttons */
|
||||
.action-btn-mini {
|
||||
width: 32px; height: 32px; border-radius: 8px; border: none; font-size: 14px;
|
||||
display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.2s;
|
||||
}
|
||||
.action-btn-mini.btn-danger { background: rgba(239, 68, 68, 0.2); color: #f87171; border: 1px solid rgba(239, 68, 68, 0.3); }
|
||||
.action-btn-mini.btn-danger:hover { background: #ef4444; color: white; transform: scale(1.1); }
|
||||
.action-btn-mini.btn-warning { background: rgba(245, 158, 11, 0.2); color: #fbbf24; border: 1px solid rgba(245, 158, 11, 0.3); }
|
||||
.action-btn-mini.btn-warning:hover { background: #f59e0b; color: white; transform: scale(1.1); }
|
||||
|
||||
<!-- Desktop Table View - Simplified -->
|
||||
<div class="table-responsive d-none d-md-block">
|
||||
<table id="result_table" class="table table-sm tableRowHover">
|
||||
<thead class="thead-dark">
|
||||
<tr>
|
||||
<th style="width:30%; text-align:left; padding-left:16px;">파일명</th>
|
||||
<th style="width:10%; text-align:center;">상태</th>
|
||||
<th style="width:30%; text-align:center;">진행률</th>
|
||||
<th style="width:12%; text-align:center;">속도</th>
|
||||
<th style="width:10%; text-align:center;">시작시간</th>
|
||||
<th style="width:8%; text-align:center;">Action</th>
|
||||
</tr>
|
||||
.action-btn-group { display: flex; justify-content: center; gap: 4px; }
|
||||
|
||||
.header-buttons { display: flex; gap: 10px; align-items: center; }
|
||||
.queue-btn-top {
|
||||
display: flex; align-items: center; gap: 6px; padding: 6px 14px;
|
||||
border: none; border-radius: 8px; font-weight: 600; font-size: 13px;
|
||||
cursor: pointer; transition: all 0.3s ease;
|
||||
}
|
||||
.queue-btn-top.btn-danger { background: rgba(239, 68, 68, 0.2); color: #f87171; border: 1px solid rgba(239, 68, 68, 0.3); }
|
||||
.queue-btn-top.btn-danger:hover { background: #ef4444; color: white; box-shadow: 0 0 15px rgba(239, 68, 68, 0.4); }
|
||||
.queue-btn-top.btn-warning { background: rgba(245, 158, 11, 0.2); color: #fbbf24; border: 1px solid rgba(245, 158, 11, 0.3); }
|
||||
.queue-btn-top.btn-warning:hover { background: #f59e0b; color: white; box-shadow: 0 0 15px rgba(245, 158, 11, 0.4); }
|
||||
|
||||
/* Details */
|
||||
.queue-detail-container { color: #d1fae5; font-size: 13px; }
|
||||
.detail-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 10px 20px; }
|
||||
.detail-item { display: flex; gap: 10px; align-items: flex-start; }
|
||||
.detail-item .label { color: #6ee7b7; font-weight: 700; min-width: 100px; opacity: 0.7; font-size: 11px; text-transform: uppercase; }
|
||||
.detail-item .value { color: #ecfdf5; word-break: break-all; }
|
||||
|
||||
/* Smooth Load */
|
||||
.content-cloak { opacity: 0; transition: opacity 0.5s ease-out; }
|
||||
.content-cloak.visible { opacity: 1; }
|
||||
|
||||
/* Mobile Friendly Card Layout - Revamped */
|
||||
.mobile-queue-container { display: none; flex-direction: column; gap: 8px; padding: 2px; width: 100% !important; margin: 0 !important; }
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.table-responsive-custom { display: none; }
|
||||
.mobile-queue-container { display: flex; }
|
||||
.queue-header-container {
|
||||
flex-direction: column; align-items: flex-start; gap: 8px;
|
||||
margin-top: 50px; padding: 10px 5px !important; margin-bottom: 10px;
|
||||
}
|
||||
.header-buttons { width: 100%; display: flex; gap: 8px; }
|
||||
.queue-btn-top { flex: 1; justify-content: center; font-size: 11px !important; padding: 10px !important; }
|
||||
.queue-meta { font-size: 10px; margin-top: 4px; }
|
||||
|
||||
/* Ensure breadcrumb span doesn't force width */
|
||||
#menu_module_div span.nav-link {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
max-width: 150px;
|
||||
white-space: nowrap !important;
|
||||
}
|
||||
|
||||
/* Header buttons wrap and layout */
|
||||
.queue-header-container { padding-top: 60px !important; }
|
||||
.header-buttons { flex-wrap: wrap !important; gap: 6px !important; }
|
||||
.queue-btn-top {
|
||||
flex: 1 1 45% !important; /* Allow two buttons per row if space exists, or wrap */
|
||||
min-width: 120px;
|
||||
}
|
||||
|
||||
/* Ensure breadcrumb span doesn't force width - moved up */
|
||||
}
|
||||
|
||||
.mobile-queue-card {
|
||||
background: linear-gradient(135deg, rgba(6, 78, 59, 0.4) 0%, rgba(2, 44, 34, 0.6) 100%);
|
||||
border: 1px solid rgba(16, 185, 129, 0.25);
|
||||
border-radius: 10px;
|
||||
padding: 12px 10px;
|
||||
box-shadow: 0 4px 15px rgba(0,0,0,0.3);
|
||||
width: 100% !important;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.mobile-card-top { display: flex; gap: 8px; align-items: flex-start; margin-bottom: 10px; }
|
||||
.mobile-card-idx-badge {
|
||||
background: rgba(16, 185, 129, 0.2); color: #6ee7b7; font-size: 10px;
|
||||
padding: 2px 6px; border-radius: 4px; font-weight: 800; border: 1px solid rgba(16, 185, 129, 0.3);
|
||||
}
|
||||
.mobile-card-filename { color: #ecfdf5; font-weight: 700; font-size: 13.5px; line-height: 1.4; word-break: break-all; flex: 1; }
|
||||
|
||||
.mobile-card-progress-section {
|
||||
background: rgba(0,0,0,0.2); padding: 10px; border-radius: 8px; margin-bottom: 10px;
|
||||
border: 1px solid rgba(255,255,255,0.05);
|
||||
}
|
||||
.mobile-progress-label { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; }
|
||||
.mobile-status-text { font-size: 11px; font-weight: 800; text-transform: uppercase; }
|
||||
.mobile-percent-text { font-size: 14px; font-weight: 900; color: #10b981; }
|
||||
|
||||
.mobile-progress-bar-container { height: 8px; background: rgba(0,0,0,0.5); border-radius: 4px; overflow: hidden; margin-top: 2px; }
|
||||
.mobile-progress-bar { background: linear-gradient(90deg, #10b981, #34d399); height: 100%; border-radius: 4px; transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1); }
|
||||
|
||||
.mobile-card-stats { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; margin-bottom: 10px; }
|
||||
.mobile-stat-item {
|
||||
display: flex; align-items: center; gap: 5px; font-size: 11px; color: #94a3b8;
|
||||
background: rgba(0,0,0,0.15); padding: 5px 8px; border-radius: 6px;
|
||||
}
|
||||
.mobile-stat-item i { color: #10b981; width: 12px; text-align: center; }
|
||||
|
||||
.mobile-card-actions { display: flex; gap: 8px; padding-top: 8px; border-top: 1px solid rgba(255,255,255,0.05); justify-content: flex-end; }
|
||||
.mobile-action-btn {
|
||||
padding: 8px 15px; border-radius: 6px; border: none; font-size: 12px; font-weight: 700;
|
||||
display: flex; align-items: center; gap: 6px; transition: opacity 0.2s;
|
||||
}
|
||||
.mobile-action-btn.btn-stop { background: rgba(239, 68, 68, 0.25); color: #f87171; border: 1px solid rgba(239, 68, 68, 0.3); }
|
||||
.mobile-action-btn.btn-delete { background: rgba(245, 158, 11, 0.2); color: #fbbf24; border: 1px solid rgba(245, 158, 11, 0.3); }
|
||||
</style>
|
||||
|
||||
<div class="content-cloak">
|
||||
<div class="queue-header-container">
|
||||
<h4 class="queue-title"><i class="fa fa-download"></i> 다운로드 큐</h4>
|
||||
<div class="header-buttons">
|
||||
<button id="reset_btn" class="queue-btn-top btn-danger">
|
||||
<i class="fa fa-refresh"></i> 초기화
|
||||
</button>
|
||||
<button id="delete_completed_btn" class="queue-btn-top btn-warning">
|
||||
<i class="fa fa-trash"></i> 완료 삭제
|
||||
</button>
|
||||
</div>
|
||||
<div class="queue-meta">실시간 동기화 활성화됨 (3초 주기)</div>
|
||||
</div>
|
||||
|
||||
<div class="table-responsive-custom">
|
||||
<table id="result_table" class="table custom-queue-table tableRowHover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width:5%;">IDX</th>
|
||||
<th style="width:8%;">Plugin</th>
|
||||
<th style="width:10%;">시작시간</th>
|
||||
<th style="width:25%;">파일명</th>
|
||||
<th style="width:8%;">상태</th>
|
||||
<th style="width:18%;">진행률</th>
|
||||
<th style="width:6%;">길이</th>
|
||||
<th style="width:5%;">PF</th>
|
||||
<th style="width:10%;">현재 상태</th>
|
||||
<th style="width:5%;">Action</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="list"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- Mobile Card View -->
|
||||
<div id="list_mobile" class="d-md-none"></div>
|
||||
|
||||
<script type="text/javascript">
|
||||
const package_name = "{{arg['package_name'] }}";
|
||||
const sub = "{{arg['sub'] }}";
|
||||
var current_data = null;
|
||||
|
||||
function on_start(silent = false) {
|
||||
$.ajax({
|
||||
url: '/' + package_name + '/ajax/' + sub + '/entity_list',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: {},
|
||||
dataType: "json",
|
||||
global: !silent,
|
||||
success: function (data) {
|
||||
current_data = data;
|
||||
|
||||
const list_body = $("#list");
|
||||
const list_mobile = $("#list_mobile");
|
||||
|
||||
if (data.length == 0) {
|
||||
list_body.html("<tr><td colspan='6' class='text-center py-5'><div class='empty-state'><i class='fa fa-inbox fa-3x mb-3' style='opacity:0.3'></i><h5>작업이 없습니다</h5></div></td></tr>");
|
||||
list_mobile.html("<div class='text-center p-5'><i class='fa fa-inbox fa-3x mb-3' style='opacity:0.3'></i><h5>작업이 없습니다</h5></div>");
|
||||
} else {
|
||||
// Table View update
|
||||
var str_table = '';
|
||||
for (i in data) str_table += make_item(data[i]);
|
||||
list_body.html(str_table);
|
||||
|
||||
// Mobile Card View update
|
||||
var str_mobile = '';
|
||||
for (i in data) str_mobile += make_item_mobile(data[i]);
|
||||
list_mobile.html(str_mobile);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
$(document).ready(function () {
|
||||
const socket_url = window.location.protocol + "//" + document.domain + ":" + location.port + "/anime_downloader/anilife/queue";
|
||||
const socket = io.connect(socket_url);
|
||||
|
||||
socket.on('connect', function() {});
|
||||
|
||||
socket.on('start', function (data) { on_start(); });
|
||||
socket.on('list_refresh', function (data) { on_start(); });
|
||||
socket.on('status', function (data) { status_html(data); });
|
||||
socket.on('add', function (data) {
|
||||
if (current_data == null || current_data.length == 0) {
|
||||
current_data = Array();
|
||||
$("#list").html(make_item(data));
|
||||
$("#list_mobile").html(make_item_mobile(data));
|
||||
} else {
|
||||
$("#list").append(make_item(data));
|
||||
$("#list_mobile").append(make_item_mobile(data));
|
||||
}
|
||||
current_data.push(data);
|
||||
});
|
||||
|
||||
// 3초마다 자동 새로고침
|
||||
setInterval(function() { on_start(true); }, 3000);
|
||||
|
||||
// 초기 로드
|
||||
globalSendCommand('list', null, null, null, function (data) {
|
||||
current_data = data;
|
||||
$("#list").html('');
|
||||
$("#list_mobile").html('');
|
||||
if (data.length == 0) {
|
||||
$("#list").html("<tr><td colspan='6' class='text-center py-5'><div class='empty-state'><i class='fa fa-inbox fa-3x mb-3' style='opacity:0.3'></i><h5>작업이 없습니다</h5></div></td></tr>");
|
||||
$("#list_mobile").html("<div class='text-center p-5'><i class='fa fa-inbox fa-3x mb-3' style='opacity:0.3'></i><h5>작업이 없습니다</h5></div>");
|
||||
} else {
|
||||
var str_table = '';
|
||||
var str_mobile = '';
|
||||
for (i in data) {
|
||||
str_table += make_item(data[i]);
|
||||
str_mobile += make_item_mobile(data[i]);
|
||||
}
|
||||
$("#list").html(str_table);
|
||||
$("#list_mobile").html(str_mobile);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
$("body").on('click', '#stop_btn', function (e) {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
var idx = $(this).data('idx');
|
||||
globalSendCommand('stop', idx, null, null, function (ret) { on_start(); });
|
||||
});
|
||||
|
||||
function make_item_mobile(data) {
|
||||
var statusClass = get_status_class(data.status_str);
|
||||
var str = '<div class="queue-card mb-3" id="card_' + data.idx + '">';
|
||||
str += ' <div class="card-header-flex">';
|
||||
str += ' <span id="card_status_kor_' + data.idx + '" class="status-badge ' + statusClass + '">' + data.status_kor + '</span>';
|
||||
str += ' </div>';
|
||||
str += ' <div class="card-content">';
|
||||
str += ' <div class="card-filename">' + data.filename + '</div>';
|
||||
str += ' <div class="progress mt-3 mb-2" style="height: 8px;">';
|
||||
str += ' <div id="card_progress_bar_' + data.idx + '" class="progress-bar" style="width:' + data.percent + '%;"></div>';
|
||||
str += ' </div>';
|
||||
str += ' <div class="card-meta">';
|
||||
str += ' <div class="meta-item"><i class="fa fa-bolt"></i> <span id="card_current_speed_' + data.idx + '">' + (data.current_speed || '-') + '</span></div>';
|
||||
str += ' <div class="meta-item"><i class="fa fa-clock-o"></i> <span>' + (data.start_time || '-') + '</span></div>';
|
||||
str += ' </div>';
|
||||
str += ' </div>';
|
||||
str += ' <div id="card_button_' + data.idx + '" class="card-footer-actions">';
|
||||
if (data.status_str == 'DOWNLOADING' || data.status_str == 'EXTRACTING' || data.status_str == 'PENDING') {
|
||||
str += ' <button id="stop_btn" class="action-btn btn-stop w-100" data-idx="' + data.idx + '"><i class="fa fa-stop mr-1"></i> 중지</button>';
|
||||
}
|
||||
str += ' </div>';
|
||||
str += '</div>';
|
||||
return str;
|
||||
}
|
||||
|
||||
function make_item(data) {
|
||||
var statusClass = get_status_class(data.status_str);
|
||||
var str = '<tr id="tr1_' + data.idx + '">';
|
||||
str += '<td style="text-align:left; padding-left:16px; max-width:300px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;" title="' + data.filename + '">' + data.filename + '</td>';
|
||||
str += '<td id="status_' + data.idx + '" style="text-align:center;"><span class="status-badge ' + statusClass + '">' + data.status_kor + '</span></td>';
|
||||
str += '<td style="text-align:center;"><div class="progress" style="height:20px;"><div id="progress_' + data.idx + '" class="progress-bar" style="width:' + data.percent + '%">' + data.percent + '%</div></div></td>';
|
||||
str += '<td id="current_speed_' + data.idx + '" style="text-align:center;">' + (data.current_speed || '-') + '</td>';
|
||||
str += '<td style="text-align:center; font-size:0.85em;">' + (data.start_time ? data.start_time.split(' ')[1] || data.start_time : '-') + '</td>';
|
||||
str += '<td id="button_' + data.idx + '" style="text-align:center;">';
|
||||
if (data.status_str == 'DOWNLOADING' || data.status_str == 'EXTRACTING' || data.status_str == 'PENDING') {
|
||||
str += '<button id="stop_btn" class="action-btn btn-stop" data-idx="' + data.idx + '"><i class="fa fa-stop"></i></button>';
|
||||
}
|
||||
str += '</td>';
|
||||
str += '</tr>';
|
||||
return str;
|
||||
}
|
||||
|
||||
function get_status_class(status_str) {
|
||||
var s = (status_str || '').toLowerCase();
|
||||
if (s == 'completed') return 'status-completed';
|
||||
if (s == 'downloading') return 'status-downloading';
|
||||
if (s == 'extracting') return 'status-extracting';
|
||||
if (s == 'pending') return 'status-pending';
|
||||
if (s == 'error' || s == 'fail') return 'status-fail';
|
||||
if (s == 'cancelled') return 'status-cancelled';
|
||||
return 'status-pending';
|
||||
}
|
||||
|
||||
function status_html(data) {
|
||||
// Table Update
|
||||
var progress = document.getElementById("progress_" + data.idx);
|
||||
if (progress) {
|
||||
progress.style.width = data.percent + '%';
|
||||
progress.innerHTML = data.percent + '%';
|
||||
var statusEl = document.getElementById("status_" + data.idx);
|
||||
if (statusEl) statusEl.innerHTML = '<span class="status-badge ' + get_status_class(data.status_str) + '">' + data.status_kor + '</span>';
|
||||
var speedEl = document.getElementById("current_speed_" + data.idx);
|
||||
if (speedEl) speedEl.innerHTML = data.current_speed || '-';
|
||||
}
|
||||
|
||||
// Mobile Card Update
|
||||
var card_progress = document.getElementById("card_progress_bar_" + data.idx);
|
||||
if (card_progress) {
|
||||
card_progress.style.width = data.percent + '%';
|
||||
var status_badge = document.getElementById("card_status_kor_" + data.idx);
|
||||
if (status_badge) {
|
||||
status_badge.innerHTML = data.status_kor;
|
||||
status_badge.className = 'status-badge ' + get_status_class(data.status_str);
|
||||
}
|
||||
var card_speed = document.getElementById("card_current_speed_" + data.idx);
|
||||
if (card_speed) card_speed.innerHTML = data.current_speed || '-';
|
||||
}
|
||||
}
|
||||
|
||||
$("body").on('click', '#reset_btn', function (e) {
|
||||
e.preventDefault();
|
||||
if (!confirm('모든 항목을 초기화하시겠습니까?')) return;
|
||||
queue_command({'command': 'reset', 'entity_id': -1});
|
||||
});
|
||||
|
||||
$("body").on('click', '#delete_completed_btn', function (e) {
|
||||
e.preventDefault();
|
||||
queue_command({'command': 'delete_completed', 'entity_id': -1});
|
||||
});
|
||||
|
||||
$("body").on('click', '#go_gdm_btn', function (e) {
|
||||
e.preventDefault();
|
||||
window.location.href = '/gommi_downloader_manager/queue/list';
|
||||
});
|
||||
|
||||
function queue_command(data) {
|
||||
$.ajax({
|
||||
url: '/' + package_name + '/ajax/' + sub + '/queue_command',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: data,
|
||||
dataType: "json",
|
||||
success: function (ret) {
|
||||
if (ret.ret == 'notify') {
|
||||
$.notify('<strong>' + ret.log + '</strong>', {type: 'warning'});
|
||||
} else if (ret.ret == 'success' || ret == true) {
|
||||
$.notify('명령을 완료했습니다.', {type: 'success'});
|
||||
}
|
||||
on_start();
|
||||
}
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
/* ========== Cosmic Violet Theme (Anilife Queue) ========== */
|
||||
body {
|
||||
background: linear-gradient(135deg, #1e1b4b 0%, #312e81 40%, #4c1d95 100%) !important;
|
||||
background-attachment: fixed;
|
||||
color: #e0e7ff;
|
||||
min-height: 100vh;
|
||||
font-family: 'Inter', 'Noto Sans KR', system-ui, sans-serif;
|
||||
}
|
||||
|
||||
/* 좌우 여백 축소 */
|
||||
.container, .container-fluid {
|
||||
max-width: 100% !important;
|
||||
padding-left: 12px !important;
|
||||
padding-right: 12px !important;
|
||||
}
|
||||
#content, .content, main {
|
||||
padding-left: 8px !important;
|
||||
padding-right: 8px !important;
|
||||
}
|
||||
|
||||
/* Table Styling */
|
||||
.table {
|
||||
color: #e0e7ff !important;
|
||||
background: rgba(49, 46, 129, 0.4) !important;
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.table thead th, .thead-dark th {
|
||||
background: linear-gradient(135deg, rgba(76, 29, 149, 0.9) 0%, rgba(49, 46, 129, 0.9) 100%) !important;
|
||||
color: #c4b5fd !important;
|
||||
border-color: rgba(167, 139, 250, 0.2) !important;
|
||||
font-weight: 600;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
.table tbody tr {
|
||||
background: rgba(30, 27, 75, 0.6) !important;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
.table tbody tr:hover {
|
||||
background: rgba(76, 29, 149, 0.5) !important;
|
||||
}
|
||||
.table td, .table th {
|
||||
border-color: rgba(167, 139, 250, 0.15) !important;
|
||||
color: #e0e7ff !important;
|
||||
vertical-align: middle !important;
|
||||
}
|
||||
|
||||
/* Status Badges */
|
||||
.status-badge {
|
||||
font-size: 11px; font-weight: 700; padding: 4px 10px; border-radius: 50rem;
|
||||
text-transform: uppercase; letter-spacing: 0.3px; display: inline-block;
|
||||
}
|
||||
.status-completed { background: rgba(34, 197, 94, 0.25); color: #4ade80; border: 1px solid rgba(34, 197, 94, 0.4); }
|
||||
.status-downloading { background: rgba(59, 130, 246, 0.25); color: #60a5fa; border: 1px solid rgba(59, 130, 246, 0.4); }
|
||||
.status-extracting { background: rgba(168, 85, 247, 0.25); color: #c084fc; border: 1px solid rgba(168, 85, 247, 0.4); }
|
||||
.status-pending { background: rgba(148, 163, 184, 0.2); color: #94a3b8; border: 1px solid rgba(148, 163, 184, 0.3); }
|
||||
.status-fail { background: rgba(239, 68, 68, 0.25); color: #f87171; border: 1px solid rgba(239, 68, 68, 0.4); }
|
||||
.status-cancelled { background: rgba(107, 114, 128, 0.25); color: #9ca3af; border: 1px solid rgba(107, 114, 128, 0.4); }
|
||||
|
||||
/* Progress Bar */
|
||||
.progress {
|
||||
background: rgba(49, 46, 129, 0.6) !important;
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.progress-bar {
|
||||
background: linear-gradient(90deg, #8b5cf6 0%, #a78bfa 100%) !important;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
|
||||
/* Buttons */
|
||||
.custom-btn {
|
||||
padding: 8px 18px; border-radius: 10px; font-weight: 600; font-size: 13px;
|
||||
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
display: inline-flex; align-items: center; justify-content: center; color: white !important;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
.btn-reset-queue { background: rgba(59, 130, 246, 0.2); border-color: rgba(59, 130, 246, 0.3); }
|
||||
.btn-reset-queue:hover { background: rgba(59, 130, 246, 0.4); transform: translateY(-2px); }
|
||||
.btn-delete-completed { background: rgba(239, 68, 68, 0.2); border-color: rgba(239, 68, 68, 0.3); }
|
||||
.btn-delete-completed:hover { background: rgba(239, 68, 68, 0.4); transform: translateY(-2px); }
|
||||
.btn-gdm { background: rgba(56, 189, 248, 0.2); border-color: rgba(56, 189, 248, 0.3); }
|
||||
.btn-gdm:hover { background: rgba(56, 189, 248, 0.4); transform: translateY(-2px); }
|
||||
|
||||
.action-btn {
|
||||
padding: 4px 10px; border-radius: 6px; font-size: 12px; font-weight: 600;
|
||||
transition: all 0.2s; border: 1px solid transparent; background: transparent;
|
||||
}
|
||||
.btn-stop { background: rgba(239, 68, 68, 0.2); color: #f87171; border-color: rgba(239, 68, 68, 0.3); }
|
||||
.btn-stop:hover { background: #ef4444; color: white; }
|
||||
|
||||
/* Mobile Card Styles */
|
||||
.queue-card {
|
||||
background: rgba(30, 27, 75, 0.5);
|
||||
backdrop-filter: blur(12px);
|
||||
border: 1px solid rgba(167, 139, 250, 0.15);
|
||||
border-radius: 16px;
|
||||
overflow: hidden;
|
||||
transition: all 0.3s;
|
||||
}
|
||||
.queue-card:hover { border-color: rgba(167, 139, 250, 0.4); transform: translateY(-2px); }
|
||||
.card-header-flex {
|
||||
padding: 10px 16px;
|
||||
background: rgba(49, 46, 129, 0.3);
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
}
|
||||
.card-content { padding: 16px; }
|
||||
.card-filename {
|
||||
font-size: 15px; font-weight: 600; color: #f8fafc;
|
||||
line-height: 1.4; word-break: break-all;
|
||||
}
|
||||
.card-meta {
|
||||
display: flex; justify-content: space-between; margin-top: 12px;
|
||||
padding-top: 12px; border-top: 1px solid rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
.meta-item {
|
||||
display: flex; align-items: center; gap: 6px;
|
||||
font-size: 12px; color: #94a3b8;
|
||||
}
|
||||
.meta-item i { color: #a78bfa; }
|
||||
.card-footer-actions { padding: 0 16px 16px 16px; }
|
||||
|
||||
/* Empty State */
|
||||
.empty-state { color: #64748b; }
|
||||
|
||||
/* Nav Pills Override */
|
||||
ul.nav.nav-pills.bg-light {
|
||||
background-color: rgba(30, 41, 59, 0.6) !important;
|
||||
backdrop-filter: blur(10px);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
border-radius: 50rem !important;
|
||||
padding: 6px !important;
|
||||
display: inline-flex !important;
|
||||
width: auto !important;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
ul.nav.nav-pills .nav-item { margin: 2px; }
|
||||
ul.nav.nav-pills .nav-link {
|
||||
border-radius: 50rem !important;
|
||||
padding: 8px 20px !important;
|
||||
color: #94a3b8 !important;
|
||||
font-weight: 600;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
ul.nav.nav-pills .nav-link:hover { background-color: rgba(255, 255, 255, 0.1); color: #fff !important; }
|
||||
ul.nav.nav-pills .nav-link.active {
|
||||
background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%) !important;
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
/* Mobile Fix */
|
||||
@media (max-width: 768px) {
|
||||
body { overflow-x: hidden !important; }
|
||||
.container, .container-fluid, .row, form {
|
||||
width: 100% !important; max-width: 100% !important;
|
||||
padding-left: 4px !important; padding-right: 4px !important;
|
||||
margin-left: 0 !important; margin-right: 0 !important;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<div id="mobile_list" class="mobile-queue-container"></div>
|
||||
</div>
|
||||
|
||||
<script type="text/javascript">
|
||||
var PACKAGE_NAME = "{{ arg['package_name'] }}";
|
||||
var MODULE_NAME = "{{ arg['module_name'] }}";
|
||||
var current_list_length = 0;
|
||||
|
||||
$(document).ready(function(){
|
||||
setTimeout(function() {
|
||||
$('.content-cloak, #menu_module_div, #menu_page_div').addClass('visible');
|
||||
}, 100);
|
||||
$(".content-cloak").addClass("visible");
|
||||
|
||||
var protocol = location.protocol;
|
||||
var socketUrl = protocol + "//" + document.domain + ":" + location.port;
|
||||
|
||||
// Queue 전용 소켓 시도
|
||||
var queueSocket = null;
|
||||
try {
|
||||
queueSocket = io.connect(socketUrl + '/anime_downloader/linkkf/queue');
|
||||
} catch (e) {
|
||||
console.error('Queue socket error:', e);
|
||||
}
|
||||
|
||||
var frameworkSocket = null;
|
||||
try {
|
||||
frameworkSocket = io.connect(socketUrl + '/framework');
|
||||
frameworkSocket.on('linkkf_status', function(data) {
|
||||
status_html(data);
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('Framework socket error:', e);
|
||||
}
|
||||
|
||||
var socket = queueSocket;
|
||||
if (socket) {
|
||||
socket.on('status_change', function(data) { button_html(data); });
|
||||
socket.on('status', function(data){ status_html(data); });
|
||||
socket.on('last', function(data){ status_html(data); button_html(data); });
|
||||
}
|
||||
|
||||
// GDM 전용 소켓 추가 핸들링 (전역 업데이트 수신용)
|
||||
var gdmSocket = null;
|
||||
try {
|
||||
gdmSocket = io.connect(socketUrl + '/gommi_downloader_manager');
|
||||
gdmSocket.on('status', function(data) {
|
||||
// 이 모듈과 관련된 작업만 처리
|
||||
if (data.caller_plugin === PACKAGE_NAME + '_' + MODULE_NAME) {
|
||||
// GDM 데이터를 큐 형식으로 변환하여 UI 업데이트
|
||||
// 수동 새로고침 없이 실시간 반영을 위해 renderList 호출 주기를 짧게 하거나 직접 UI 갱신
|
||||
silentFetchList(function(newList) {
|
||||
renderList(newList);
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('GDM socket error:', e);
|
||||
}
|
||||
|
||||
on_start();
|
||||
refreshIntervalId = setInterval(autoRefreshList, 3000);
|
||||
});
|
||||
|
||||
var refreshIntervalId = null;
|
||||
|
||||
function silentFetchList(callback) {
|
||||
$.ajax({
|
||||
url: '/' + PACKAGE_NAME + '/ajax/' + MODULE_NAME + '/command',
|
||||
type: 'POST',
|
||||
cache: false,
|
||||
global: false,
|
||||
data: {command: 'list'},
|
||||
dataType: 'json',
|
||||
success: function(data) { if (callback) callback(data); }
|
||||
});
|
||||
}
|
||||
|
||||
function autoRefreshList() {
|
||||
silentFetchList(function(data) {
|
||||
if (data.length !== current_list_length) {
|
||||
current_list_length = data.length;
|
||||
renderList(data);
|
||||
}
|
||||
|
||||
var hasActiveDownload = false;
|
||||
if (data && data.length > 0) {
|
||||
for (var j = 0; j < data.length; j++) {
|
||||
if (data[j].status_str === 'DOWNLOADING' || data[j].status_str === 'WAITING' || data[j].status_str === 'STARTED') {
|
||||
hasActiveDownload = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasActiveDownload && refreshIntervalId) {
|
||||
clearInterval(refreshIntervalId);
|
||||
refreshIntervalId = null;
|
||||
}
|
||||
if (hasActiveDownload && !refreshIntervalId) {
|
||||
refreshIntervalId = setInterval(autoRefreshList, 3000);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function on_start() {
|
||||
silentFetchList(function(data) {
|
||||
current_list_length = data.length;
|
||||
renderList(data);
|
||||
});
|
||||
}
|
||||
|
||||
function renderList(data) {
|
||||
$("#list").html('');
|
||||
$("#mobile_list").html('');
|
||||
if (!data || data.length == 0) {
|
||||
let empty_msg = "<div style='text-align:center; padding: 40px; color: #6ee7b7;'>다운로드 대기 중인 작업이 없습니다.</div>";
|
||||
$("#list").html("<tr><td colspan='10' style='text-align:center; padding: 40px; color: #6ee7b7;'>다운로드 대기 중인 작업이 없습니다.</td></tr>");
|
||||
$("#mobile_list").html(empty_msg);
|
||||
} else {
|
||||
var str = '';
|
||||
var m_str = '';
|
||||
for(var i in data) {
|
||||
str += make_item(data[i]);
|
||||
m_str += make_mobile_item(data[i]);
|
||||
}
|
||||
$("#list").html(str);
|
||||
$("#mobile_list").html(m_str);
|
||||
}
|
||||
}
|
||||
|
||||
$("body").on('click', '#stop_btn', function(e){
|
||||
e.stopPropagation(); e.preventDefault();
|
||||
globalSendCommand('stop', $(this).data('idx'), null, null, function(ret){
|
||||
refresh_item(ret.data);
|
||||
});
|
||||
});
|
||||
|
||||
$("body").on('click', '#reset_btn', function(e){
|
||||
e.preventDefault();
|
||||
globalConfirmModal('초기화 하시겠습니까?', function(){
|
||||
globalSendCommand('reset', null, null, null, function(ret){
|
||||
autoRefreshList();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
$("body").on('click', '#delete_completed_btn', function(e){
|
||||
e.preventDefault();
|
||||
globalSendCommand('delete_completed', null, null, null, function(ret){
|
||||
autoRefreshList();
|
||||
});
|
||||
});
|
||||
|
||||
$("body").on('click', '#delete_btn', function(e){
|
||||
e.stopPropagation(); e.preventDefault();
|
||||
let idx = $(this).data('idx');
|
||||
globalSendCommand('remove', idx, null, null, function(ret){
|
||||
autoRefreshList();
|
||||
});
|
||||
});
|
||||
|
||||
function refresh_item(data) {
|
||||
$('#tr1_'+data.idx).html(make_item1(data));
|
||||
$('#collapse_'+data.idx).html(make_item2(data));
|
||||
}
|
||||
|
||||
function make_item(data) {
|
||||
var str = '<tr id="tr1_'+data.idx+'" style="cursor: pointer;" data-toggle="collapse" data-target="#collapse_'+ data.idx + '" aria-expanded="false" >';
|
||||
str += make_item1(data);
|
||||
str += '</tr>';
|
||||
str += '<tr class="collapse tableRowHoverOff" id="collapse_' + data.idx + '">';
|
||||
str += make_item2(data);
|
||||
str += '</tr>';
|
||||
return str;
|
||||
}
|
||||
|
||||
function make_item1(data) {
|
||||
var str = '<td style="text-align:center;">'+ data.idx + '</td>';
|
||||
str += '<td style="text-align:center;"><span class="badge badge-info">'+ data.callback_id + '</span></td>';
|
||||
str += '<td style="text-align:center; font-size: 12px; color: #6ee7b7;">'+ data.start_time + '</td>';
|
||||
str += '<td style="font-weight: 600;">'+ data.filename + '</td>';
|
||||
|
||||
var status_class = 'status-wait';
|
||||
if (data.status_str === 'DOWNLOADING') status_class = 'status-downloading';
|
||||
else if (data.status_str === 'COMPLETED') status_class = 'status-completed';
|
||||
else if (data.status_str === 'STOP') status_class = 'status-fail';
|
||||
|
||||
str += '<td id="status_'+data.idx+'" style="text-align:center;"><span class="badge-status ' + status_class + '">'+ data.status_kor + '</span></td>';
|
||||
|
||||
var visi = (parseInt(data.percent) > 0) ? 'visible' : 'hidden';
|
||||
str += '<td><div class="progress custom-progress"><div id="progress_'+data.idx+'" class="progress-bar" style="visibility: '+visi+'; width:'+data.percent+'%">'+data.percent +'%</div></div></td>';
|
||||
|
||||
str += '<td style="text-align:center;">'+ data.duration_str + '</td>';
|
||||
str += '<td id="current_pf_count_'+data.idx+'" style="text-align:center; color: #f87171;">'+ data.current_pf_count + '</td>';
|
||||
str += '<td style="text-align:center; font-size: 13px;"><div id="current_speed_'+data.idx+'">'+ data.current_speed + '</div><div id="download_time_'+data.idx+'" style="font-size: 11px; opacity: 0.6;">'+ data.download_time + '</div></td>';
|
||||
|
||||
str += '<td id="button_'+data.idx+'" style="text-align:center; padding: 10px 4px !important;">';
|
||||
str += '<div class="action-btn-group">';
|
||||
if (data.status_str == 'DOWNLOADING' || data.status_str == 'WAITING') {
|
||||
str += '<button id="stop_btn" class="action-btn-mini btn-danger" data-idx="'+data.idx+'" title="중지"><i class="fa fa-stop"></i></button>';
|
||||
} else {
|
||||
str += '<button id="delete_btn" class="action-btn-mini btn-warning" data-idx="'+data.idx+'" title="삭제"><i class="fa fa-times"></i></button>';
|
||||
}
|
||||
str += '</div>';
|
||||
str += '</td>';
|
||||
return str;
|
||||
}
|
||||
|
||||
function make_mobile_item(data) {
|
||||
var status_class = 'status-wait';
|
||||
if (data.status_str === 'DOWNLOADING') status_class = 'status-downloading';
|
||||
else if (data.status_str === 'COMPLETED') status_class = 'status-completed';
|
||||
else if (data.status_str === 'STOP') status_class = 'status-fail';
|
||||
|
||||
var str = '<div class="mobile-queue-card" id="mobile_card_'+data.idx+'">';
|
||||
|
||||
// Top Section: Index and Filename
|
||||
str += ' <div class="mobile-card-top">';
|
||||
str += ' <div class="mobile-card-idx-badge">#' + data.idx + '</div>';
|
||||
str += ' <div class="mobile-card-filename">' + data.filename + '</div>';
|
||||
str += ' </div>';
|
||||
|
||||
// Progress Section
|
||||
str += ' <div class="mobile-card-progress-section">';
|
||||
str += ' <div class="mobile-progress-label">';
|
||||
str += ' <div class="mobile-status-text ' + status_class + '-text">' + data.status_kor + '</div>';
|
||||
str += ' <div id="m_percent_' + data.idx + '" class="mobile-percent-text">' + data.percent + '%</div>';
|
||||
str += ' </div>';
|
||||
str += ' <div class="mobile-progress-bar-container">';
|
||||
str += ' <div id="m_progress_bar_' + data.idx + '" class="mobile-progress-bar" style="width:' + data.percent + '%"></div>';
|
||||
str += ' </div>';
|
||||
str += ' </div>';
|
||||
|
||||
// Stats Section
|
||||
str += ' <div class="mobile-card-stats">';
|
||||
str += ' <div class="mobile-stat-item"><i class="fa fa-tachometer"></i><span id="m_speed_' + data.idx + '">' + data.current_speed + '</span></div>';
|
||||
str += ' <div class="mobile-stat-item"><i class="fa fa-hourglass-half"></i><span id="m_time_' + data.idx + '">' + data.download_time + '</span></div>';
|
||||
str += ' <div class="mobile-stat-item"><i class="fa fa-calendar-o"></i><span>' + data.start_time.split(' ')[1] + '</span></div>';
|
||||
str += ' <div class="mobile-stat-item"><i class="fa fa-exclamation-circle"></i><span>PF: ' + data.current_pf_count + '</span></div>';
|
||||
str += ' </div>';
|
||||
|
||||
// Action Section
|
||||
str += ' <div class="mobile-card-actions" id="m_button_' + data.idx + '">';
|
||||
if (data.status_str == 'DOWNLOADING' || data.status_str == 'WAITING') {
|
||||
str += '<button id="stop_btn" class="mobile-action-btn btn-stop" data-idx="'+data.idx+'"><i class="fa fa-stop-circle"></i> 중지</button>';
|
||||
} else {
|
||||
str += '<button id="delete_btn" class="mobile-action-btn btn-delete" data-idx="'+data.idx+'"><i class="fa fa-trash"></i> 삭제</button>';
|
||||
}
|
||||
str += ' </div>';
|
||||
|
||||
str += '</div>';
|
||||
return str;
|
||||
}
|
||||
|
||||
function make_item2(data) {
|
||||
var str = '<td colspan="10" style="background: rgba(0,0,0,0.2); padding: 15px !important;">';
|
||||
str += '<div id="detail_'+data.idx+'" class="queue-detail-container">';
|
||||
str += get_detail(data);
|
||||
str += '</div>';
|
||||
str += '</td>';
|
||||
return str;
|
||||
}
|
||||
|
||||
function get_detail(data) {
|
||||
var str = '<div class="detail-grid">';
|
||||
str += '<div class="detail-item"><span class="label">파일 경로</span><span class="value">' + data.save_fullpath + '</span></div>';
|
||||
str += '<div class="detail-item"><span class="label">URL</span><span class="value text-truncate">' + data.url + '</span></div>';
|
||||
str += '<div class="detail-item"><span class="label">진행 상황</span><span class="value">' + data.percent+ '% (' + data.current_duration + ' / ' + data.duration + ')</span></div>';
|
||||
str += '<div class="detail-item"><span class="label">비트레이트</span><span class="value">' + data.current_bitrate + '</span></div>';
|
||||
str += '<div class="detail-item"><span class="label">허용 에러(PF)</span><span class="value">' + data.max_pf_count + '</span></div>';
|
||||
if (data.status_str == 'COMPLETED') {
|
||||
str += '<div class="detail-item"><span class="label">파일 크기</span><span class="value">' + data.filesize_str + '</span></div>';
|
||||
str += '<div class="detail-item"><span class="label">최종 속도</span><span class="value">' + (data.download_speed || 'N/A') + '</span></div>';
|
||||
}
|
||||
str += '</div>';
|
||||
return str;
|
||||
}
|
||||
|
||||
function button_html(data) {
|
||||
var str = '<div class="action-btn-group">';
|
||||
if (data.status_str == 'DOWNLOADING' || data.status_str == 'WAITING') {
|
||||
str += '<button id="stop_btn" class="action-btn-mini btn-danger" data-idx="'+data.idx+'" title="중지"><i class="fa fa-stop"></i></button>';
|
||||
} else {
|
||||
str += '<button id="delete_btn" class="action-btn-mini btn-warning" data-idx="'+data.idx+'" title="삭제"><i class="fa fa-times"></i></button>';
|
||||
}
|
||||
str += '</div>';
|
||||
$("#button_" + data.idx).html(str);
|
||||
}
|
||||
|
||||
function status_html(data) {
|
||||
var progress = document.getElementById("progress_" + data.idx);
|
||||
if (!progress) return;
|
||||
|
||||
progress.style.width = data.percent+ '%';
|
||||
progress.innerHTML = data.percent+ '%';
|
||||
progress.style.visibility = 'visible';
|
||||
|
||||
var statusEl = document.getElementById("status_" + data.idx);
|
||||
if (statusEl) {
|
||||
var status_class = 'status-wait';
|
||||
if (data.status_str === 'DOWNLOADING') status_class = 'status-downloading';
|
||||
else if (data.status_str === 'COMPLETED') status_class = 'status-completed';
|
||||
else if (data.status_str === 'STOP') status_class = 'status-fail';
|
||||
statusEl.innerHTML = '<span class="badge-status ' + status_class + '">'+ data.status_kor + '</span>';
|
||||
}
|
||||
|
||||
var pfEl = document.getElementById("current_pf_count_" + data.idx);
|
||||
if (pfEl) pfEl.innerHTML = data.current_pf_count;
|
||||
|
||||
var speedEl = document.getElementById("current_speed_" + data.idx);
|
||||
if (speedEl) speedEl.innerHTML = data.current_speed;
|
||||
|
||||
var timeEl = document.getElementById("download_time_" + data.idx);
|
||||
if (timeEl) timeEl.innerHTML = data.download_time;
|
||||
|
||||
var detailEl = document.getElementById("detail_" + data.idx);
|
||||
if (detailEl) detailEl.innerHTML = get_detail(data);
|
||||
|
||||
// Mobile UI Update
|
||||
var mProgressBar = document.getElementById("m_progress_bar_" + data.idx);
|
||||
if (mProgressBar) mProgressBar.style.width = data.percent + '%';
|
||||
|
||||
var mPercent = document.getElementById("m_percent_" + data.idx);
|
||||
if (mPercent) mPercent.innerHTML = data.percent + '%';
|
||||
|
||||
var mSpeed = document.getElementById("m_speed_" + data.idx);
|
||||
if (mSpeed) mSpeed.innerHTML = data.current_speed;
|
||||
|
||||
var mTime = document.getElementById("m_time_" + data.idx);
|
||||
if (mTime) mTime.innerHTML = data.download_time;
|
||||
|
||||
var mButton = document.getElementById("m_button_" + data.idx);
|
||||
if (mButton) {
|
||||
var btn_str = '';
|
||||
if (data.status_str == 'DOWNLOADING' || data.status_str == 'WAITING') {
|
||||
btn_str += '<button id="stop_btn" class="mobile-action-btn btn-stop" data-idx="'+data.idx+'"><i class="fa fa-stop-circle"></i> 중지</button>';
|
||||
} else {
|
||||
btn_str += '<button id="delete_btn" class="mobile-action-btn btn-delete" data-idx="'+data.idx+'"><i class="fa fa-trash"></i> 삭제</button>';
|
||||
}
|
||||
mButton.innerHTML = btn_str;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{% endblock %}
|
||||
|
||||
|
||||
@@ -11,20 +11,10 @@ body {
|
||||
background-attachment: fixed !important;
|
||||
}
|
||||
|
||||
/* Global Container Margin Overrides */
|
||||
/* Global Container Margin Overrides - mobile_custom.css와 통합 */
|
||||
#main_container {
|
||||
width: 100% !important;
|
||||
max-width: 100% !important;
|
||||
padding-left: 15px !important;
|
||||
padding-right: 15px !important;
|
||||
margin-left: 0 !important;
|
||||
margin-right: 0 !important;
|
||||
}
|
||||
.container, .container-fluid:not(.anilife-common-wrapper) {
|
||||
width: 100% !important;
|
||||
max-width: 100% !important;
|
||||
padding-left: 0 !important;
|
||||
padding-right: 0 !important;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -40,7 +30,7 @@ body {
|
||||
</div>
|
||||
|
||||
<form id="program_list">
|
||||
<div class="card p-2 p-md-4 mb-2 mb-md-4 border-0" style="background: rgba(49, 46, 129, 0.6); backdrop-filter: blur(10px); box-shadow: 0 4px 20px rgba(139, 92, 246, 0.2); border-radius: 16px;">
|
||||
<div class="card p-1 p-md-4 mb-2 mb-md-4 border-0" style="background: rgba(49, 46, 129, 0.6); backdrop-filter: blur(10px); box-shadow: 0 4px 20px rgba(139, 92, 246, 0.2); border-radius: 16px;">
|
||||
<div class="form-group mb-0">
|
||||
<label for="code" class="text-white font-weight-bold mb-2" style="color: #c4b5fd !important;">
|
||||
<i class="fa fa-search mr-2" style="color: #a78bfa;"></i>작품 Code
|
||||
@@ -50,14 +40,13 @@ body {
|
||||
placeholder="URL 또는 코드를 입력하세요"
|
||||
style="background: rgba(30, 27, 75, 0.8); color: #e0e7ff; box-shadow: inset 0 2px 4px rgba(0,0,0,0.3); border-radius: 12px 0 0 12px;">
|
||||
<div class="input-group-append">
|
||||
<button id="analysis_btn" class="btn px-2 px-md-4 font-weight-bold" type="button"
|
||||
style="background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%); color: white; box-shadow: 0 0 15px rgba(139, 92, 246, 0.4);">
|
||||
<button id="analysis_btn" class="btn px-3 font-weight-bold" type="button"
|
||||
style="background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%); color: white; box-shadow: 0 0 15px rgba(139, 92, 246, 0.4); min-width: 80px;">
|
||||
<i class="fa fa-cogs mr-1"></i> 분석
|
||||
</button>
|
||||
<button id="go_anilife_btn" class="btn px-2 px-md-3" type="button"
|
||||
style="background: rgba(167, 139, 250, 0.2); border: 1px solid rgba(167, 139, 250, 0.4); color: #c4b5fd; border-radius: 0 12px 12px 0;">
|
||||
<span class="d-none d-md-inline">Go 애니라이프</span>
|
||||
<span class="d-md-none">Go</span>
|
||||
<button id="go_anilife_btn" class="btn px-3 font-weight-bold" type="button"
|
||||
style="background: rgba(167, 139, 250, 0.2); border: 1px solid rgba(167, 139, 250, 0.4); color: #c4b5fd; border-radius: 0 12px 12px 0; min-width: 80px;">
|
||||
GO
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -616,10 +605,16 @@ body {
|
||||
.episode-list-container {
|
||||
margin-top: 20px;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
|
||||
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.episode-list-container {
|
||||
grid-template-columns: 1fr !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* 에피소드 카드 */
|
||||
.episode-card {
|
||||
display: flex;
|
||||
@@ -775,9 +770,12 @@ body {
|
||||
|
||||
/* 모바일 반응형 - Bootstrap 모든 레이아웃 강제 덮어쓰기 */
|
||||
@media (max-width: 768px) {
|
||||
/* 상단 서브메뉴가 SJVA 메인 navbar에 가려지지 않도록 여백 추가 */
|
||||
ul.nav.nav-pills.bg-light {
|
||||
margin-top: 60px !important;
|
||||
/* Ensure breadcrumb span doesn't force width */
|
||||
#menu_module_div span.nav-link {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
max-width: 150px;
|
||||
white-space: nowrap !important;
|
||||
}
|
||||
|
||||
/* 입력창 크기 최적화 */
|
||||
@@ -809,8 +807,8 @@ body {
|
||||
.row, form, #program_list, #program_auto_form, #episode_list {
|
||||
width: 100% !important;
|
||||
max-width: 100% !important;
|
||||
padding-left: 10px !important;
|
||||
padding-right: 10px !important;
|
||||
padding-left: 4px !important; /* 10px -> 4px */
|
||||
padding-right: 4px !important; /* 10px -> 4px */
|
||||
margin-left: 0 !important;
|
||||
margin-right: 0 !important;
|
||||
box-sizing: border-box !important;
|
||||
@@ -868,8 +866,8 @@ body {
|
||||
align-items: center !important;
|
||||
width: 100% !important;
|
||||
max-width: 100% !important;
|
||||
padding: 10px 12px !important;
|
||||
gap: 10px !important;
|
||||
padding: 8px 6px !important; /* 좌우 패딩 대폭 축소 */
|
||||
gap: 6px !important; /* 요소 간 간격 축소 */
|
||||
margin: 0 !important;
|
||||
box-sizing: border-box !important;
|
||||
}
|
||||
|
||||
@@ -197,7 +197,10 @@
|
||||
tmp += '</div>';
|
||||
tmp += '<div class=\"card-body\">'
|
||||
tmp += '<h5 class=\"card-title\">' + data.anime_list[i].title + '</h5>';
|
||||
tmp += '<a href=\"./request?code=' + data.anime_list[i].code + '\" class=\"btn btn-primary cut-text\">' + data.anime_list[i].title + '</a>';
|
||||
tmp += '<div class=\"card-actions\">';
|
||||
tmp += '<a href=\"./request?code=' + data.anime_list[i].code + '\" class=\"btn btn-primary cut-text\"><i class="fa fa-info-circle"></i> 상세</a>';
|
||||
tmp += '<button type=\"button\" class=\"btn btn-sch btn-add-schedule\" data-code=\"' + data.anime_list[i].code + '\" data-title=\"' + data.anime_list[i].title.replace(/"/g, '"') + '\"><i class="fa fa-calendar-plus-o"></i> 스케쥴</button>';
|
||||
tmp += '</div>';
|
||||
tmp += '</div>';
|
||||
tmp += '</div>';
|
||||
tmp += '</div>';
|
||||
@@ -262,7 +265,10 @@
|
||||
tmp += '</div>';
|
||||
tmp += '<div class="card-body">'
|
||||
tmp += '<h5 class="card-title">' + data.anime_list[i].title + '</h5>';
|
||||
tmp += '<a href="' + request_url + '" class="btn btn-primary cut-text">' + data.anime_list[i].title + '</a>';
|
||||
tmp += '<div class="card-actions">';
|
||||
tmp += '<a href="' + request_url + '" class="btn btn-primary cut-text"><i class="fa fa-info-circle"></i> 상세</a>';
|
||||
tmp += '<button type="button" class="btn btn-sch btn-add-schedule" data-code="' + data.anime_list[i].code + '" data-title="' + data.anime_list[i].title.replace(/"/g, '"') + '"><i class="fa fa-calendar-plus-o"></i> 스케쥴</button>';
|
||||
tmp += '</div>';
|
||||
tmp += '</div>';
|
||||
tmp += '</div>';
|
||||
tmp += '</div>';
|
||||
@@ -314,7 +320,10 @@
|
||||
tmp += '</div>';
|
||||
tmp += '<div class="card-body">'
|
||||
tmp += '<h5 class="card-title">' + data.anime_list[i].title + '</h5>';
|
||||
tmp += '<a href="./request?code=' + data.anime_list[i].code + '" class="btn btn-primary cut-text">' + data.anime_list[i].title + '</a>';
|
||||
tmp += '<div class="card-actions">';
|
||||
tmp += '<a href="./request?code=' + data.anime_list[i].code + '" class="btn btn-primary cut-text"><i class="fa fa-info-circle"></i> 상세</a>';
|
||||
tmp += '<button type="button" class="btn btn-sch btn-add-schedule" data-code="' + data.anime_list[i].code + '" data-title="' + data.anime_list[i].title.replace(/"/g, '"') + '"><i class="fa fa-calendar-plus-o"></i> 스케쥴</button>';
|
||||
tmp += '</div>';
|
||||
tmp += '</div>';
|
||||
tmp += '</div>';
|
||||
tmp += '</div>';
|
||||
@@ -578,6 +587,38 @@
|
||||
};
|
||||
|
||||
document.addEventListener("scroll", debounce(onScroll, 300));
|
||||
|
||||
// ================================
|
||||
// 스케쥴 등록 버튼 핸들러
|
||||
// ================================
|
||||
$('body').on('click', '.btn-add-schedule', function(e) {
|
||||
e.preventDefault();
|
||||
var code = $(this).data('code');
|
||||
var title = $(this).data('title');
|
||||
var btn = $(this);
|
||||
|
||||
btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>');
|
||||
|
||||
$.ajax({
|
||||
url: '/' + package_name + '/ajax/' + sub + '/add_schedule',
|
||||
type: 'POST',
|
||||
data: { code: code, title: title },
|
||||
dataType: 'json',
|
||||
success: function(ret) {
|
||||
if (ret.ret === 'success' || ret.ret === 'exist') {
|
||||
$.notify('<strong>' + (ret.ret === 'exist' ? '이미 등록됨' : '스케쥴 등록 완료') + '</strong>', { type: ret.ret === 'exist' ? 'info' : 'success' });
|
||||
} else {
|
||||
$.notify('<strong>등록 실패: ' + (ret.msg || ret.ret) + '</strong>', { type: 'warning' });
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
$.notify('<strong>스케쥴 등록 중 오류</strong>', { type: 'danger' });
|
||||
},
|
||||
complete: function() {
|
||||
btn.prop('disabled', false).html('<i class="fa fa-calendar-plus-o"></i> 스케쥴');
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
<style>
|
||||
button.code-button {
|
||||
@@ -1221,6 +1262,57 @@
|
||||
color: #fff !important;
|
||||
box-shadow: 0 4px 12px rgba(37, 99, 235, 0.4);
|
||||
}
|
||||
/* Card Actions Layout */
|
||||
.card-actions {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
margin-top: auto;
|
||||
}
|
||||
.card-actions .btn {
|
||||
font-size: 13px;
|
||||
padding: 8px 12px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
.card-actions .btn-sch {
|
||||
background: linear-gradient(135deg, #f472b6 0%, #ec4899 100%) !important;
|
||||
border: none !important;
|
||||
color: white !important;
|
||||
}
|
||||
.card-actions .btn-sch:hover {
|
||||
background: linear-gradient(135deg, #ec4899 0%, #db2777 100%) !important;
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
/* Reduced Wrapper Margins */
|
||||
#yommi_wrapper {
|
||||
max-width: 100% !important;
|
||||
padding: 10px 8px !important;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
@media (min-width: 1200px) {
|
||||
#yommi_wrapper {
|
||||
max-width: 95% !important;
|
||||
padding: 20px 15px !important;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.row.infinite-scroll > [class*="col-"] {
|
||||
padding: 6px !important;
|
||||
}
|
||||
.card-body {
|
||||
padding: 10px !important;
|
||||
}
|
||||
.card-title {
|
||||
font-size: 0.85rem !important;
|
||||
}
|
||||
.card-actions .btn {
|
||||
font-size: 12px;
|
||||
padding: 6px 10px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<script type="text/javascript">
|
||||
@@ -1231,6 +1323,5 @@ $(document).ready(function(){
|
||||
}, 100);
|
||||
});
|
||||
</script>
|
||||
</style>
|
||||
|
||||
{% endblock %}
|
||||
|
||||
@@ -8,7 +8,12 @@
|
||||
<div class="glass-card p-4">
|
||||
<div class="d-flex justify-content-between align-items-center mb-4">
|
||||
<h2 class="text-white font-weight-bold"><i class="bi bi-gear-fill mr-2"></i>Anilife 설정</h2>
|
||||
{{ macros.m_button_group([['globalSettingSaveBtn', '설정 저장']])}}
|
||||
<div>
|
||||
<button type="button" class="btn btn-outline-info btn-sm mr-2" id="btn-self-update" title="최신 버전으로 업데이트">
|
||||
<i class="bi bi-arrow-repeat"></i> 업데이트
|
||||
</button>
|
||||
{{ macros.m_button_group([['globalSettingSaveBtn', '설정 저장']])}}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{{ macros.m_row_start('5') }}
|
||||
@@ -709,6 +714,37 @@ function getDragAfterElement(container, x) {
|
||||
return [...container.querySelectorAll('.tag-chip:not(.dragging)')].reduce((c, el) => { var box = el.getBoundingClientRect(); var offset = x - box.left - box.width/2; return (offset < 0 && offset > c.offset) ? {offset, element: el} : c; }, {offset: Number.NEGATIVE_INFINITY}).element;
|
||||
}
|
||||
|
||||
// ======================================
|
||||
// 자가 업데이트 기능
|
||||
// ======================================
|
||||
$('#btn-self-update').on('click', function() {
|
||||
if (!confirm('최신 코드를 다운로드하고 플러그인을 리로드하시겠습니까?')) return;
|
||||
|
||||
var btn = $(this);
|
||||
var originalHTML = btn.html();
|
||||
btn.prop('disabled', true).html('<i class="bi bi-arrow-repeat spin"></i> 업데이트 중...');
|
||||
|
||||
$.ajax({
|
||||
url: '/' + package_name + '/ajax/' + sub + '/self_update',
|
||||
type: 'POST',
|
||||
dataType: 'json',
|
||||
success: function(ret) {
|
||||
if (ret.ret === 'success') {
|
||||
$.notify('<strong>업데이트 완료!</strong> 페이지를 새로고침합니다.', {type: 'success'});
|
||||
setTimeout(function() { location.reload(); }, 1500);
|
||||
} else {
|
||||
$.notify('<strong>업데이트 실패: ' + ret.msg + '</strong>', {type: 'danger'});
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
$.notify('<strong>업데이트 중 오류 발생</strong>', {type: 'danger'});
|
||||
},
|
||||
complete: function() {
|
||||
btn.prop('disabled', false).html(originalHTML);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
</script>
|
||||
|
||||
<style>
|
||||
|
||||
@@ -768,6 +768,12 @@ $(document).ready(function(){
|
||||
str += '<button class="action-btn btn-play" data-path="' + item.filepath + '" data-filename="' + item.filename + '"><i class="fa fa-play"></i> 재생</button>';
|
||||
str += '<button class="action-btn btn-merge-sub" data-id="' + item.id + '" data-filename="' + item.filename + '"><i class="fa fa-cc"></i> 자막합침</button>';
|
||||
}
|
||||
|
||||
// [보기] 버튼 추가 - JSON 버튼 왼쪽에 배치
|
||||
if (item.content_code) {
|
||||
str += '<button class="action-btn" onclick="location.href=\'/' + package_name + '/' + sub + '/request?code=' + item.content_code + '\'"><i class="fa fa-eye"></i> 보기</button>';
|
||||
}
|
||||
|
||||
str += '<button class="action-btn" onclick="m_modal(current_data.list[' + i + '])"><i class="fa fa-code"></i> JSON</button>';
|
||||
str += '<button class="action-btn" onclick="search_item(\'' + (item.title || '') + '\')"><i class="fa fa-search"></i> 검색</button>';
|
||||
str += '<button class="action-btn" onclick="db_remove(' + item.id + ')"><i class="fa fa-trash"></i> 삭제</button>';
|
||||
|
||||
@@ -150,6 +150,23 @@ $(document).ready(function(){
|
||||
socket.on('last', function(data){ status_html(data); button_html(data); });
|
||||
}
|
||||
|
||||
// GDM 전용 소켓 추가 핸들링 (전역 업데이트 수신용)
|
||||
var gdmSocket = null;
|
||||
try {
|
||||
gdmSocket = io.connect(socketUrl + '/gommi_downloader_manager');
|
||||
gdmSocket.on('status', function(data) {
|
||||
// 이 모듈과 관련된 작업만 처리
|
||||
if (data.caller_plugin === PACKAGE_NAME + '_' + MODULE_NAME) {
|
||||
// GDM 데이터를 큐 형식으로 변환하여 UI 즉시 업데이트
|
||||
silentFetchList(function(newList) {
|
||||
smartSyncList(newList);
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('GDM socket error:', e);
|
||||
}
|
||||
|
||||
on_start();
|
||||
refreshIntervalId = setInterval(autoRefreshList, 3000);
|
||||
});
|
||||
@@ -170,15 +187,13 @@ function silentFetchList(callback) {
|
||||
|
||||
function autoRefreshList() {
|
||||
silentFetchList(function(data) {
|
||||
if (data.length !== current_list_length) {
|
||||
current_list_length = data.length;
|
||||
renderList(data);
|
||||
}
|
||||
// 무조건 스마트 싱크 호출 (내부에서 변경 사항이 있을 때만 업데이트됨)
|
||||
smartSyncList(data);
|
||||
|
||||
var hasActiveDownload = false;
|
||||
if (data && data.length > 0) {
|
||||
for (var j = 0; j < data.length; j++) {
|
||||
if (data[j].status_str === 'DOWNLOADING' || data[j].status_str === 'WAITING' || data[j].status_str === 'STARTED') {
|
||||
if (data[j].status_str === 'DOWNLOADING' || data[j].status_str === 'WAITING' || data[j].status_str === 'STARTED' || data[j].status_str === 'ANALYZING') {
|
||||
hasActiveDownload = true;
|
||||
break;
|
||||
}
|
||||
@@ -202,6 +217,51 @@ function on_start() {
|
||||
});
|
||||
}
|
||||
|
||||
function smartSyncList(data) {
|
||||
if (!data) return;
|
||||
|
||||
if (data.length == 0) {
|
||||
if (current_list_length !== 0) {
|
||||
current_list_length = 0;
|
||||
renderList(data);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 1. 기존 리스트에 있는 항목들과 비교하여 업데이트 또는 삭제
|
||||
var currentIds = data.map(function(item) { return item.idx; });
|
||||
|
||||
// 현재 DOM에 있는 항목들 중 사라진 항목 제거
|
||||
$('#list tr[id^="tr1_"]').each(function() {
|
||||
var domIdx = $(this).attr('id').replace('tr1_', '');
|
||||
// GDM ID 등 문자열 포함 가능성 고려하여 타입 맞춤
|
||||
if (currentIds.indexOf(domIdx) === -1 && currentIds.indexOf(parseInt(domIdx)) === -1) {
|
||||
$(this).remove();
|
||||
$('#collapse_' + domIdx).remove();
|
||||
}
|
||||
});
|
||||
|
||||
// 2. 새로운 리스트 순회하며 업데이트 또는 추가
|
||||
for (var i = 0; i < data.length; i++) {
|
||||
var item = data[i];
|
||||
var row = $('#tr1_' + item.idx);
|
||||
|
||||
if (row.length > 0) {
|
||||
// 이미 존재하는 경우: 상태 및 데이터만 업데이트 (깜빡임 방지)
|
||||
status_html(item);
|
||||
button_html(item);
|
||||
|
||||
// 파일명이나 다른 필드도 변할 수 있으므로 필요한 경우 갱신
|
||||
// (여기서는 진행률과 상태가 핵심이므로 status_html에서 처리됨)
|
||||
} else {
|
||||
// 새로 추가된 경우: 리스트의 올바른 위치에 삽입 (간단히 append)
|
||||
$("#list").append(make_item(item));
|
||||
}
|
||||
}
|
||||
|
||||
current_list_length = data.length;
|
||||
}
|
||||
|
||||
function renderList(data) {
|
||||
$("#list").html('');
|
||||
if (!data || data.length == 0) {
|
||||
@@ -274,8 +334,8 @@ function make_item1(data) {
|
||||
|
||||
str += '<td id="status_'+data.idx+'" style="text-align:center;"><span class="badge-status ' + status_class + '">'+ data.status_kor + '</span></td>';
|
||||
|
||||
var visi = (parseInt(data.percent) > 0) ? 'visible' : 'hidden';
|
||||
str += '<td><div class="progress custom-progress"><div id="progress_'+data.idx+'" class="progress-bar" style="visibility: '+visi+'; width:'+data.percent+'%">'+data.percent +'%</div></div></td>';
|
||||
// 진행률 표시: 0%이더라도 다운로드 중이면 바를 표시 (깜빡임 서프레스)
|
||||
str += '<td><div class="progress custom-progress"><div id="progress_'+data.idx+'" class="progress-bar" style="width:'+data.percent+'%">'+data.percent +'%</div></div></td>';
|
||||
|
||||
str += '<td style="text-align:center;">'+ data.duration_str + '</td>';
|
||||
str += '<td id="current_pf_count_'+data.idx+'" style="text-align:center; color: #f87171;">'+ data.current_pf_count + '</td>';
|
||||
@@ -334,7 +394,6 @@ function status_html(data) {
|
||||
|
||||
progress.style.width = data.percent+ '%';
|
||||
progress.innerHTML = data.percent+ '%';
|
||||
progress.style.visibility = 'visible';
|
||||
|
||||
var statusEl = document.getElementById("status_" + data.idx);
|
||||
if (statusEl) {
|
||||
|
||||
@@ -49,7 +49,7 @@
|
||||
const package_name = "{{arg['package_name'] }}";
|
||||
const sub = "{{arg['sub'] }}";
|
||||
const ohli24_url = "{{arg['ohli24_url']}}";
|
||||
// let current_data = '';
|
||||
var current_data = null;
|
||||
|
||||
const params = new Proxy(new URLSearchParams(window.location.search), {
|
||||
get: (searchParams, prop) => searchParams.get(prop),
|
||||
@@ -195,45 +195,21 @@
|
||||
}
|
||||
|
||||
$(function () {
|
||||
// console.log(params.wr_id)
|
||||
// console.log(findGetParameter('wr_id'))
|
||||
// console.log(params.code)
|
||||
if (params.code === '') {
|
||||
|
||||
} else {
|
||||
document.getElementById("code").value = params.code
|
||||
// {#document.getElementById("analysis_btn").click();#}
|
||||
// URL 파라미터 처리 (code)
|
||||
const urlCode = params.code || findGetParameter('code');
|
||||
const currentCode = "{{arg['linkkf_current_code']}}";
|
||||
|
||||
const targetCode = urlCode || currentCode;
|
||||
|
||||
if (targetCode) {
|
||||
document.getElementById("code").value = targetCode;
|
||||
// wr_id, bo_table 등이 있으면 같이 전달
|
||||
analyze(params.wr_id || findGetParameter('wr_id'), params.bo_table || findGetParameter('bo_table'));
|
||||
}
|
||||
|
||||
if ("{{arg['linkkf_current_code']}}" !== "") {
|
||||
if (params.code === null) {
|
||||
// console.log('params.code === null')
|
||||
document.getElementById("code").value = "{{arg['linkkf_current_code']}}";
|
||||
|
||||
} else if (params.code === '') {
|
||||
document.getElementById("code").value = "{{arg['linkkf_current_code']}}";
|
||||
} else {
|
||||
|
||||
// console.log('params code exist')
|
||||
// console.log(params.code)
|
||||
document.getElementById("code").value = params.code
|
||||
|
||||
analyze(params.wr_id, params.bo_table)
|
||||
// document.getElementById("analysis_btn").click();
|
||||
// $('#analysis_btn').trigger('click')
|
||||
}
|
||||
// 값이 공백이 아니면 분석 버튼 계속 누름
|
||||
// {#document.getElementById("analysis_btn").click();#}
|
||||
} else {
|
||||
|
||||
}
|
||||
|
||||
})
|
||||
});
|
||||
|
||||
$(document).ready(function () {
|
||||
|
||||
// console.log('wr_id::', params.wr_id)
|
||||
|
||||
});
|
||||
|
||||
// Enter 키로 검색 트리거
|
||||
@@ -312,26 +288,29 @@
|
||||
|
||||
$("body").on('click', '#add_queue_btn', function (e) {
|
||||
e.preventDefault();
|
||||
data = current_data.episode[$(this).data('idx')];
|
||||
// console.log('data:::>', data)
|
||||
let episode_data = current_data.episode[$(this).data('idx')];
|
||||
// console.log('episode_data:::>', episode_data)
|
||||
$.ajax({
|
||||
url: '/' + package_name + '/ajax/' + sub + '/add_queue',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: {data: JSON.stringify(data)},
|
||||
data: {data: JSON.stringify(episode_data)},
|
||||
dataType: "json",
|
||||
success: function (data) {
|
||||
// console.log('#add_queue_btn::data >>', data)
|
||||
if (data.ret == 'enqueue_db_append' || data.ret == 'enqueue_db_exist') {
|
||||
success: function (ret) {
|
||||
// console.log('#add_queue_btn::ret >>', ret)
|
||||
if (ret.ret == 'enqueue_db_append' || ret.ret == 'enqueue_db_exist' || ret.ret == 'enqueue_gdm_success') {
|
||||
$.notify('<strong>다운로드 작업을 추가 하였습니다.</strong>', {type: 'success'});
|
||||
} else if (data.ret == 'queue_exist') {
|
||||
} else if (ret.ret == 'queue_exist') {
|
||||
$.notify('<strong>이미 큐에 있습니다. 삭제 후 추가하세요.</strong>', {type: 'warning'});
|
||||
} else if (data.ret == 'db_completed') {
|
||||
} else if (ret.ret == 'db_completed') {
|
||||
$.notify('<strong>DB에 완료 기록이 있습니다.</strong>', {type: 'warning'});
|
||||
} else if (data.ret == 'file_exists') {
|
||||
} else if (ret.ret == 'file_exists') {
|
||||
$.notify('<strong>파일이 이미 존재합니다.</strong>', {type: 'warning'});
|
||||
} else if (ret.ret == 'extract_failed') {
|
||||
$.notify('<strong>추가 실패: 영상 주소 추출에 실패하였습니다.</strong>', {type: 'warning'});
|
||||
} else {
|
||||
$.notify('<strong>추가 실패</strong><br>' + ret.log, {type: 'warning'});
|
||||
const msg = ret.log || '알 수 없는 이유로 추가에 실패하였습니다.';
|
||||
$.notify('<strong>추가 실패</strong><br>' + msg, {type: 'warning'});
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -340,16 +319,14 @@
|
||||
|
||||
$("body").on('click', '#check_download_btn', function (e) {
|
||||
e.preventDefault();
|
||||
all = $('input[id^="checkbox_"]');
|
||||
let data = [];
|
||||
let idx;
|
||||
for (let i in all) {
|
||||
if (all[i].checked) {
|
||||
idx = parseInt(all[i].id.split('_')[1])
|
||||
data.push(current_data.episode[idx]);
|
||||
let selected_data = [];
|
||||
$('input[id^="checkbox_"]').each(function() {
|
||||
if ($(this).prop('checked')) {
|
||||
let idx = parseInt($(this).attr('id').split('_')[1]);
|
||||
selected_data.push(current_data.episode[idx]);
|
||||
}
|
||||
}
|
||||
if (data.length == 0) {
|
||||
});
|
||||
if (selected_data.length == 0) {
|
||||
$.notify('<strong>선택하세요.</strong>', {type: 'warning'});
|
||||
return;
|
||||
}
|
||||
@@ -357,13 +334,43 @@
|
||||
url: '/' + package_name + '/ajax/' + sub + '/add_queue_checked_list',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: {data: JSON.stringify(data)},
|
||||
data: {data: JSON.stringify(selected_data)},
|
||||
dataType: "json",
|
||||
success: function (data) {
|
||||
success: function (ret) {
|
||||
$.notify('<strong>백그라운드로 작업을 추가합니다.</strong>', {type: 'success'});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
$("body").on('click', '#down_subtitle_btn', function (e) {
|
||||
e.preventDefault();
|
||||
let selected_data = [];
|
||||
$('input[id^="checkbox_"]').each(function() {
|
||||
if ($(this).prop('checked')) {
|
||||
let idx = parseInt($(this).attr('id').split('_')[1]);
|
||||
selected_data.push(current_data.episode[idx]);
|
||||
}
|
||||
});
|
||||
if (selected_data.length == 0) {
|
||||
$.notify('<strong>선택하세요.</strong>', {type: 'warning'});
|
||||
return;
|
||||
}
|
||||
$.ajax({
|
||||
url: '/' + package_name + '/ajax/' + sub + '/add_sub_queue_checked_list',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: {data: JSON.stringify(selected_data)},
|
||||
dataType: "json",
|
||||
success: function (ret) {
|
||||
if (ret.ret == "success") {
|
||||
$.notify('<strong>백그라운드로 자막 다운로드를 시작합니다.</strong>', {type: 'success'});
|
||||
} else {
|
||||
const msg = ret.log || '알 수 없는 이유로 요청에 실패하였습니다.';
|
||||
$.notify('<strong>자막 다운로드 요청 실패: ' + msg + '</strong>', {type: 'warning'});
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
<style>
|
||||
#anime_downloader_wrapper {
|
||||
|
||||
@@ -8,7 +8,12 @@
|
||||
<div class="glass-card p-4">
|
||||
<div class="d-flex justify-content-between align-items-center mb-4">
|
||||
<h2 class="text-white font-weight-bold"><i class="bi bi-gear-fill mr-2"></i>Linkkf 설정</h2>
|
||||
{{ macros.m_button_group([['globalSettingSaveBtn', '설정 저장']])}}
|
||||
<div>
|
||||
<button type="button" class="btn btn-outline-info btn-sm mr-2" id="btn-self-update" title="최신 버전으로 업데이트">
|
||||
<i class="bi bi-arrow-repeat"></i> 업데이트
|
||||
</button>
|
||||
{{ macros.m_button_group([['globalSettingSaveBtn', '설정 저장']])}}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{{ macros.m_row_start('5') }}
|
||||
@@ -77,6 +82,93 @@
|
||||
</div>
|
||||
</div>
|
||||
{{ macros.setting_checkbox('linkkf_auto_mode_all', '에피소드 모두 받기', value=arg['linkkf_auto_mode_all'], desc=['On : 이전 에피소드를 모두 받습니다.', 'Off : 최신 에피소드만 받습니다.']) }}
|
||||
{{ macros.setting_checkbox('linkkf_auto_download_new', '새 에피소드 자동 다운로드', value=arg['linkkf_auto_download_new'], desc=['On : 새 에피소드 감지 시 자동으로 큐에 추가합니다.', 'Off : 알림만 보내고 다운로드는 수동으로 합니다.']) }}
|
||||
|
||||
<div class="row" style="padding-top: 10px; padding-bottom:10px;">
|
||||
<div class="col-sm-3 set-left"><strong>모니터링 주기</strong></div>
|
||||
<div class="col-sm-9">
|
||||
<select class="form-control form-control-sm col-sm-3" id="linkkf_monitor_interval" name="linkkf_monitor_interval">
|
||||
<option value="5" {% if arg.get('linkkf_monitor_interval', '10') == '5' %}selected{% endif %}>5분</option>
|
||||
<option value="10" {% if arg.get('linkkf_monitor_interval', '10') == '10' or not arg.get('linkkf_monitor_interval') %}selected{% endif %}>10분 (기본)</option>
|
||||
<option value="15" {% if arg.get('linkkf_monitor_interval', '10') == '15' %}selected{% endif %}>15분</option>
|
||||
<option value="30" {% if arg.get('linkkf_monitor_interval', '10') == '30' %}selected{% endif %}>30분</option>
|
||||
<option value="60" {% if arg.get('linkkf_monitor_interval', '10') == '60' %}selected{% endif %}>1시간</option>
|
||||
</select>
|
||||
<div style="padding-top:5px;"><em class="text-muted">'all' 모드 사용 시 사이트를 확인하는 주기입니다.</em></div>
|
||||
</div>
|
||||
</div>
|
||||
{{ macros.m_tab_content_end() }}
|
||||
|
||||
{{ macros.m_tab_content_start('action', false) }}
|
||||
<div class="row mb-3">
|
||||
<div class="col-sm-12">
|
||||
<h5 class="text-white mb-3"><i class="bi bi-lightning-fill mr-2"></i>수동 작업</h5>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row mb-4">
|
||||
<div class="col-sm-3 set-left"><strong>스케줄러 1회 실행</strong></div>
|
||||
<div class="col-sm-9">
|
||||
<button type="button" class="btn btn-outline-success btn-sm" id="global_one_execute_btn">
|
||||
<i class="bi bi-play-circle mr-1"></i> 1회 실행
|
||||
</button>
|
||||
<div style="padding-top:5px;"><em class="text-muted">자동 다운로드 스케줄러를 즉시 1회 실행합니다.</em></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row mb-4">
|
||||
<div class="col-sm-3 set-left"><strong>DB 초기화</strong></div>
|
||||
<div class="col-sm-9">
|
||||
<button type="button" class="btn btn-outline-danger btn-sm" id="global_reset_db_btn">
|
||||
<i class="bi bi-trash mr-1"></i> DB 초기화
|
||||
</button>
|
||||
<div style="padding-top:5px;"><em class="text-muted">다운로드 기록 DB를 초기화합니다.</em></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<hr style="border-color: rgba(255,255,255,0.1); margin: 30px 0;">
|
||||
|
||||
<div class="row mb-3">
|
||||
<div class="col-sm-12">
|
||||
<h5 class="text-white mb-3"><i class="bi bi-bell-fill mr-2"></i>알림 설정</h5>
|
||||
</div>
|
||||
</div>
|
||||
{{ macros.setting_checkbox('linkkf_notify_enabled', '알림 활성화', value=arg['linkkf_notify_enabled'], desc='새 에피소드가 큐에 추가되면 알림을 보냅니다.') }}
|
||||
|
||||
<div class="row mb-3">
|
||||
<div class="col-sm-12">
|
||||
<h6 class="text-info mb-2"><i class="bi bi-discord mr-1"></i> Discord</h6>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row" style="padding-top: 10px; padding-bottom:10px;">
|
||||
<div class="col-sm-3 set-left"><strong>Discord Webhook URL</strong></div>
|
||||
<div class="col-sm-9">
|
||||
<div class="input-group">
|
||||
<input type="text" class="form-control form-control-sm" id="linkkf_discord_webhook_url" name="linkkf_discord_webhook_url" value="{{arg['linkkf_discord_webhook_url']}}">
|
||||
<div class="input-group-append">
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary" id="copy_discord_url_btn" title="URL 복사">
|
||||
<i class="bi bi-clipboard"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div style="padding-top:5px;"><em class="text-muted">Discord 서버 설정 → 연동 → 웹훅에서 URL을 복사하세요.</em></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row mb-3 mt-4">
|
||||
<div class="col-sm-12">
|
||||
<h6 class="text-info mb-2"><i class="bi bi-telegram mr-1"></i> Telegram</h6>
|
||||
</div>
|
||||
</div>
|
||||
{{ macros.setting_input_text('linkkf_telegram_bot_token', 'Telegram Bot Token', col='9', value=arg['linkkf_telegram_bot_token'], desc='@BotFather에서 생성한 봇 토큰입니다.') }}
|
||||
{{ macros.setting_input_text('linkkf_telegram_chat_id', 'Telegram Chat ID', col='4', value=arg['linkkf_telegram_chat_id'], desc='알림을 받을 채팅방 ID (개인: 숫자, 그룹: -숫자)') }}
|
||||
|
||||
<div class="row mb-3 mt-3">
|
||||
<div class="col-sm-3"></div>
|
||||
<div class="col-sm-9">
|
||||
<button type="button" class="btn btn-outline-info btn-sm" id="test_notify_btn">
|
||||
<i class="bi bi-send mr-1"></i> 테스트 알림 전송
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{{ macros.m_tab_content_end() }}
|
||||
|
||||
</div><!--tab-content-->
|
||||
@@ -366,6 +458,94 @@ $("body").on('click', '#go_btn', function(e){
|
||||
window.open(url, "_blank");
|
||||
});
|
||||
|
||||
// 1회 실행 버튼
|
||||
$(document).on('click', '#global_one_execute_btn', function(e){
|
||||
e.preventDefault();
|
||||
$.ajax({
|
||||
url: '/'+package_name+'/ajax/'+sub+'/immediately_execute',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
dataType: "json",
|
||||
success: function(ret) {
|
||||
if (ret.ret == 'success') {
|
||||
$.notify('스케줄러 1회 실행을 시작합니다.', {type:'success'});
|
||||
} else {
|
||||
$.notify(ret.msg || '실행 실패', {type:'danger'});
|
||||
}
|
||||
},
|
||||
error: function(xhr, status, error) {
|
||||
$.notify('에러: ' + error, {type:'danger'});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// DB 초기화 버튼
|
||||
$(document).on('click', '#global_reset_db_btn', function(e){
|
||||
e.preventDefault();
|
||||
if (!confirm('정말 DB를 초기화하시겠습니까?')) return;
|
||||
$.ajax({
|
||||
url: '/'+package_name+'/ajax/'+sub+'/reset_db',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
dataType: "json",
|
||||
success: function(ret) {
|
||||
if (ret.ret == 'success') {
|
||||
$.notify('DB가 초기화되었습니다.', {type:'success'});
|
||||
} else {
|
||||
$.notify(ret.msg || '초기화 실패', {type:'danger'});
|
||||
}
|
||||
},
|
||||
error: function(xhr, status, error) {
|
||||
$.notify('에러: ' + error, {type:'danger'});
|
||||
}
|
||||
});
|
||||
});
|
||||
// Discord Webhook URL 복사 버튼
|
||||
$(document).on('click', '#copy_discord_url_btn', function(e){
|
||||
e.preventDefault();
|
||||
var url = $('#linkkf_discord_webhook_url').val();
|
||||
if (!url) {
|
||||
$.notify('복사할 URL이 없습니다.', {type:'warning'});
|
||||
return;
|
||||
}
|
||||
navigator.clipboard.writeText(url).then(function() {
|
||||
$.notify('URL이 클립보드에 복사되었습니다.', {type:'success'});
|
||||
}).catch(function() {
|
||||
// Fallback for older browsers
|
||||
var temp = $('<input>').val(url).appendTo('body').select();
|
||||
document.execCommand('copy');
|
||||
temp.remove();
|
||||
$.notify('URL이 클립보드에 복사되었습니다.', {type:'success'});
|
||||
});
|
||||
});
|
||||
|
||||
// 테스트 알림 버튼
|
||||
$(document).on('click', '#test_notify_btn', function(e){
|
||||
e.preventDefault();
|
||||
var btn = $(this);
|
||||
btn.prop('disabled', true).html('<i class="bi bi-arrow-repeat spin mr-1"></i> 전송 중...');
|
||||
|
||||
$.ajax({
|
||||
url: '/'+package_name+'/ajax/'+sub+'/test_notification',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
dataType: "json",
|
||||
success: function(ret) {
|
||||
if (ret.ret == 'success') {
|
||||
$.notify('테스트 알림을 전송했습니다!', {type:'success'});
|
||||
} else {
|
||||
$.notify(ret.msg || '알림 전송 실패', {type:'danger'});
|
||||
}
|
||||
},
|
||||
error: function(xhr, status, error) {
|
||||
$.notify('에러: ' + error, {type:'danger'});
|
||||
},
|
||||
complete: function() {
|
||||
btn.prop('disabled', false).html('<i class="bi bi-send mr-1"></i> 테스트 알림 전송');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ======================================
|
||||
// 폴더 탐색 기능
|
||||
// ======================================
|
||||
@@ -553,5 +733,105 @@ $('#tag_chips_container').on('dragover', function(e) { e.preventDefault(); var a
|
||||
function getDragAfterElement(container, x) {
|
||||
return [...container.querySelectorAll('.tag-chip:not(.dragging)')].reduce((c, el) => { var box = el.getBoundingClientRect(); var offset = x - box.left - box.width/2; return (offset < 0 && offset > c.offset) ? {offset, element: el} : c; }, {offset: Number.NEGATIVE_INFINITY}).element;
|
||||
}
|
||||
|
||||
// ======================================
|
||||
// 자가 업데이트 기능
|
||||
// ======================================
|
||||
$(document).on('click', '#btn-self-update', function() {
|
||||
$('#updateConfirmModal').modal('show');
|
||||
});
|
||||
|
||||
// 실제 업데이트 실행 (모달에서 확인 버튼 클릭 시)
|
||||
$(document).on('click', '#confirmUpdateBtn', function() {
|
||||
$('#updateConfirmModal').modal('hide');
|
||||
|
||||
var btn = $('#btn-self-update');
|
||||
var originalHTML = btn.html();
|
||||
btn.prop('disabled', true).html('<i class="bi bi-arrow-repeat spin"></i> 업데이트 중...');
|
||||
|
||||
$.ajax({
|
||||
url: '/' + package_name + '/ajax/' + sub + '/self_update',
|
||||
type: 'POST',
|
||||
dataType: 'json',
|
||||
success: function(ret) {
|
||||
if (ret.ret === 'success') {
|
||||
$.notify('<strong>업데이트 완료!</strong> 페이지를 새로고침합니다.', {type: 'success'});
|
||||
setTimeout(function() { location.reload(); }, 1500);
|
||||
} else {
|
||||
$.notify('<strong>업데이트 실패: ' + ret.msg + '</strong>', {type: 'danger'});
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
$.notify('<strong>업데이트 중 오류 발생</strong>', {type: 'danger'});
|
||||
},
|
||||
complete: function() {
|
||||
btn.prop('disabled', false).html(originalHTML);
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<!-- Update Confirmation Modal (Linkkf Green Theme) -->
|
||||
<div class="modal fade" id="updateConfirmModal" tabindex="-1" role="dialog" aria-hidden="true">
|
||||
<div class="modal-dialog modal-dialog-centered" role="document">
|
||||
<div class="modal-content animate__animated animate__zoomIn" style="background: linear-gradient(145deg, #1e293b 0%, #0f172a 100%); border: 1px solid rgba(16, 185, 129, 0.3); border-radius: 20px; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);">
|
||||
<div class="modal-body text-center" style="padding: 40px 30px;">
|
||||
<div style="width: 80px; height: 80px; background: linear-gradient(135deg, rgba(16, 185, 129, 0.2) 0%, rgba(5, 150, 105, 0.2) 100%); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 24px; border: 2px solid rgba(16, 185, 129, 0.3);">
|
||||
<i class="bi bi-arrow-repeat" style="color: #10b981; font-size: 36px;"></i>
|
||||
</div>
|
||||
<h4 style="color: #f1f5f9; font-weight: 700; margin-bottom: 12px;">플러그인 업데이트</h4>
|
||||
<p style="color: #94a3b8; font-size: 15px; margin-bottom: 8px;">최신 코드를 다운로드하고 플러그인을 리로드합니다.</p>
|
||||
<p style="color: #64748b; font-size: 13px; margin-bottom: 32px;"><i class="bi bi-info-circle"></i> 서버 재시작 없이 즉시 적용됩니다.</p>
|
||||
<div style="display: flex; gap: 12px; justify-content: center;">
|
||||
<button type="button" class="btn" data-dismiss="modal" style="width: 120px; background: rgba(255,255,255,0.1); border: 1px solid rgba(255,255,255,0.2); color: #94a3b8; border-radius: 10px; padding: 12px 24px; font-weight: 600;">취소</button>
|
||||
<button type="button" id="confirmUpdateBtn" class="btn" style="width: 140px; background: linear-gradient(135deg, #10b981 0%, #059669 100%); border: none; color: white; border-radius: 10px; padding: 12px 24px; font-weight: 600; box-shadow: 0 4px 15px rgba(16, 185, 129, 0.4);">
|
||||
<i class="bi bi-download"></i> 업데이트
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
/* Update Button Enhanced Visibility (Linkkf Green) */
|
||||
#btn-self-update {
|
||||
background: linear-gradient(135deg, #10b981 0%, #059669 100%) !important;
|
||||
border: none !important;
|
||||
color: white !important;
|
||||
font-weight: 600;
|
||||
padding: 8px 16px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3);
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
#btn-self-update:hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, #059669 0%, #047857 100%) !important;
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
|
||||
}
|
||||
#btn-self-update:disabled {
|
||||
background: linear-gradient(135deg, #475569 0%, #334155 100%) !important;
|
||||
color: #94a3b8 !important;
|
||||
cursor: not-allowed;
|
||||
box-shadow: none;
|
||||
opacity: 0.7;
|
||||
}
|
||||
#btn-self-update .bi-arrow-repeat.spin,
|
||||
.spin {
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
@keyframes spin {
|
||||
from { transform: rotate(0deg); }
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
/* Animate.css for modal */
|
||||
.animate__animated { animation-duration: 0.3s; }
|
||||
.animate__zoomIn { animation-name: zoomIn; }
|
||||
@keyframes zoomIn {
|
||||
from { opacity: 0; transform: scale3d(0.3, 0.3, 0.3); }
|
||||
50% { opacity: 1; }
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
@@ -1,193 +1,159 @@
|
||||
{% extends "base.html" %}
|
||||
{% block content %}
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
|
||||
<link rel="stylesheet" href="{{ url_for('.static', filename='css/mobile_custom.css') }}"/>
|
||||
|
||||
<style>
|
||||
/* Premium Dark Theme Variables */
|
||||
:root {
|
||||
--bg-color: #0f172a; /* Slate 900 */
|
||||
--card-bg: #1e293b; /* Slate 800 */
|
||||
--text-color: #f8fafc; /* Slate 50 */
|
||||
--text-muted: #94a3b8; /* Slate 400 */
|
||||
--accent-color: #3b82f6; /* Blue 500 */
|
||||
--accent-hover: #2563eb; /* Blue 600 */
|
||||
--terminal-bg: #000000;
|
||||
--terminal-text: #4ade80; /* Green 400 */
|
||||
--border-color: #334155; /* Slate 700 */
|
||||
}
|
||||
|
||||
/* Global Override */
|
||||
/* Match gds_dviewer Log Page Design */
|
||||
body {
|
||||
background-color: var(--bg-color) !important;
|
||||
background-image: radial-gradient(circle at top right, #1e293b 0%, transparent 60%), radial-gradient(circle at bottom left, #1e293b 0%, transparent 60%);
|
||||
color: var(--text-color);
|
||||
font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
/* overflow: hidden 제거 - 모바일 스크롤 허용 */
|
||||
background: linear-gradient(145deg, #0f172a, #1e293b) !important;
|
||||
color: #f8fafc;
|
||||
font-family: 'Inter', -apple-system, sans-serif;
|
||||
}
|
||||
|
||||
/* Container & Typography */
|
||||
.container-fluid {
|
||||
padding: 8px; /* 최소 여백 */
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
body {
|
||||
overflow-x: hidden !important;
|
||||
overflow-y: auto !important; /* 세로 스크롤 허용 */
|
||||
}
|
||||
.container-fluid {
|
||||
padding: 4px; /* 모바일 더 작은 여백 */
|
||||
}
|
||||
.tab-pane {
|
||||
padding: 8px;
|
||||
}
|
||||
.dashboard-card {
|
||||
margin-top: 8px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
/* 로그 테이블 뷰포트 기반 높이 */
|
||||
textarea#log, textarea#add {
|
||||
max-height: 60vh !important;
|
||||
height: auto !important;
|
||||
min-height: 300px !important;
|
||||
}
|
||||
}
|
||||
|
||||
h1, h2, h3, h4, h5, h6 {
|
||||
color: var(--text-color);
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.025em;
|
||||
}
|
||||
|
||||
/* Main Card */
|
||||
.dashboard-card {
|
||||
background-color: var(--card-bg);
|
||||
border: 1px solid var(--border-color);
|
||||
.log-card {
|
||||
background: linear-gradient(145deg, rgba(20, 30, 48, 0.95), rgba(36, 59, 85, 0.9));
|
||||
border: 1px solid rgba(100, 150, 180, 0.25);
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
|
||||
overflow: hidden;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.log-card-header {
|
||||
background: transparent;
|
||||
border-bottom: 1px solid rgba(100, 150, 180, 0.2);
|
||||
padding: 16px 20px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.log-card-header h5 {
|
||||
margin: 0;
|
||||
color: #e2e8f0;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.log-card-header h5 i {
|
||||
color: #7dd3fc;
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
.btn-log {
|
||||
background: linear-gradient(180deg, rgba(45, 55, 72, 0.95), rgba(35, 45, 60, 0.98));
|
||||
border: 1px solid rgba(100, 150, 180, 0.25);
|
||||
color: #7dd3fc;
|
||||
padding: 6px 14px;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
border-radius: 6px;
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
.btn-log:hover {
|
||||
background: linear-gradient(180deg, rgba(55, 65, 82, 0.95), rgba(45, 55, 70, 0.98));
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.btn-log.danger {
|
||||
background: rgba(239, 68, 68, 0.15);
|
||||
border: 1px solid rgba(239, 68, 68, 0.4);
|
||||
color: #fca5a5;
|
||||
}
|
||||
|
||||
.btn-log.danger:hover {
|
||||
background: rgba(239, 68, 68, 0.3);
|
||||
}
|
||||
|
||||
.log-container {
|
||||
height: calc(100vh - 200px);
|
||||
min-height: 400px;
|
||||
overflow-y: auto;
|
||||
padding: 16px;
|
||||
font-family: 'SF Mono', 'Consolas', 'Monaco', monospace;
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.log-line-error { color: #f87171; }
|
||||
.log-line-warning { color: #fbbf24; }
|
||||
.log-line-info { color: #5eead4; }
|
||||
.log-line-debug { color: #94a3b8; }
|
||||
|
||||
/* Tabs Styling */
|
||||
.nav-tabs {
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
background-color: rgba(0,0,0,0.2);
|
||||
border-bottom: 1px solid rgba(100, 150, 180, 0.2);
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
padding: 10px 10px 0 10px;
|
||||
}
|
||||
|
||||
.nav-tabs .nav-link {
|
||||
color: var(--text-muted) !important;
|
||||
color: #94a3b8 !important;
|
||||
border: none !important;
|
||||
border-radius: 8px 8px 0 0 !important;
|
||||
padding: 10px 20px;
|
||||
font-weight: 500;
|
||||
transition: all 0.2s ease;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.nav-tabs .nav-link:hover {
|
||||
color: var(--text-color) !important;
|
||||
background-color: rgba(255,255,255,0.05);
|
||||
color: #e2e8f0 !important;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
.nav-tabs .nav-link.active {
|
||||
color: var(--accent-color) !important;
|
||||
background-color: var(--card-bg) !important;
|
||||
border-bottom: 2px solid var(--accent-color) !important;
|
||||
color: #7dd3fc !important;
|
||||
background: rgba(20, 30, 48, 0.95) !important;
|
||||
border-bottom: 2px solid #7dd3fc !important;
|
||||
}
|
||||
|
||||
/* Content Area */
|
||||
.tab-content {
|
||||
padding: 0; /* Removing default padding to let terminal fill */
|
||||
}
|
||||
|
||||
.tab-pane {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
/* Terminal Styling */
|
||||
textarea#log, textarea#add {
|
||||
background-color: var(--terminal-bg) !important;
|
||||
color: var(--terminal-text) !important;
|
||||
border: 1px solid #333;
|
||||
border-radius: 6px;
|
||||
font-family: 'JetBrains Mono', 'Fira Code', 'Consolas', monospace;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
padding: 16px;
|
||||
width: 100%;
|
||||
box-shadow: inset 0 2px 4px 0 rgba(0, 0, 0, 0.5);
|
||||
resize: none; /* Disable manual resize */
|
||||
overscroll-behavior: contain; /* 스크롤 체인 방지 */
|
||||
transform: translateZ(0); /* GPU 가속화 */
|
||||
will-change: scroll-position;
|
||||
}
|
||||
|
||||
textarea#log:focus, textarea#add:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent-color);
|
||||
box-shadow: 0 0 0 1px var(--accent-color);
|
||||
}
|
||||
|
||||
/* Controls Bar */
|
||||
.controls-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
padding: 12px 20px;
|
||||
background-color: rgba(0,0,0,0.2);
|
||||
border-top: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
/* Toggle Switch */
|
||||
.form-check-input {
|
||||
background-color: #334155;
|
||||
border-color: #475569;
|
||||
cursor: pointer;
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
border-top: 1px solid rgba(100, 150, 180, 0.2);
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.form-check-input:checked {
|
||||
background-color: var(--accent-color);
|
||||
border-color: var(--accent-color);
|
||||
background-color: #7dd3fc;
|
||||
border-color: #7dd3fc;
|
||||
}
|
||||
|
||||
.form-check-label {
|
||||
color: var(--text-muted);
|
||||
color: #94a3b8;
|
||||
font-weight: 500;
|
||||
margin-right: 12px;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
/* Buttons */
|
||||
.btn-action {
|
||||
background-color: transparent;
|
||||
border: 1px solid var(--border-color);
|
||||
color: var(--text-color);
|
||||
border-radius: 6px;
|
||||
padding: 6px 16px;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
transition: all 0.2s;
|
||||
margin-left: 12px;
|
||||
@media (max-width: 768px) {
|
||||
.log-container {
|
||||
height: calc(100vh - 180px);
|
||||
min-height: 300px;
|
||||
padding: 12px;
|
||||
}
|
||||
.log-card-header {
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
align-items: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
.btn-action:hover {
|
||||
background-color: var(--accent-color);
|
||||
border-color: var(--accent-color);
|
||||
color: white;
|
||||
/* Smooth Load */
|
||||
.content-cloak {
|
||||
opacity: 0;
|
||||
transition: opacity 0.5s ease-out;
|
||||
}
|
||||
.content-cloak.visible {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
</style>
|
||||
|
||||
<div class="container-fluid content-cloak" id="main_container">
|
||||
<!-- Header -->
|
||||
<div class="d-flex justify-content-between align-items-center mb-4">
|
||||
<div>
|
||||
<h2 class="mb-1">System Logs</h2>
|
||||
<p class="text-muted mb-0" style="color: var(--text-muted);">Real-time application logs and history.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="dashboard-card">
|
||||
<div class="container-fluid content-cloak" id="main_container" style="max-width: 1400px;">
|
||||
<div class="log-card">
|
||||
<nav>
|
||||
{{ macros.m_tab_head_start() }}
|
||||
{{ macros.m_tab_head('old', 'History', true) }}
|
||||
@@ -196,27 +162,20 @@
|
||||
</nav>
|
||||
|
||||
<div class="tab-content" id="nav-tabContent">
|
||||
<!-- Old Logs -->
|
||||
<!-- History Logs -->
|
||||
{{ macros.m_tab_content_start('old', true) }}
|
||||
<div>
|
||||
<textarea id="log" rows="30" disabled spellcheck="false"></textarea>
|
||||
</div>
|
||||
<div class="log-container" id="log-history"></div>
|
||||
{{ macros.m_tab_content_end() }}
|
||||
|
||||
<!-- New Logs -->
|
||||
<!-- Real-time Logs -->
|
||||
{{ macros.m_tab_content_start('new', false) }}
|
||||
<div>
|
||||
<textarea id="add" rows="30" disabled spellcheck="false"></textarea>
|
||||
</div>
|
||||
|
||||
<div class="log-container" id="log-realtime"></div>
|
||||
<div class="controls-bar">
|
||||
<div class="d-flex align-items-center">
|
||||
<label class="form-check-label" for="auto_scroll">Auto Scroll</label>
|
||||
<div class="form-check form-switch mb-0">
|
||||
<input id="auto_scroll" name="auto_scroll" class="form-check-input" type="checkbox" checked>
|
||||
</div>
|
||||
<button id="clear" class="btn btn-action">Clear Console</button>
|
||||
<label class="form-check-label" for="auto_scroll">Auto Scroll</label>
|
||||
<div class="form-check form-switch mb-0">
|
||||
<input id="auto_scroll" name="auto_scroll" class="form-check-input" type="checkbox" checked>
|
||||
</div>
|
||||
<button id="clear" class="btn-log">Clear</button>
|
||||
</div>
|
||||
{{ macros.m_tab_content_end() }}
|
||||
</div>
|
||||
@@ -224,90 +183,58 @@
|
||||
</div>
|
||||
|
||||
<script type="text/javascript">
|
||||
$(document).ready(function() {
|
||||
// Force fluid layout
|
||||
$("#main_container").removeClass("container").addClass("container-fluid");
|
||||
|
||||
$('#loading').show();
|
||||
ResizeTextAreaLog()
|
||||
})
|
||||
|
||||
function ResizeTextAreaLog() {
|
||||
// Dynamic height calculation
|
||||
ClientHeight = window.innerHeight;
|
||||
// Adjust calculation based on new layout (header + padding + tabs + toolbars)
|
||||
// Approx header: 80, padding: 80, tabs: 50, footer: 60 => ~270
|
||||
var offset = 340;
|
||||
var newHeight = ClientHeight - offset;
|
||||
if (newHeight < 400) newHeight = 400; // Min height
|
||||
|
||||
$("#log").height(newHeight);
|
||||
$("#add").height(newHeight);
|
||||
function escapeHtml(text) {
|
||||
const div = document.createElement('div');
|
||||
div.appendChild(document.createTextNode(text));
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
$(window).resize(function() {
|
||||
ResizeTextAreaLog();
|
||||
function formatLogLine(line) {
|
||||
let className = '';
|
||||
if (line.includes('ERROR')) className = 'log-line-error';
|
||||
else if (line.includes('WARNING')) className = 'log-line-warning';
|
||||
else if (line.includes('INFO')) className = 'log-line-info';
|
||||
else if (line.includes('DEBUG')) className = 'log-line-debug';
|
||||
return '<div class="' + className + '">' + escapeHtml(line) + '</div>';
|
||||
}
|
||||
|
||||
$(document).ready(function() {
|
||||
$("#main_container").removeClass("container").addClass("container-fluid");
|
||||
$('#loading').show();
|
||||
setTimeout(function() {
|
||||
$('.content-cloak').addClass('visible');
|
||||
}, 100);
|
||||
});
|
||||
|
||||
var protocol = window.location.protocol;
|
||||
var socket = io.connect(protocol + "//" + document.domain + ":" + location.port + "/log");
|
||||
|
||||
socket.emit("start", {'package':'{{package}}'} );
|
||||
socket.on('on_start', function(data){
|
||||
var logEl = document.getElementById("log");
|
||||
logEl.innerHTML += data.data;
|
||||
logEl.scrollTop = logEl.scrollHeight;
|
||||
logEl.style.visibility = 'visible';
|
||||
$('#loading').hide();
|
||||
socket.emit("start", {'package':'{{package}}'});
|
||||
|
||||
socket.on('on_start', function(data) {
|
||||
var container = document.getElementById("log-history");
|
||||
var lines = data.data.split('\n');
|
||||
var html = '';
|
||||
lines.forEach(function(line) {
|
||||
html += formatLogLine(line);
|
||||
});
|
||||
container.innerHTML = html || '<div class="text-muted text-center">로그가 비어 있습니다.</div>';
|
||||
container.scrollTop = container.scrollHeight;
|
||||
$('#loading').hide();
|
||||
});
|
||||
|
||||
socket.on('add', function(data){
|
||||
if (data.package == "{{package}}") {
|
||||
var chk = $('#auto_scroll').is(":checked");
|
||||
var addEl = document.getElementById("add");
|
||||
addEl.innerHTML += data.data;
|
||||
if (chk) addEl.scrollTop = addEl.scrollHeight;
|
||||
}
|
||||
socket.on('add', function(data) {
|
||||
if (data.package == "{{package}}") {
|
||||
var chk = $('#auto_scroll').is(":checked");
|
||||
var container = document.getElementById("log-realtime");
|
||||
container.innerHTML += formatLogLine(data.data);
|
||||
if (chk) container.scrollTop = container.scrollHeight;
|
||||
}
|
||||
});
|
||||
|
||||
$("#clear").click(function(e) {
|
||||
e.preventDefault();
|
||||
document.getElementById("add").innerHTML = '';
|
||||
});
|
||||
</script>
|
||||
|
||||
<style>
|
||||
/* Smooth Load Transition */
|
||||
.content-cloak,
|
||||
#menu_module_div,
|
||||
#menu_page_div {
|
||||
opacity: 0;
|
||||
transition: opacity 0.5s ease-out;
|
||||
}
|
||||
|
||||
/* Staggered Delays for Natural Top-Down Flow */
|
||||
#menu_module_div.visible {
|
||||
opacity: 1;
|
||||
transition-delay: 0ms;
|
||||
}
|
||||
|
||||
#menu_page_div.visible {
|
||||
opacity: 1;
|
||||
transition-delay: 150ms;
|
||||
}
|
||||
|
||||
.content-cloak.visible {
|
||||
opacity: 1;
|
||||
transition-delay: 300ms;
|
||||
}
|
||||
</style>
|
||||
|
||||
<script type="text/javascript">
|
||||
$(document).ready(function(){
|
||||
// Smooth Load Trigger
|
||||
setTimeout(function() {
|
||||
$('.content-cloak, #menu_module_div, #menu_page_div').addClass('visible');
|
||||
}, 100);
|
||||
e.preventDefault();
|
||||
document.getElementById("log-realtime").innerHTML = '';
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -3,451 +3,409 @@
|
||||
<link rel="stylesheet" href="{{ url_for('.static', filename='css/mobile_custom.css') }}"/>
|
||||
<link rel="stylesheet" href="{{ url_for('.static', filename='css/' ~ arg['sub'] ~ '.css') }}"/>
|
||||
|
||||
<script type="text/javascript">
|
||||
function globalConfirmModal(title, body, func) {
|
||||
$("#confirm_title").html(title);
|
||||
$("#confirm_body").html(body);
|
||||
|
||||
// Remove previous handlers to prevent accumulation
|
||||
$("body").off('click', '#confirm_button').on('click', '#confirm_button', function(e){
|
||||
e.stopImmediatePropagation();
|
||||
e.preventDefault();
|
||||
if (typeof func === 'function') {
|
||||
func();
|
||||
}
|
||||
$("body").off('click', '#confirm_button');
|
||||
$("#confirm_modal").modal('hide');
|
||||
});
|
||||
|
||||
// Clean up listener when modal is closed (any way)
|
||||
$("#confirm_modal").one('hidden.bs.modal', function () {
|
||||
$("body").off('click', '#confirm_button');
|
||||
$('#confirm_button').removeAttr('onclick');
|
||||
});
|
||||
|
||||
<div id="ohli24_queue_wrapper" class="ohli24-common-wrapper container-fluid mt-4 content-cloak ohli24-queue-page">
|
||||
<div class="glass-card p-4">
|
||||
<!-- 헤더 버튼 그룹 -->
|
||||
<div class="ohli24-header">
|
||||
<div class="ohli24-header-left">
|
||||
<div class="ohli24-icon-box">
|
||||
<i class="bi bi-cloud-download-fill text-primary" style="font-size: 1.5rem;"></i>
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="ohli24-header-title">다운로드 큐</h3>
|
||||
<span class="ohli24-header-subtitle">총 <span id="queue_count" class="text-info font-weight-bold">0</span>개의 항목</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ohli24-header-right d-flex flex-wrap">
|
||||
<button id="reset_btn" class="btn-modern btn-modern-danger mr-2 mb-2">
|
||||
<i class="bi bi-arrow-counterclockwise mr-1"></i> 전체 초기화
|
||||
</button>
|
||||
<button id="delete_completed_btn" class="btn-modern btn-modern-warning mr-2 mb-2">
|
||||
<i class="bi bi-trash mr-1"></i> 완료 항목 삭제
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 다운로드 목록 -->
|
||||
<div id="download_list_div" class="queue-list d-flex flex-column gap-3"></div>
|
||||
|
||||
<!-- 빈 상태 표시 -->
|
||||
<div id="empty_state" class="empty-state d-flex flex-column align-items-center justify-content-center py-5" style="display: none; min-height: 300px;">
|
||||
<div class="empty-icon-wrapper mb-4">
|
||||
<i class="bi bi-inbox-fill text-muted opacity-20" style="font-size: 5rem;"></i>
|
||||
</div>
|
||||
<h4 class="text-white-50 font-weight-bold mb-2">다운로드 대기 항목 없음</h4>
|
||||
<p class="text-muted mb-0">새로운 에피소드를 추가하면 이곳에 실시간으로 나타납니다.</p>
|
||||
<div class="mt-4">
|
||||
<span class="badge badge-pill badge-dark py-2 px-3" style="background: rgba(255,255,255,0.05); color: #64748b; font-weight: 500;">
|
||||
<i class="bi bi-info-circle mr-1"></i> 에피소드 목록에서 '다운로드'를 눌러보세요
|
||||
</span>
|
||||
</div>
|
||||
$("#confirm_modal").modal();
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.queue-header-container {
|
||||
display: flex; justify-content: space-between; align-items: flex-end;
|
||||
margin-bottom: 20px; border-bottom: 1px solid rgba(16, 185, 129, 0.2); padding-bottom: 10px;
|
||||
}
|
||||
.queue-title { color: var(--forest-accent); font-weight: 700; margin: 0; }
|
||||
.queue-meta { font-size: 12px; color: #6ee7b7; opacity: 0.6; }
|
||||
|
||||
.custom-queue-table {
|
||||
background: rgba(6, 78, 59, 0.2); border-collapse: separate; border-spacing: 0 4px; color: #ecfdf5;
|
||||
}
|
||||
.custom-queue-table thead th {
|
||||
background: rgba(2, 44, 34, 0.8) !important; color: #6ee7b7; font-size: 13px;
|
||||
text-transform: uppercase; border: none !important; padding: 12px 8px !important;
|
||||
text-align: center;
|
||||
}
|
||||
.custom-queue-table tbody tr {
|
||||
background: rgba(6, 78, 59, 0.3); transition: all 0.2s;
|
||||
}
|
||||
.custom-queue-table tbody tr:hover { background: rgba(6, 78, 59, 0.5) !important; }
|
||||
.custom-queue-table td { border: none !important; vertical-align: middle !important; padding: 14px 8px !important; }
|
||||
|
||||
/* Badges & Status */
|
||||
.badge-status {
|
||||
padding: 4px 10px; border-radius: 6px; font-size: 11px; font-weight: 700;
|
||||
display: inline-block; min-width: 60px; text-align: center;
|
||||
}
|
||||
.status-downloading { background: rgba(16, 185, 129, 0.2); color: #34d399; border: 1px solid rgba(16, 185, 129, 0.3); }
|
||||
.status-wait { background: rgba(251, 191, 36, 0.1); color: #fbbf24; border: 1px solid rgba(251, 191, 36, 0.2); }
|
||||
.status-completed { background: rgba(59, 130, 246, 0.2); color: #60a5fa; border: 1px solid rgba(59, 130, 246, 0.3); }
|
||||
.status-fail { background: rgba(239, 68, 68, 0.2); color: #f87171; border: 1px solid rgba(239, 68, 68, 0.3); }
|
||||
|
||||
/* Progress Bar */
|
||||
.custom-progress { height: 18px; background: rgba(0,0,0,0.4); border-radius: 9px; overflow: hidden; border: 1px solid rgba(16, 185, 129, 0.1); }
|
||||
.custom-progress .progress-bar {
|
||||
background: linear-gradient(90deg, #10b981, #059669) !important;
|
||||
font-weight: 700; font-size: 11px;
|
||||
transition: width 0.4s ease-out;
|
||||
box-shadow: inset 0 1px 2px rgba(0,0,0,0.1);
|
||||
}
|
||||
|
||||
/* Action Buttons */
|
||||
.action-btn-mini {
|
||||
width: 32px; height: 32px; border-radius: 8px; border: none; font-size: 14px;
|
||||
display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.2s;
|
||||
}
|
||||
.action-btn-mini.btn-danger { background: rgba(239, 68, 68, 0.2); color: #f87171; border: 1px solid rgba(239, 68, 68, 0.3); }
|
||||
.action-btn-mini.btn-danger:hover { background: #ef4444; color: white; transform: scale(1.1); }
|
||||
.action-btn-mini.btn-warning { background: rgba(245, 158, 11, 0.2); color: #fbbf24; border: 1px solid rgba(245, 158, 11, 0.3); }
|
||||
.action-btn-mini.btn-warning:hover { background: #f59e0b; color: white; transform: scale(1.1); }
|
||||
|
||||
.action-btn-group { display: flex; justify-content: center; gap: 4px; }
|
||||
|
||||
.header-buttons { display: flex; gap: 10px; align-items: center; }
|
||||
.queue-btn-top {
|
||||
display: flex; align-items: center; gap: 6px; padding: 6px 14px;
|
||||
border: none; border-radius: 8px; font-weight: 600; font-size: 13px;
|
||||
cursor: pointer; transition: all 0.3s ease;
|
||||
}
|
||||
.queue-btn-top.btn-danger { background: rgba(239, 68, 68, 0.2); color: #f87171; border: 1px solid rgba(239, 68, 68, 0.3); }
|
||||
.queue-btn-top.btn-danger:hover { background: #ef4444; color: white; box-shadow: 0 0 15px rgba(239, 68, 68, 0.4); }
|
||||
.queue-btn-top.btn-warning { background: rgba(245, 158, 11, 0.2); color: #fbbf24; border: 1px solid rgba(245, 158, 11, 0.3); }
|
||||
.queue-btn-top.btn-warning:hover { background: #f59e0b; color: white; box-shadow: 0 0 15px rgba(245, 158, 11, 0.4); }
|
||||
|
||||
/* Details */
|
||||
.queue-detail-container { color: #d1fae5; font-size: 13px; }
|
||||
.detail-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 10px 20px; }
|
||||
.detail-item { display: flex; gap: 10px; align-items: flex-start; }
|
||||
.detail-item .label { color: #6ee7b7; font-weight: 700; min-width: 100px; opacity: 0.7; font-size: 11px; text-transform: uppercase; }
|
||||
.detail-item .value { color: #ecfdf5; word-break: break-all; }
|
||||
|
||||
/* Smooth Load */
|
||||
.content-cloak { opacity: 0; transition: opacity 0.5s ease-out; }
|
||||
.content-cloak.visible { opacity: 1; }
|
||||
</style>
|
||||
|
||||
<div class="content-cloak">
|
||||
<div class="queue-header-container">
|
||||
<h4 class="queue-title"><i class="fa fa-download"></i> 다운로드 큐</h4>
|
||||
<div class="header-buttons">
|
||||
<button id="reset_btn" class="queue-btn-top btn-danger">
|
||||
<i class="fa fa-refresh"></i> 초기화
|
||||
</button>
|
||||
<button id="delete_completed_btn" class="queue-btn-top btn-warning">
|
||||
<i class="fa fa-trash"></i> 완료 삭제
|
||||
</button>
|
||||
</div>
|
||||
<div class="queue-meta">실시간 동기화 활성화됨 (3초 주기)</div>
|
||||
</div>
|
||||
|
||||
<div class="table-responsive-custom">
|
||||
<table id="result_table" class="table custom-queue-table tableRowHover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width:5%;">IDX</th>
|
||||
<th style="width:8%;">Plugin</th>
|
||||
<th style="width:10%;">시작시간</th>
|
||||
<th style="width:25%;">파일명</th>
|
||||
<th style="width:8%;">상태</th>
|
||||
<th style="width:18%;">진행률</th>
|
||||
<th style="width:6%;">길이</th>
|
||||
<th style="width:5%;">PF</th>
|
||||
<th style="width:10%;">현재 상태</th>
|
||||
<th style="width:5%;">Action</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="list"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
/* Premium Glassmorphism UI */
|
||||
.ohli24-queue-page {
|
||||
animation: fadeIn 0.5s ease-out;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; transform: translateY(10px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
.icon-box {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
background: rgba(59, 130, 246, 0.1);
|
||||
border-radius: 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: 1px solid rgba(59, 130, 246, 0.2);
|
||||
}
|
||||
|
||||
/* Modern Buttons */
|
||||
.btn-modern {
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
padding: 10px 18px;
|
||||
font-weight: 600;
|
||||
font-size: 0.9rem;
|
||||
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: white;
|
||||
text-transform: none;
|
||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.btn-modern:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 15px rgba(0, 0, 0, 0.2);
|
||||
filter: brightness(1.1);
|
||||
}
|
||||
|
||||
.btn-modern:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.btn-modern-danger { background: linear-gradient(135deg, #f43f5e 0%, #e11d48 100%); }
|
||||
.btn-modern-warning { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); }
|
||||
.btn-modern-info { background: linear-gradient(135deg, #0ea5e9 0%, #0284c7 100%); }
|
||||
.btn-modern-secondary { background: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.1); }
|
||||
|
||||
/* Queue Items */
|
||||
.queue-item {
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
border: 1px solid rgba(255, 255, 255, 0.05);
|
||||
border-radius: 16px;
|
||||
padding: 16px;
|
||||
transition: all 0.3s ease;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 15px;
|
||||
}
|
||||
|
||||
.queue-item:hover {
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border-color: rgba(255, 255, 255, 0.1);
|
||||
transform: translateX(4px);
|
||||
}
|
||||
|
||||
.item-number {
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
font-weight: 700;
|
||||
color: #64748b;
|
||||
font-size: 1.1rem;
|
||||
min-width: 40px;
|
||||
}
|
||||
|
||||
.item-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.item-filename {
|
||||
color: #f1f5f9;
|
||||
font-weight: 600;
|
||||
font-size: 0.95rem;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.item-meta {
|
||||
font-size: 0.8rem;
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
/* Modern Progress Bar */
|
||||
.progress-container {
|
||||
flex: 1.5;
|
||||
min-width: 150px;
|
||||
}
|
||||
|
||||
.progress-wrapper {
|
||||
position: relative;
|
||||
height: 28px;
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
border-radius: 14px;
|
||||
overflow: hidden;
|
||||
border: 1px solid rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
.progress-bar {
|
||||
height: 100%;
|
||||
border-radius: 14px;
|
||||
transition: width 0.4s cubic-bezier(0.4, 0, 0.2, 1), background-color 0.3s ease;
|
||||
}
|
||||
|
||||
.status-waiting { background: linear-gradient(90deg, #64748b, #475569); }
|
||||
.status-downloading {
|
||||
background: linear-gradient(90deg, #3b82f6, #2563eb);
|
||||
box-shadow: 0 0 10px rgba(59, 130, 246, 0.3);
|
||||
}
|
||||
.status-completed {
|
||||
background: linear-gradient(90deg, #10b981, #059669);
|
||||
box-shadow: 0 0 10px rgba(16, 185, 129, 0.3);
|
||||
}
|
||||
.status-failed { background: linear-gradient(90deg, #ef4444, #dc2626); }
|
||||
|
||||
.progress-label {
|
||||
position: absolute;
|
||||
top: 0; left: 0; width: 100%; height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 700;
|
||||
color: white;
|
||||
text-shadow: 0 1px 2px rgba(0,0,0,0.5);
|
||||
pointer-events: none;
|
||||
padding: 0 10px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Actions */
|
||||
.cancel-btn {
|
||||
background: rgba(239, 68, 68, 0.1);
|
||||
border: 1px solid rgba(239, 68, 68, 0.2);
|
||||
color: #f87171;
|
||||
padding: 6px 12px;
|
||||
border-radius: 8px;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
transition: all 0.2s;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.cancel-btn:hover {
|
||||
background: #ef4444;
|
||||
color: white;
|
||||
}
|
||||
|
||||
@media (max-width: 992px) {
|
||||
.queue-item { flex-direction: column; align-items: stretch; }
|
||||
.progress-container { flex: none; width: 100%; }
|
||||
.item-actions { display: flex; justify-content: flex-end; }
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
animation: fadeIn 0.8s ease-out;
|
||||
}
|
||||
|
||||
.empty-icon-wrapper i {
|
||||
display: inline-block;
|
||||
transition: transform 0.3s ease;
|
||||
}
|
||||
|
||||
.empty-state:hover .empty-icon-wrapper i {
|
||||
transform: translateY(-10px);
|
||||
color: #3b82f6 !important;
|
||||
opacity: 0.4 !important;
|
||||
}
|
||||
</style>
|
||||
|
||||
<script src="{{ url_for('.static', filename='js/sjva_ui14.js') }}"></script>
|
||||
<script type="text/javascript">
|
||||
var package_name = "{{arg['package_name'] }}";
|
||||
var sub = "{{arg['sub'] }}";
|
||||
var current_data = null;
|
||||
|
||||
$(document).ready(function () {
|
||||
// Force parent container to be fluid to allow full width
|
||||
$("#main_container").removeClass("container").addClass("container-fluid");
|
||||
|
||||
// Smooth Load Trigger
|
||||
setTimeout(function() {
|
||||
$('.content-cloak, #menu_module_div, #menu_page_div').addClass('visible');
|
||||
}, 100);
|
||||
|
||||
var socket = io.connect(window.location.href);
|
||||
socket.on('on_start', (data) => {})
|
||||
socket.on('start', function (data) {
|
||||
on_start();
|
||||
});
|
||||
socket.on('list_refresh', function (data) {
|
||||
on_start()
|
||||
});
|
||||
socket.on('status', function (data) {
|
||||
on_status(data)
|
||||
});
|
||||
|
||||
on_start();
|
||||
var refreshIntervalId = setInterval(silentRefresh, 3000);
|
||||
});
|
||||
|
||||
var PACKAGE_NAME = "{{ arg['package_name'] }}";
|
||||
var MODULE_NAME = "{{ arg['module_name'] }}";
|
||||
var current_list_length = 0;
|
||||
var refreshIntervalId = null;
|
||||
|
||||
function silentRefresh() {
|
||||
$.ajax({
|
||||
url: '/' + package_name + '/ajax/' + sub + '/entity_list',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
global: false,
|
||||
data: {},
|
||||
dataType: "json",
|
||||
success: function (data) {
|
||||
// 목록 길이 변경 시 전체 다시 그리기
|
||||
if (data.length !== current_list_length) {
|
||||
current_list_length = data.length;
|
||||
make_download_list(data);
|
||||
} else {
|
||||
// 진행률만 업데이트 (전체 다시 그리기 없이)
|
||||
for (var i = 0; i < data.length; i++) {
|
||||
var item = data[i];
|
||||
var progressBar = document.getElementById("progress_" + item.entity_id);
|
||||
if (progressBar) {
|
||||
progressBar.style.width = item.ffmpeg_percent + '%';
|
||||
var label = item.ffmpeg_status_kor;
|
||||
if (item.ffmpeg_percent != 0) label += " (" + item.ffmpeg_percent + "%)";
|
||||
if (item.current_speed) label += " " + item.current_speed;
|
||||
var labelEl = document.getElementById("progress_" + item.entity_id + "_label");
|
||||
if (labelEl) labelEl.innerHTML = label;
|
||||
|
||||
// 상태 클래스 업데이트
|
||||
var statusClass = getStatusClass(item.ffmpeg_status_kor);
|
||||
$(progressBar).removeClass('status-waiting status-downloading status-completed status-failed').addClass(statusClass);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var hasActive = false;
|
||||
for (var i = 0; i < data.length; i++) {
|
||||
if (data[i].ffmpeg_status_kor === '다운로드중' || data[i].ffmpeg_status_kor === '대기중' || data[i].ffmpeg_status_kor === '추출중') {
|
||||
hasActive = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasActive && refreshIntervalId) {
|
||||
clearInterval(refreshIntervalId);
|
||||
refreshIntervalId = null;
|
||||
}
|
||||
if (hasActive && !refreshIntervalId) {
|
||||
refreshIntervalId = setInterval(silentRefresh, 2000);
|
||||
}
|
||||
$(document).ready(function(){
|
||||
$(".content-cloak").addClass("visible");
|
||||
|
||||
var protocol = location.protocol;
|
||||
var socketUrl = protocol + "//" + document.domain + ":" + location.port;
|
||||
|
||||
// Queue 전용 소켓 시도
|
||||
var queueSocket = null;
|
||||
try {
|
||||
queueSocket = io.connect(socketUrl + '/anime_downloader/linkkf/queue');
|
||||
} catch (e) {
|
||||
console.error('Queue socket error:', e);
|
||||
}
|
||||
|
||||
var frameworkSocket = null;
|
||||
try {
|
||||
frameworkSocket = io.connect(socketUrl + '/framework');
|
||||
frameworkSocket.on('linkkf_status', function(data) {
|
||||
status_html(data);
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('Framework socket error:', e);
|
||||
}
|
||||
|
||||
var socket = queueSocket;
|
||||
if (socket) {
|
||||
socket.on('status_change', function(data) { button_html(data); });
|
||||
socket.on('status', function(data){ status_html(data); });
|
||||
socket.on('last', function(data){ status_html(data); button_html(data); });
|
||||
}
|
||||
|
||||
// GDM 전용 소켓 추가 핸들링 (전역 업데이트 수신용)
|
||||
var gdmSocket = null;
|
||||
try {
|
||||
gdmSocket = io.connect(socketUrl + '/gommi_downloader_manager');
|
||||
gdmSocket.on('status', function(data) {
|
||||
// 이 모듈과 관련된 작업만 처리
|
||||
if (data.caller_plugin === PACKAGE_NAME + '_' + MODULE_NAME) {
|
||||
// GDM 데이터를 큐 형식으로 변환하여 UI 업데이트
|
||||
// 수동 새로고침 없이 실시간 반영을 위해 renderList 호출 주기를 짧게 하거나 직접 UI 갱신
|
||||
silentFetchList(function(newList) {
|
||||
renderList(newList);
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('GDM socket error:', e);
|
||||
}
|
||||
|
||||
function on_start() {
|
||||
$.ajax({
|
||||
url: '/' + package_name + '/ajax/' + sub + '/entity_list',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: {},
|
||||
dataType: "json",
|
||||
success: function (data) {
|
||||
current_list_length = data.length;
|
||||
make_download_list(data)
|
||||
}
|
||||
});
|
||||
}
|
||||
on_start();
|
||||
refreshIntervalId = setInterval(autoRefreshList, 3000);
|
||||
});
|
||||
|
||||
function on_status(data) {
|
||||
var entity_id = data.entity_id;
|
||||
var percent = data.ffmpeg_percent;
|
||||
var status_kor = data.ffmpeg_status_kor;
|
||||
var speed = data.current_speed;
|
||||
|
||||
var progressBar = document.getElementById("progress_" + entity_id);
|
||||
if (progressBar != null) {
|
||||
// Update percentage and label
|
||||
progressBar.style.width = percent + '%';
|
||||
var label = status_kor;
|
||||
if (percent != 0) label += " (" + percent + "%)";
|
||||
if (speed) label += " " + speed;
|
||||
document.getElementById("progress_" + entity_id + "_label").innerHTML = label;
|
||||
|
||||
// Real-time status class (color) update
|
||||
var statusClass = getStatusClass(status_kor);
|
||||
$(progressBar).removeClass('status-waiting status-downloading status-completed status-failed').addClass(statusClass);
|
||||
|
||||
// Auto-refresh list if completed to show 'Watch' button or other actions
|
||||
if (status_kor === '완료' || status_kor === 'completed') {
|
||||
// Throttle refresh to avoid flickering if multiple complete
|
||||
if (window.statusRefreshTimeout) clearTimeout(window.statusRefreshTimeout);
|
||||
window.statusRefreshTimeout = setTimeout(on_start, 1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
var refreshIntervalId = null;
|
||||
|
||||
function getStatusClass(status) {
|
||||
if (status === '다운로드중') return 'status-downloading';
|
||||
if (status === '완료' || status === 'completed') return 'status-completed';
|
||||
if (status === '실패' || status === 'FAILED') return 'status-failed';
|
||||
return 'status-waiting';
|
||||
}
|
||||
function silentFetchList(callback) {
|
||||
$.ajax({
|
||||
url: '/' + PACKAGE_NAME + '/ajax/' + MODULE_NAME + '/command',
|
||||
type: 'POST',
|
||||
cache: false,
|
||||
global: false,
|
||||
data: {command: 'list'},
|
||||
dataType: 'json',
|
||||
success: function(data) { if (callback) callback(data); }
|
||||
});
|
||||
}
|
||||
|
||||
function make_download_list(data) {
|
||||
document.getElementById('queue_count').textContent = data.length;
|
||||
|
||||
if (data.length === 0) {
|
||||
document.getElementById('download_list_div').style.display = 'none';
|
||||
document.getElementById('empty_state').style.display = 'flex';
|
||||
return;
|
||||
function autoRefreshList() {
|
||||
silentFetchList(function(data) {
|
||||
if (data.length !== current_list_length) {
|
||||
current_list_length = data.length;
|
||||
renderList(data);
|
||||
}
|
||||
|
||||
document.getElementById('download_list_div').style.display = 'flex';
|
||||
document.getElementById('empty_state').style.display = 'none';
|
||||
var hasActiveDownload = false;
|
||||
if (data && data.length > 0) {
|
||||
for (var j = 0; j < data.length; j++) {
|
||||
if (data[j].status_str === 'DOWNLOADING' || data[j].status_str === 'WAITING' || data[j].status_str === 'STARTED') {
|
||||
hasActiveDownload = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasActiveDownload && refreshIntervalId) {
|
||||
clearInterval(refreshIntervalId);
|
||||
refreshIntervalId = null;
|
||||
}
|
||||
if (hasActiveDownload && !refreshIntervalId) {
|
||||
refreshIntervalId = setInterval(autoRefreshList, 3000);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function on_start() {
|
||||
silentFetchList(function(data) {
|
||||
current_list_length = data.length;
|
||||
renderList(data);
|
||||
});
|
||||
}
|
||||
|
||||
function renderList(data) {
|
||||
$("#list").html('');
|
||||
if (!data || data.length == 0) {
|
||||
$("#list").html("<tr><td colspan='10' style='text-align:center; padding: 40px; color: #6ee7b7;'>다운로드 대기 중인 작업이 없습니다.</td></tr>");
|
||||
} else {
|
||||
var str = '';
|
||||
for (var i in data) {
|
||||
var item = data[i];
|
||||
var statusClass = getStatusClass(item.ffmpeg_status_kor);
|
||||
var label = item.ffmpeg_status_kor;
|
||||
if (item.ffmpeg_percent != 0) {
|
||||
label += ' (' + item.ffmpeg_percent + '%)';
|
||||
}
|
||||
|
||||
str += '<div class="queue-item">';
|
||||
str += '<div class="item-number">#' + item.entity_id + '</div>';
|
||||
str += '<div class="item-info">';
|
||||
str += '<div class="item-filename">' + (item.filename || '파일명 없음') + '</div>';
|
||||
str += '<div class="item-meta">';
|
||||
str += '<span class="item-time"><i class="fa fa-clock-o"></i> ' + item.created_time + '</span>';
|
||||
str += '</div>';
|
||||
str += '</div>';
|
||||
str += '<div class="progress-container">';
|
||||
str += '<div class="progress-wrapper">';
|
||||
str += '<div id="progress_' + item.entity_id + '" class="progress-bar ' + statusClass + '" style="width: ' + item.ffmpeg_percent + '%;"></div>';
|
||||
str += '<span id="progress_' + item.entity_id + '_label" class="progress-label">' + label + '</span>';
|
||||
str += '</div>';
|
||||
str += '</div>';
|
||||
str += '<div class="item-actions">';
|
||||
str += '<button class="cancel-btn" data-id="' + item.entity_id + '" onclick="cancelItem(' + item.entity_id + ')"><i class="fa fa-times"></i> 취소</button>';
|
||||
str += '</div>';
|
||||
str += '</div>';
|
||||
for(var i in data) {
|
||||
str += make_item(data[i]);
|
||||
}
|
||||
document.getElementById("download_list_div").innerHTML = str;
|
||||
$("#list").html(str);
|
||||
}
|
||||
}
|
||||
|
||||
function cancelItem(entity_id) {
|
||||
queue_command({'command': 'cancel', 'entity_id': entity_id});
|
||||
}
|
||||
|
||||
$("body").on('click', '#reset_btn', function (e) {
|
||||
e.preventDefault();
|
||||
if (!confirm('정말 큐를 초기화하시겠습니까?')) return;
|
||||
queue_command({'command': 'reset', 'entity_id': -1});
|
||||
$("body").on('click', '#stop_btn', function(e){
|
||||
e.stopPropagation(); e.preventDefault();
|
||||
globalSendCommand('stop', $(this).data('idx'), null, null, function(ret){
|
||||
autoRefreshList();
|
||||
});
|
||||
});
|
||||
|
||||
$("body").on('click', '#delete_completed_btn', function (e) {
|
||||
e.preventDefault();
|
||||
queue_command({'command': 'delete_completed', 'entity_id': -1});
|
||||
});
|
||||
|
||||
function queue_command(data) {
|
||||
$.ajax({
|
||||
url: '/' + package_name + '/ajax/' + sub + '/queue_command',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: data,
|
||||
dataType: "json",
|
||||
success: function (ret) {
|
||||
if (ret.ret == 'notify') {
|
||||
$.notify('<strong>' + ret.log + '</strong>', {type: 'warning'});
|
||||
}
|
||||
on_start();
|
||||
}
|
||||
$("body").on('click', '#reset_btn', function(e){
|
||||
e.preventDefault();
|
||||
globalConfirmModal('초기화 하시겠습니까?', function(){
|
||||
globalSendCommand('reset', null, null, null, function(ret){
|
||||
autoRefreshList();
|
||||
});
|
||||
}
|
||||
|
||||
$("body").on('click', '#go_ffmpeg_btn', function (e) {
|
||||
e.preventDefault();
|
||||
$(location).attr('href', '/ffmpeg')
|
||||
});
|
||||
});
|
||||
|
||||
$("body").on('click', '#delete_completed_btn', function(e){
|
||||
e.preventDefault();
|
||||
globalSendCommand('delete_completed', null, null, null, function(ret){
|
||||
autoRefreshList();
|
||||
});
|
||||
});
|
||||
|
||||
$("body").on('click', '#delete_btn', function(e){
|
||||
e.stopPropagation(); e.preventDefault();
|
||||
let idx = $(this).data('idx');
|
||||
globalSendCommand('remove', idx, null, null, function(ret){
|
||||
autoRefreshList();
|
||||
});
|
||||
});
|
||||
|
||||
function refresh_item(data) {
|
||||
if (!data || !data.idx) {
|
||||
autoRefreshList();
|
||||
return;
|
||||
}
|
||||
$('#tr1_'+data.idx).html(make_item1(data));
|
||||
$('#collapse_'+data.idx).html(make_item2(data));
|
||||
}
|
||||
|
||||
function make_item(data) {
|
||||
var str = '<tr id="tr1_'+data.idx+'" style="cursor: pointer;" data-toggle="collapse" data-target="#collapse_'+ data.idx + '" aria-expanded="false" >';
|
||||
str += make_item1(data);
|
||||
str += '</tr>';
|
||||
str += '<tr class="collapse tableRowHoverOff" id="collapse_' + data.idx + '">';
|
||||
str += make_item2(data);
|
||||
str += '</tr>';
|
||||
return str;
|
||||
}
|
||||
|
||||
function make_item1(data) {
|
||||
var str = '<td style="text-align:center;">'+ data.idx + '</td>';
|
||||
str += '<td style="text-align:center;"><span class="badge badge-info">'+ data.callback_id + '</span></td>';
|
||||
str += '<td style="text-align:center; font-size: 12px; color: #6ee7b7;">'+ data.start_time + '</td>';
|
||||
str += '<td style="font-weight: 600;">'+ data.filename + '</td>';
|
||||
|
||||
var status_class = 'status-wait';
|
||||
if (data.status_str === 'DOWNLOADING') status_class = 'status-downloading';
|
||||
else if (data.status_str === 'COMPLETED') status_class = 'status-completed';
|
||||
else if (data.status_str === 'STOP') status_class = 'status-fail';
|
||||
|
||||
str += '<td id="status_'+data.idx+'" style="text-align:center;"><span class="badge-status ' + status_class + '">'+ data.status_kor + '</span></td>';
|
||||
|
||||
var visi = (parseInt(data.percent) > 0) ? 'visible' : 'hidden';
|
||||
str += '<td><div class="progress custom-progress"><div id="progress_'+data.idx+'" class="progress-bar" style="visibility: '+visi+'; width:'+data.percent+'%">'+data.percent +'%</div></div></td>';
|
||||
|
||||
str += '<td style="text-align:center;">'+ data.duration_str + '</td>';
|
||||
str += '<td id="current_pf_count_'+data.idx+'" style="text-align:center; color: #f87171;">'+ data.current_pf_count + '</td>';
|
||||
str += '<td style="text-align:center; font-size: 13px;"><div id="current_speed_'+data.idx+'">'+ data.current_speed + '</div><div id="download_time_'+data.idx+'" style="font-size: 11px; opacity: 0.6;">'+ data.download_time + '</div></td>';
|
||||
|
||||
str += '<td id="button_'+data.idx+'" style="text-align:center; padding: 10px 4px !important;">';
|
||||
str += '<div class="action-btn-group">';
|
||||
if (data.status_str == 'DOWNLOADING' || data.status_str == 'WAITING') {
|
||||
str += '<button id="stop_btn" class="action-btn-mini btn-danger" data-idx="'+data.idx+'" title="중지"><i class="fa fa-stop"></i></button>';
|
||||
} else {
|
||||
str += '<button id="delete_btn" class="action-btn-mini btn-warning" data-idx="'+data.idx+'" title="삭제"><i class="fa fa-times"></i></button>';
|
||||
}
|
||||
str += '</div>';
|
||||
str += '</td>';
|
||||
return str;
|
||||
}
|
||||
|
||||
function make_item2(data) {
|
||||
var str = '<td colspan="10" style="background: rgba(0,0,0,0.2); padding: 15px !important;">';
|
||||
str += '<div id="detail_'+data.idx+'" class="queue-detail-container">';
|
||||
str += get_detail(data);
|
||||
str += '</div>';
|
||||
str += '</td>';
|
||||
return str;
|
||||
}
|
||||
|
||||
function get_detail(data) {
|
||||
var str = '<div class="detail-grid">';
|
||||
str += '<div class="detail-item"><span class="label">파일 경로</span><span class="value">' + data.save_fullpath + '</span></div>';
|
||||
str += '<div class="detail-item"><span class="label">URL</span><span class="value text-truncate">' + data.url + '</span></div>';
|
||||
str += '<div class="detail-item"><span class="label">진행 상황</span><span class="value">' + data.percent+ '% (' + data.current_duration + ' / ' + data.duration + ')</span></div>';
|
||||
str += '<div class="detail-item"><span class="label">비트레이트</span><span class="value">' + data.current_bitrate + '</span></div>';
|
||||
str += '<div class="detail-item"><span class="label">허용 에러(PF)</span><span class="value">' + data.max_pf_count + '</span></div>';
|
||||
if (data.status_str == 'COMPLETED') {
|
||||
str += '<div class="detail-item"><span class="label">파일 크기</span><span class="value">' + data.filesize_str + '</span></div>';
|
||||
str += '<div class="detail-item"><span class="label">최종 속도</span><span class="value">' + (data.download_speed || 'N/A') + '</span></div>';
|
||||
}
|
||||
str += '</div>';
|
||||
return str;
|
||||
}
|
||||
|
||||
function button_html(data) {
|
||||
var str = '<div class="action-btn-group">';
|
||||
if (data.status_str == 'DOWNLOADING' || data.status_str == 'WAITING') {
|
||||
str += '<button id="stop_btn" class="action-btn-mini btn-danger" data-idx="'+data.idx+'" title="중지"><i class="fa fa-stop"></i></button>';
|
||||
} else {
|
||||
str += '<button id="delete_btn" class="action-btn-mini btn-warning" data-idx="'+data.idx+'" title="삭제"><i class="fa fa-times"></i></button>';
|
||||
}
|
||||
str += '</div>';
|
||||
$("#button_" + data.idx).html(str);
|
||||
}
|
||||
|
||||
function status_html(data) {
|
||||
var progress = document.getElementById("progress_" + data.idx);
|
||||
if (!progress) return;
|
||||
|
||||
progress.style.width = data.percent+ '%';
|
||||
progress.innerHTML = data.percent+ '%';
|
||||
progress.style.visibility = 'visible';
|
||||
|
||||
var statusEl = document.getElementById("status_" + data.idx);
|
||||
if (statusEl) {
|
||||
var status_class = 'status-wait';
|
||||
if (data.status_str === 'DOWNLOADING') status_class = 'status-downloading';
|
||||
else if (data.status_str === 'COMPLETED') status_class = 'status-completed';
|
||||
else if (data.status_str === 'STOP') status_class = 'status-fail';
|
||||
statusEl.innerHTML = '<span class="badge-status ' + status_class + '">'+ data.status_kor + '</span>';
|
||||
}
|
||||
|
||||
var pfEl = document.getElementById("current_pf_count_" + data.idx);
|
||||
if (pfEl) pfEl.innerHTML = data.current_pf_count;
|
||||
|
||||
var speedEl = document.getElementById("current_speed_" + data.idx);
|
||||
if (speedEl) speedEl.innerHTML = data.current_speed;
|
||||
|
||||
var timeEl = document.getElementById("download_time_" + data.idx);
|
||||
if (timeEl) timeEl.innerHTML = data.download_time;
|
||||
|
||||
var detailEl = document.getElementById("detail_" + data.idx);
|
||||
if (detailEl) detailEl.innerHTML = get_detail(data);
|
||||
}
|
||||
</script>
|
||||
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
{% endblock %}
|
||||
@@ -213,9 +213,14 @@
|
||||
let epThumbSrc = data.episode[i].thumbnail || '';
|
||||
let epTitle = data.episode[i].title || '';
|
||||
|
||||
// 에피소드 번호 추출 (title에서 "N화" 패턴 찾기)
|
||||
let epNumMatch = epTitle.match(/(\d+)화/);
|
||||
let epNumText = epNumMatch ? epNumMatch[1] + '화' : (parseInt(i) + 1) + '화';
|
||||
// 에피소드 번호 추출: 백엔드 epi_no 우선, 없으면 정규식, 마지막으로 인덱스
|
||||
let epNumText = '';
|
||||
if (data.episode[i].epi_no !== undefined && data.episode[i].epi_no !== null) {
|
||||
epNumText = data.episode[i].epi_no + '화';
|
||||
} else {
|
||||
let epNumMatch = epTitle.match(/(\d+(?:\.\d+)?)[\s\.\…화회]*$/);
|
||||
epNumText = epNumMatch ? epNumMatch[1] + '화' : (parseInt(i) + 1) + '화';
|
||||
}
|
||||
|
||||
str += '<div class="episode-card">';
|
||||
str += '<div class="episode-thumb">';
|
||||
|
||||
@@ -17,6 +17,9 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="ohli24-header-right">
|
||||
<button type="button" class="btn btn-outline-info btn-sm mr-2" id="btn-self-update" title="최신 버전으로 업데이트">
|
||||
<i class="bi bi-arrow-repeat"></i> 업데이트
|
||||
</button>
|
||||
{{ macros.m_button_group([['globalSettingSaveBtn', '설정 저장']])}}
|
||||
</div>
|
||||
</div>
|
||||
@@ -855,6 +858,105 @@ function getDragAfterElement(container, x) {
|
||||
}, { offset: Number.NEGATIVE_INFINITY }).element;
|
||||
}
|
||||
|
||||
// ======================================
|
||||
// 자가 업데이트 기능
|
||||
// ======================================
|
||||
$(document).on('click', '#btn-self-update', function() {
|
||||
$('#updateConfirmModal').modal('show');
|
||||
});
|
||||
|
||||
// 실제 업데이트 실행 (이벤트 위임 - 모달이 스크립트 이후에 있으므로)
|
||||
$(document).on('click', '#confirmUpdateBtn', function() {
|
||||
$('#updateConfirmModal').modal('hide');
|
||||
|
||||
var btn = $('#btn-self-update');
|
||||
var originalHTML = btn.html();
|
||||
btn.prop('disabled', true).html('<i class="bi bi-arrow-repeat spin"></i> 업데이트 중...');
|
||||
|
||||
$.ajax({
|
||||
url: '/' + package_name + '/ajax/' + sub + '/self_update',
|
||||
type: 'POST',
|
||||
dataType: 'json',
|
||||
success: function(ret) {
|
||||
if (ret.ret === 'success') {
|
||||
if (ret.needs_restart) {
|
||||
$.notify('<strong>⚠️ 모델 변경 감지!</strong><br>서버 재시작이 필요합니다.', {type: 'warning', delay: 10000});
|
||||
} else {
|
||||
$.notify('<strong>✅ 업데이트 완료!</strong><br>페이지를 새로고침하세요.', {type: 'success', delay: 5000});
|
||||
}
|
||||
} else {
|
||||
$.notify('<strong>업데이트 실패: ' + ret.msg + '</strong>', {type: 'danger'});
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
$.notify('<strong>업데이트 중 오류 발생</strong>', {type: 'danger'});
|
||||
},
|
||||
complete: function() {
|
||||
btn.prop('disabled', false).html(originalHTML);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
</script>
|
||||
|
||||
<!-- Update Confirmation Modal -->
|
||||
<div class="modal fade" id="updateConfirmModal" tabindex="-1" role="dialog" aria-hidden="true">
|
||||
<div class="modal-dialog modal-dialog-centered" role="document">
|
||||
<div class="modal-content animate__animated animate__zoomIn" style="background: linear-gradient(145deg, #1e293b 0%, #0f172a 100%); border: 1px solid rgba(59, 130, 246, 0.3); border-radius: 20px; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);">
|
||||
<div class="modal-body text-center" style="padding: 40px 30px;">
|
||||
<div style="width: 80px; height: 80px; background: linear-gradient(135deg, rgba(59, 130, 246, 0.2) 0%, rgba(99, 102, 241, 0.2) 100%); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 24px; border: 2px solid rgba(59, 130, 246, 0.3);">
|
||||
<i class="bi bi-arrow-repeat" style="color: #3b82f6; font-size: 36px;"></i>
|
||||
</div>
|
||||
<h4 style="color: #f1f5f9; font-weight: 700; margin-bottom: 12px;">플러그인 업데이트</h4>
|
||||
<p style="color: #94a3b8; font-size: 15px; margin-bottom: 8px;">최신 코드를 다운로드하고 플러그인을 리로드합니다.</p>
|
||||
<p style="color: #64748b; font-size: 13px; margin-bottom: 32px;"><i class="bi bi-info-circle"></i> 서버 재시작 없이 즉시 적용됩니다.</p>
|
||||
<div style="display: flex; gap: 12px; justify-content: center;">
|
||||
<button type="button" class="btn" data-dismiss="modal" style="width: 120px; background: rgba(255,255,255,0.1); border: 1px solid rgba(255,255,255,0.2); color: #94a3b8; border-radius: 10px; padding: 12px 24px; font-weight: 600;">취소</button>
|
||||
<button type="button" id="confirmUpdateBtn" class="btn" style="width: 140px; background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); border: none; color: white; border-radius: 10px; padding: 12px 24px; font-weight: 600; box-shadow: 0 4px 15px rgba(59, 130, 246, 0.4);">
|
||||
<i class="bi bi-download"></i> 업데이트
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
/* Update Button Enhanced Visibility */
|
||||
#btn-self-update {
|
||||
background: linear-gradient(135deg, #0ea5e9 0%, #0284c7 100%) !important;
|
||||
border: none !important;
|
||||
color: white !important;
|
||||
font-weight: 600;
|
||||
padding: 8px 16px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 8px rgba(14, 165, 233, 0.3);
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
#btn-self-update:hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, #0284c7 0%, #0369a1 100%) !important;
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 4px 12px rgba(14, 165, 233, 0.4);
|
||||
}
|
||||
#btn-self-update:disabled {
|
||||
background: linear-gradient(135deg, #475569 0%, #334155 100%) !important;
|
||||
color: #94a3b8 !important;
|
||||
cursor: not-allowed;
|
||||
box-shadow: none;
|
||||
opacity: 0.7;
|
||||
}
|
||||
#btn-self-update .bi-arrow-repeat.spin {
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
@keyframes spin {
|
||||
from { transform: rotate(0deg); }
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
/* Animate.css for modal */
|
||||
.animate__zoomIn {
|
||||
animation-duration: 0.3s;
|
||||
}
|
||||
</style>
|
||||
|
||||
{% endblock %}
|
||||
Reference in New Issue
Block a user