53 lines
1.8 KiB
Python
53 lines
1.8 KiB
Python
import re
|
|
from urllib.parse import urlparse
|
|
|
|
from flask import Blueprint, jsonify, request
|
|
from yt_dlp import YoutubeDL
|
|
|
|
from server.helpers.regex import url_regex
|
|
from .video_list import VideoList
|
|
from ..database import db
|
|
from ...mysql import query
|
|
from ...process.ytlogging import YtdlLogger
|
|
|
|
list_route = Blueprint('lists', __name__)
|
|
|
|
|
|
@list_route.route('/add', methods=['POST'])
|
|
def add_list():
|
|
data = request.get_json(silent=True)
|
|
if not isinstance(data, dict) or not data:
|
|
return jsonify({'error': 'Data should be a key-value mapping.'}), 400
|
|
|
|
url = data.get('url')
|
|
|
|
# Check if it's a valid URL
|
|
if not url or not urlparse(url).scheme or not re.match(url_regex, url):
|
|
return jsonify({'error': 'Invalid URL'}), 400
|
|
|
|
# Check if it's a YouTube URL
|
|
if 'youtube.com' not in url:
|
|
return jsonify({'error': 'URL is not a YouTube URL'}), 400
|
|
|
|
# Check if the list is already in the database
|
|
existing_list = VideoList.query.filter_by(url=url).first()
|
|
if existing_list:
|
|
return jsonify({'added': False, 'message': 'List already in database', 'name': existing_list.name, 'url': existing_list.url, 'id': existing_list.id}), 200
|
|
|
|
# Use yt-dlp to get the playlist name
|
|
with YoutubeDL({'extract_flat': 'in_playlist', 'logger': YtdlLogger('logs')}) as ydl:
|
|
info_dict = ydl.extract_info(url, download=False)
|
|
playlist_name = info_dict.get('title', None)
|
|
|
|
if not playlist_name:
|
|
return jsonify({'error': 'Could not get playlist name'}), 400
|
|
|
|
# Add the list to the database
|
|
new_list = VideoList(name=playlist_name, url=url)
|
|
db.session.add(new_list)
|
|
db.session.commit()
|
|
|
|
list_id = query(f'SELECT * FROM `video_lists` WHERE `url`=%s', (url,))
|
|
|
|
return jsonify({'added': True, 'message': 'List added to database', 'name': playlist_name, 'url': url, 'id': list_id}), 201
|