74 lines
2.2 KiB
Python
74 lines
2.2 KiB
Python
import shutil
|
|
|
|
from ucast.models import Channel, Video
|
|
from ucast.service import storage, util, videoutil, youtube
|
|
|
|
|
|
class ChannelAlreadyExistsException(Exception):
|
|
def __init__(self, *args: object) -> None:
|
|
super().__init__("channel already exists", *args)
|
|
|
|
|
|
def download_channel_avatar(channel: Channel):
|
|
store = storage.Storage()
|
|
channel_folder = store.get_or_create_channel_folder(channel.slug)
|
|
util.download_image_file(
|
|
channel.avatar_url, channel_folder.file_avatar, videoutil.AVATAR_SIZE
|
|
)
|
|
videoutil.resize_avatar(channel_folder.file_avatar, channel_folder.file_avatar_sm)
|
|
|
|
|
|
def create_channel(channel_str: str) -> Channel:
|
|
if youtube.CHANID_REGEX.match(channel_str):
|
|
if Channel.objects.filter(channel_id=channel_str).exists():
|
|
raise ChannelAlreadyExistsException()
|
|
|
|
channel_url = youtube.channel_url_from_str(channel_str)
|
|
channel_data = youtube.get_channel_metadata(channel_url)
|
|
|
|
if Channel.objects.filter(channel_id=channel_data.id).exists():
|
|
raise ChannelAlreadyExistsException()
|
|
|
|
channel_slug = Channel.get_new_slug(channel_data.name)
|
|
|
|
channel = Channel(
|
|
channel_id=channel_data.id,
|
|
name=channel_data.name,
|
|
slug=channel_slug,
|
|
description=channel_data.description,
|
|
subscribers=channel_data.subscribers,
|
|
avatar_url=channel_data.avatar_url,
|
|
)
|
|
|
|
download_channel_avatar(channel)
|
|
|
|
channel.save()
|
|
return channel
|
|
|
|
|
|
def delete_video(id: int):
|
|
video = Video.objects.get(id=id)
|
|
|
|
store = storage.Storage()
|
|
channel_folder = store.get_channel_folder(video.channel.slug)
|
|
|
|
util.remove_if_exists(channel_folder.get_audio(video.slug))
|
|
util.remove_if_exists(channel_folder.get_cover(video.slug))
|
|
util.remove_if_exists(channel_folder.get_thumbnail(video.slug))
|
|
util.remove_if_exists(channel_folder.get_thumbnail(video.slug, True))
|
|
|
|
video.is_deleted = True
|
|
video.downloaded = None
|
|
video.download_size = None
|
|
video.save()
|
|
|
|
|
|
def delete_channel(id: int):
|
|
channel = Channel.objects.get(id=id)
|
|
|
|
store = storage.Storage()
|
|
channel_folder = store.get_channel_folder(channel.slug)
|
|
|
|
shutil.rmtree(channel_folder.dir_root)
|
|
|
|
channel.delete()
|