Skip to content

Commit

Permalink
feat: check path and directory existence
Browse files Browse the repository at this point in the history
Exquisitely implemention :)

Signed-off-by: jingfelix <[email protected]>
  • Loading branch information
jingfelix committed Mar 23, 2024
1 parent 41da1eb commit 63d695f
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 12 deletions.
21 changes: 9 additions & 12 deletions src/bilifm/command.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
import os

import typer
from typing_extensions import Annotated

from .audio import Audio
from .fav import Fav
from .season import Season
from .user import User
from .util import Directory, Path

app = typer.Typer()


@app.command()
def bv(bv: str):
def bv(bv: str, directory: Directory = None):
audio = Audio(bv)
audio.download()


@app.command()
def uid(uid: str):
def uid(uid: str, directory: Directory = None):
user = User(uid)

for video in user.videos:
Expand All @@ -30,7 +30,11 @@ def uid(uid: str):


@app.command()
def fav(media_id: str, cookies_path: str):
def fav(
media_id: str,
cookies_path: str = Path,
directory: Directory = None,
):
with open(cookies_path, "r") as f:
cookies = f.read()

Expand All @@ -44,20 +48,13 @@ def fav(media_id: str, cookies_path: str):


@app.command()
def season(
uid: str,
sid: str,
directory: Annotated[str, typer.Option("-o", "--directory")] = "",
):
def season(uid: str, sid: str, directory: Directory = None):
sea = Season(uid, sid)
ret = sea.get_videos()
if not ret:
typer.Exit(1)
return

if directory:
os.chdir(directory)

if not os.path.isdir(sea.name):
os.makedirs(sea.name)
os.chdir(sea.name)
Expand Down
24 changes: 24 additions & 0 deletions src/bilifm/util.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import os
import random
import time
import urllib.parse
from functools import reduce
from hashlib import md5

import requests
import typer
from typing_extensions import Annotated

HEADERS = {
"authority": "api.bilibili.com",
Expand Down Expand Up @@ -168,3 +171,24 @@ def request(
params = get_signed_params(params)

return requests.request(method, url, params=params, headers=headers, **kwargs)


def change_directory(directory: str):
if directory:
if not os.path.exists(directory):
os.makedirs(directory)

if not os.path.isdir(directory):
raise typer.BadParameter(f"{directory} is not a directory")

os.chdir(directory)


def check_path(path: str):
if not os.path.exists(path):
raise typer.BadParameter(f"{path} does not exist")
return path


Directory = Annotated[str, typer.Option("-o", "--directory", callback=change_directory)]
Path = typer.Argument(callback=check_path)

0 comments on commit 63d695f

Please sign in to comment.