# -*- coding: UTF-8 -*-
import json
import os
import platform

from flask import Flask, request
from threading import Thread

app = Flask(__name__)


def single_dl(url, options):
    command = f'yt-dlp {options} {url}'
    os.system(command)


def batch_dl(urls, options):
    for url in urls:
        print('[Start download] Video url: %s' % url.strip())
        single_dl(url, options)


@app.route('/ping')
def ping():
    return 'ytb-dl'


@app.route('/download', methods=['post'])
def download():
    try:
        data = request.get_json()
        options = '-f best --output "/usr/local/download/%(id)s.%(ext)s"'
        if 'options' in data:
            options = data['options']
        if 'urls' in data:
            video_urls = data['urls']
            if len(video_urls) > 0:
                dl_thread = Thread(target=batch_dl, args=(video_urls, options))
                dl_thread.start()
                return json.dumps({
                    'code': 200,
                    'message': f'开始下载 {len(video_urls)} 个视频'
                }, ensure_ascii=False)
        return json.dumps({
            'code': 300,
            'message': '未下载视频'
        }, ensure_ascii=False)
    except Exception as e:
        return json.dumps({
            'code': 500,
            'message': repr(e)
        }, ensure_ascii=False)


if __name__ == '__main__':
    output_path = '/usr/local/download/'
    v_options = '-f best '
    if str.upper(platform.system()) == 'WINDOWS':
        output_path = 'E:/youtube-dl/'
    if not os.path.exists(output_path):
        os.makedirs(output_path)

    app.run(host='0.0.0.0', port=5000)
