Skip to content

Commit

Permalink
feat: add setting file option
Browse files Browse the repository at this point in the history
  • Loading branch information
phillychi3 committed Dec 26, 2024
1 parent 30d28af commit a44be46
Show file tree
Hide file tree
Showing 8 changed files with 440 additions and 13 deletions.
22 changes: 22 additions & 0 deletions backend/src/core/syncfile.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from pathlib import Path
import os

from sqlalchemy import func
from db import get_db
from core.fileparser import FileParser, FileType
from sqlmodel import Session, select, union
Expand Down Expand Up @@ -63,6 +65,23 @@ def sync_video_file(metadata: dict, db: Session):
raise Exception(f"同步影片檔案失敗: {str(e)}")


def sync_album_data(album_id: int, db: Session):
"""更新專輯的資料 專輯數量等..."""
album = db.exec(select(Album).where(Album.id == album_id)).first()
if not album:
raise ValueError("Album not found")

album.total_tracks = db.exec(
select(func.count())
.select_from(MusicTrack)
.where(MusicTrack.album_id == album_id)
).first()

db.add(album)
db.commit()
return album


def sync_music_file(metadata: dict, db: Session):
"""同步音樂檔案到資料庫"""
track = MusicTrack(
Expand Down Expand Up @@ -113,6 +132,9 @@ def sync_music_file(metadata: dict, db: Session):
db.add(track_file)
db.commit()

if track.album_id:
sync_album_data(track.album_id, db)

return track_file

except Exception as e:
Expand Down
2 changes: 2 additions & 0 deletions backend/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from routers.file import file_router
from routers.stream import stream_router
from routers.user import user_router
from routers.setting import setting_router
from core.logger import logger
from starlette.middleware.cors import CORSMiddleware

Expand All @@ -35,6 +36,7 @@ def ping():
app.include_router(file_router)
app.include_router(stream_router)
app.include_router(user_router)
app.include_router(setting_router)
logger.info("Server started")

app.add_middleware(
Expand Down
14 changes: 9 additions & 5 deletions backend/src/routers/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
from pydantic import BaseModel


class FilePathRequest(BaseModel):
file_path: str


class AlbumResponse(BaseModel):
id: Optional[int] = None
created_at: Optional[datetime] = None
Expand Down Expand Up @@ -196,21 +200,21 @@ async def get_file(


@file_router.post("/parse_file")
async def parse_one_file(file_path: str):
async def parse_one_file(request: FilePathRequest):
"""解析1個檔案"""
try:
data = sync_one_file(Path(file_path))
data = sync_one_file(Path(request.file_path))
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
print(data)
return data


@file_router.post("/scanall")
async def scan_all_files(dir_path: Optional[str] = None):
async def scan_all_files(request: FilePathRequest):
"""掃描所有檔案"""
if dir_path:
sync_dir_file(Path(dir_path))
if Path(request.file_path):
sync_dir_file(Path(request.file_path))
else:
for dir in load_setting().storages:
sync_dir_file(dir.path)
Expand Down
35 changes: 35 additions & 0 deletions backend/src/routers/setting.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from typing import Annotated
from fastapi import APIRouter, Depends
from sqlmodel import Session

from db import get_db
import os


setting_router = APIRouter(prefix="/setting", tags=["setting"])

SessionDep = Annotated[Session, Depends(get_db)]


@setting_router.get("/dir")
async def get_system_dir(path: str = "/") -> dict:
try:
items = os.listdir(path)
files = []
dirs = []

for item in items:
full_path = os.path.join(path, item)
if os.path.isfile(full_path):
files.append(item)
elif os.path.isdir(full_path):
dirs.append(item)

except NotADirectoryError:
return {"error": "該路徑不是目錄"}
except FileNotFoundError:
return {"error": "找不到路徑"}
except PermissionError:
return {"error": "沒有權限訪問該路徑"}

return {"files": files, "dirs": dirs, "path": path}
29 changes: 29 additions & 0 deletions docker-compose-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,37 @@ services:
networks:
- lithium-network

backend:
build:
context: ./backend
container_name: lithium-backend
volumes:
- backend:/app/data
ports:
- "8000:8000"
environment:
SQLIP: postgres
networks:
- lithium-network
depends_on:
- postgres

frontend:
build:
context: ./frontend/web
container_name: lithium-frontend
volumes:
- ./frontend:/app
ports:
- "3000:3000"
networks:
- lithium-network
depends_on:
- backend

volumes:
postgres_data:
backend:

networks:
lithium-network:
Expand Down
6 changes: 2 additions & 4 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ services:
- lithium-network

backend:
build:
context: ./backend
image: phillychi3/lithium-player-backend:latest
container_name: lithium-backend
volumes:
- backend:/app/data
Expand All @@ -29,8 +28,7 @@ services:
- postgres

frontend:
build:
context: ./frontend/web
image: phillychi3/lithium-player-frontend:latest
container_name: lithium-frontend
volumes:
- ./frontend:/app
Expand Down
2 changes: 1 addition & 1 deletion frontend/web/src/routes/app/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
<div class="p-4">
<h3 class="truncate text-lg font-bold">{album.title}</h3>
<p class="truncate text-sm opacity-75">{album.artist}</p>
<p class="mt-1 text-xs opacity-60">{album.tracks?.length || 0} 首歌曲</p>
<p class="mt-1 text-xs opacity-60">{album.total_tracks || 0} 首歌曲</p>
</div>
</div>
{/each}
Expand Down
Loading

0 comments on commit a44be46

Please sign in to comment.