reformatting
This commit is contained in:
104
logic.py
104
logic.py
@@ -18,61 +18,61 @@ from .model import ModelSetting
|
|||||||
#########################################################
|
#########################################################
|
||||||
|
|
||||||
class Logic(object):
|
class Logic(object):
|
||||||
db_default = {
|
db_default = {
|
||||||
'db_version': '1',
|
'db_version': '1',
|
||||||
'temp_path': os.path.join(path_data, 'download_tmp'),
|
'temp_path': os.path.join(path_data, 'download_tmp'),
|
||||||
'save_path': os.path.join(path_data, 'download'),
|
'save_path': os.path.join(path_data, 'download'),
|
||||||
'default_filename': '%(title)s-%(id)s.%(ext)s',
|
'default_filename': '%(title)s-%(id)s.%(ext)s',
|
||||||
'proxy': '',
|
'proxy': '',
|
||||||
'activate_cors': False
|
'activate_cors': False
|
||||||
}
|
}
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def db_init():
|
def db_init():
|
||||||
try:
|
try:
|
||||||
for key, value in Logic.db_default.items():
|
for key, value in Logic.db_default.items():
|
||||||
if db.session.query(ModelSetting).filter_by(key=key).count() == 0:
|
if db.session.query(ModelSetting).filter_by(key=key).count() == 0:
|
||||||
db.session.add(ModelSetting(key, value))
|
db.session.add(ModelSetting(key, value))
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
# Logic.migration()
|
# Logic.migration()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error('Exception:%s', e)
|
logger.error('Exception:%s', e)
|
||||||
logger.error(traceback.format_exc())
|
logger.error(traceback.format_exc())
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def plugin_load():
|
def plugin_load():
|
||||||
try:
|
try:
|
||||||
logger.debug('%s plugin_load', package_name)
|
logger.debug('%s plugin_load', package_name)
|
||||||
Logic.db_init() # DB 초기화
|
Logic.db_init()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import glob2
|
import glob2
|
||||||
except ImportError:
|
except ImportError:
|
||||||
# glob2 설치
|
# glob2 설치
|
||||||
logger.debug('glob2 install')
|
logger.debug('glob2 install')
|
||||||
logger.debug(subprocess.check_output([sys.executable, '-m', 'pip', 'install', 'glob2'], universal_newlines=True))
|
logger.debug(subprocess.check_output([sys.executable, '-m', 'pip', 'install', 'glob2'], universal_newlines=True))
|
||||||
try:
|
try:
|
||||||
import flask_cors
|
import flask_cors
|
||||||
except ImportError:
|
except ImportError:
|
||||||
# flask-cors 설치
|
# flask-cors 설치
|
||||||
logger.debug('flask-cors install')
|
logger.debug('flask-cors install')
|
||||||
logger.debug(subprocess.check_output([sys.executable, '-m', 'pip', 'install', 'flask-cors'], universal_newlines=True))
|
logger.debug(subprocess.check_output([sys.executable, '-m', 'pip', 'install', 'flask-cors'], universal_newlines=True))
|
||||||
|
|
||||||
# youtube-dl 업데이트
|
# youtube-dl 업데이트
|
||||||
logger.debug('youtube-dl upgrade')
|
logger.debug('youtube-dl upgrade')
|
||||||
logger.debug(subprocess.check_output([sys.executable, '-m', 'pip', 'install', '--upgrade', 'youtube-dl'], universal_newlines=True))
|
logger.debug(subprocess.check_output([sys.executable, '-m', 'pip', 'install', '--upgrade', 'youtube-dl'], universal_newlines=True))
|
||||||
|
|
||||||
# 편의를 위해 json 파일 생성
|
# 편의를 위해 json 파일 생성
|
||||||
from plugin import plugin_info
|
from plugin import plugin_info
|
||||||
Util.save_from_dict_to_json(plugin_info, os.path.join(os.path.dirname(__file__), 'info.json'))
|
Util.save_from_dict_to_json(plugin_info, os.path.join(os.path.dirname(__file__), 'info.json'))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error('Exception:%s', e)
|
logger.error('Exception:%s', e)
|
||||||
logger.error(traceback.format_exc())
|
logger.error(traceback.format_exc())
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def plugin_unload():
|
def plugin_unload():
|
||||||
try:
|
try:
|
||||||
logger.debug('%s plugin_unload', package_name)
|
logger.debug('%s plugin_unload', package_name)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error('Exception:%s', e)
|
logger.error('Exception:%s', e)
|
||||||
logger.error(traceback.format_exc())
|
logger.error(traceback.format_exc())
|
||||||
|
|||||||
200
logic_normal.py
200
logic_normal.py
@@ -13,109 +13,109 @@ from .my_youtube_dl import Status
|
|||||||
#########################################################
|
#########################################################
|
||||||
|
|
||||||
class LogicNormal(object):
|
class LogicNormal(object):
|
||||||
youtube_dl_list = []
|
youtube_dl_list = []
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_preset_list():
|
def get_preset_list():
|
||||||
preset_list = [
|
preset_list = [
|
||||||
['bestvideo+bestaudio/best', '최고 화질'],
|
['bestvideo+bestaudio/best', '최고 화질'],
|
||||||
['bestvideo[height<=1080]+bestaudio/best[height<=1080]', '1080p'],
|
['bestvideo[height<=1080]+bestaudio/best[height<=1080]', '1080p'],
|
||||||
['worstvideo+worstaudio/worst', '최저 화질'],
|
['worstvideo+worstaudio/worst', '최저 화질'],
|
||||||
['bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]', '최고 화질(mp4)'],
|
['bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]', '최고 화질(mp4)'],
|
||||||
['bestvideo[ext=mp4][height<=1080]+bestaudio[ext=m4a]/best[ext=mp4][height<=1080]', '1080p(mp4)'],
|
['bestvideo[ext=mp4][height<=1080]+bestaudio[ext=m4a]/best[ext=mp4][height<=1080]', '1080p(mp4)'],
|
||||||
['bestvideo[filesize<50M]+bestaudio/best[filesize<50M]', '50MB 미만'],
|
['bestvideo[filesize<50M]+bestaudio/best[filesize<50M]', '50MB 미만'],
|
||||||
['bestaudio/best', '오디오만'],
|
['bestaudio/best', '오디오만'],
|
||||||
['_custom', '사용자 정의']
|
['_custom', '사용자 정의']
|
||||||
]
|
]
|
||||||
return preset_list
|
return preset_list
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_postprocessor_list():
|
def get_postprocessor_list():
|
||||||
postprocessor_list = [
|
postprocessor_list = [
|
||||||
['', '후처리 안함', None],
|
['', '후처리 안함', None],
|
||||||
['mp4', 'MP4', '비디오 변환'],
|
['mp4', 'MP4', '비디오 변환'],
|
||||||
['flv', 'FLV', '비디오 변환'],
|
['flv', 'FLV', '비디오 변환'],
|
||||||
['webm', 'WebM', '비디오 변환'],
|
['webm', 'WebM', '비디오 변환'],
|
||||||
['ogg', 'Ogg', '비디오 변환'],
|
['ogg', 'Ogg', '비디오 변환'],
|
||||||
['mkv', 'MKV', '비디오 변환'],
|
['mkv', 'MKV', '비디오 변환'],
|
||||||
['ts', 'TS', '비디오 변환'],
|
['ts', 'TS', '비디오 변환'],
|
||||||
['avi', 'AVI', '비디오 변환'],
|
['avi', 'AVI', '비디오 변환'],
|
||||||
['wmv', 'WMV', '비디오 변환'],
|
['wmv', 'WMV', '비디오 변환'],
|
||||||
['mov', 'MOV', '비디오 변환'],
|
['mov', 'MOV', '비디오 변환'],
|
||||||
['gif', 'GIF', '비디오 변환'],
|
['gif', 'GIF', '비디오 변환'],
|
||||||
['mp3', 'MP3', '오디오 추출'],
|
['mp3', 'MP3', '오디오 추출'],
|
||||||
['aac', 'AAC', '오디오 추출'],
|
['aac', 'AAC', '오디오 추출'],
|
||||||
['flac', 'FLAC', '오디오 추출'],
|
['flac', 'FLAC', '오디오 추출'],
|
||||||
['m4a', 'M4A', '오디오 추출'],
|
['m4a', 'M4A', '오디오 추출'],
|
||||||
['opus', 'Opus', '오디오 추출'],
|
['opus', 'Opus', '오디오 추출'],
|
||||||
['vorbis', 'Vorbis', '오디오 추출'],
|
['vorbis', 'Vorbis', '오디오 추출'],
|
||||||
['wav', 'WAV', '오디오 추출']
|
['wav', 'WAV', '오디오 추출']
|
||||||
]
|
]
|
||||||
return postprocessor_list
|
return postprocessor_list
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_postprocessor():
|
def get_postprocessor():
|
||||||
video_convertor = []
|
video_convertor = []
|
||||||
extract_audio = []
|
extract_audio = []
|
||||||
for i in LogicNormal.get_postprocessor_list():
|
for i in LogicNormal.get_postprocessor_list():
|
||||||
if i[2] == '비디오 변환':
|
if i[2] == '비디오 변환':
|
||||||
video_convertor.append(i[0])
|
video_convertor.append(i[0])
|
||||||
elif i[2] == '오디오 추출':
|
elif i[2] == '오디오 추출':
|
||||||
extract_audio.append(i[0])
|
extract_audio.append(i[0])
|
||||||
return video_convertor, extract_audio
|
return video_convertor, extract_audio
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_data(youtube_dl):
|
def get_data(youtube_dl):
|
||||||
try:
|
try:
|
||||||
data = {}
|
data = {}
|
||||||
data['plugin'] = youtube_dl.plugin
|
data['plugin'] = youtube_dl.plugin
|
||||||
data['url'] = youtube_dl.url
|
data['url'] = youtube_dl.url
|
||||||
data['filename'] = youtube_dl.filename
|
data['filename'] = youtube_dl.filename
|
||||||
data['temp_path'] = youtube_dl.temp_path
|
data['temp_path'] = youtube_dl.temp_path
|
||||||
data['save_path'] = youtube_dl.save_path
|
data['save_path'] = youtube_dl.save_path
|
||||||
data['index'] = youtube_dl.index
|
data['index'] = youtube_dl.index
|
||||||
data['status_str'] = youtube_dl.status.name
|
data['status_str'] = youtube_dl.status.name
|
||||||
data['status_ko'] = str(youtube_dl.status)
|
data['status_ko'] = str(youtube_dl.status)
|
||||||
data['end_time'] = ''
|
data['end_time'] = ''
|
||||||
data['extractor'] = youtube_dl.info_dict['extractor'] if youtube_dl.info_dict['extractor'] is not None else ''
|
data['extractor'] = youtube_dl.info_dict['extractor'] if youtube_dl.info_dict['extractor'] is not None else ''
|
||||||
data['title'] = youtube_dl.info_dict['title'] if youtube_dl.info_dict['title'] is not None else youtube_dl.url
|
data['title'] = youtube_dl.info_dict['title'] if youtube_dl.info_dict['title'] is not None else youtube_dl.url
|
||||||
data['uploader'] = youtube_dl.info_dict['uploader'] if youtube_dl.info_dict['uploader'] is not None else ''
|
data['uploader'] = youtube_dl.info_dict['uploader'] if youtube_dl.info_dict['uploader'] is not None else ''
|
||||||
data['uploader_url'] = youtube_dl.info_dict['uploader_url'] if youtube_dl.info_dict['uploader_url'] is not None else ''
|
data['uploader_url'] = youtube_dl.info_dict['uploader_url'] if youtube_dl.info_dict['uploader_url'] is not None else ''
|
||||||
data['downloaded_bytes_str'] = ''
|
data['downloaded_bytes_str'] = ''
|
||||||
data['total_bytes_str'] = ''
|
data['total_bytes_str'] = ''
|
||||||
data['percent'] = '0'
|
data['percent'] = '0'
|
||||||
data['eta'] = youtube_dl.progress_hooks['eta'] if youtube_dl.progress_hooks['eta'] is not None else ''
|
data['eta'] = youtube_dl.progress_hooks['eta'] if youtube_dl.progress_hooks['eta'] is not None else ''
|
||||||
data['speed_str'] = LogicNormal.human_readable_size(youtube_dl.progress_hooks['speed'], '/s') if youtube_dl.progress_hooks['speed'] is not None else ''
|
data['speed_str'] = LogicNormal.human_readable_size(youtube_dl.progress_hooks['speed'], '/s') if youtube_dl.progress_hooks['speed'] is not None else ''
|
||||||
if youtube_dl.status == Status.READY: # 다운로드 전
|
if youtube_dl.status == Status.READY: # 다운로드 전
|
||||||
data['start_time'] = ''
|
data['start_time'] = ''
|
||||||
data['download_time'] = ''
|
data['download_time'] = ''
|
||||||
else:
|
else:
|
||||||
if youtube_dl.end_time is None: # 완료 전
|
if youtube_dl.end_time is None: # 완료 전
|
||||||
download_time = datetime.now() - youtube_dl.start_time
|
download_time = datetime.now() - youtube_dl.start_time
|
||||||
else:
|
else:
|
||||||
download_time = youtube_dl.end_time - youtube_dl.start_time
|
download_time = youtube_dl.end_time - youtube_dl.start_time
|
||||||
data['end_time'] = youtube_dl.end_time.strftime('%m-%d %H:%M:%S')
|
data['end_time'] = youtube_dl.end_time.strftime('%m-%d %H:%M:%S')
|
||||||
if None not in (youtube_dl.progress_hooks['downloaded_bytes'], youtube_dl.progress_hooks['total_bytes']): # 둘 다 값이 있으면
|
if None not in (youtube_dl.progress_hooks['downloaded_bytes'], youtube_dl.progress_hooks['total_bytes']): # 둘 다 값이 있으면
|
||||||
data['downloaded_bytes_str'] = LogicNormal.human_readable_size(youtube_dl.progress_hooks['downloaded_bytes'])
|
data['downloaded_bytes_str'] = LogicNormal.human_readable_size(youtube_dl.progress_hooks['downloaded_bytes'])
|
||||||
data['total_bytes_str'] = LogicNormal.human_readable_size(youtube_dl.progress_hooks['total_bytes'])
|
data['total_bytes_str'] = LogicNormal.human_readable_size(youtube_dl.progress_hooks['total_bytes'])
|
||||||
data['percent'] = '%.2f' % (float(youtube_dl.progress_hooks['downloaded_bytes']) / float(youtube_dl.progress_hooks['total_bytes']) * 100)
|
data['percent'] = '%.2f' % (float(youtube_dl.progress_hooks['downloaded_bytes']) / float(youtube_dl.progress_hooks['total_bytes']) * 100)
|
||||||
data['start_time'] = youtube_dl.start_time.strftime('%m-%d %H:%M:%S')
|
data['start_time'] = youtube_dl.start_time.strftime('%m-%d %H:%M:%S')
|
||||||
data['download_time'] = '%02d:%02d' % (download_time.seconds / 60, download_time.seconds % 60)
|
data['download_time'] = '%02d:%02d' % (download_time.seconds / 60, download_time.seconds % 60)
|
||||||
return data
|
return data
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error('Exception:%s', e)
|
logger.error('Exception:%s', e)
|
||||||
logger.error(traceback.format_exc())
|
logger.error(traceback.format_exc())
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def human_readable_size(size, suffix=''):
|
def human_readable_size(size, suffix=''):
|
||||||
for unit in ('Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB'):
|
for unit in ('Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB'):
|
||||||
if size < 1024.0:
|
if size < 1024.0:
|
||||||
return '%3.1f %s%s' % (size, unit, suffix)
|
return '%3.1f %s%s' % (size, unit, suffix)
|
||||||
size /= 1024.0
|
size /= 1024.0
|
||||||
return '%.1f %s%s' % (size, 'YB', suffix)
|
return '%.1f %s%s' % (size, 'YB', suffix)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def abort(base, code):
|
def abort(base, code):
|
||||||
base['errorCode'] = code
|
base['errorCode'] = code
|
||||||
return jsonify(base)
|
return jsonify(base)
|
||||||
|
|||||||
162
model.py
162
model.py
@@ -17,95 +17,95 @@ app.config['SQLALCHEMY_BINDS'][package_name] = 'sqlite:///%s' % (os.path.join(pa
|
|||||||
#########################################################
|
#########################################################
|
||||||
|
|
||||||
class ModelSetting(db.Model):
|
class ModelSetting(db.Model):
|
||||||
__tablename__ = '%s_setting' % package_name
|
__tablename__ = '%s_setting' % package_name
|
||||||
__table_args__ = {'mysql_collate': 'utf8_general_ci'}
|
__table_args__ = {'mysql_collate': 'utf8_general_ci'}
|
||||||
__bind_key__ = package_name
|
__bind_key__ = package_name
|
||||||
|
|
||||||
id = db.Column(db.Integer, primary_key=True)
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
key = db.Column(db.String(100), unique=True, nullable=False)
|
key = db.Column(db.String(100), unique=True, nullable=False)
|
||||||
value = db.Column(db.String, nullable=False)
|
value = db.Column(db.String, nullable=False)
|
||||||
|
|
||||||
def __init__(self, key, value):
|
def __init__(self, key, value):
|
||||||
self.key = key
|
self.key = key
|
||||||
self.value = value
|
self.value = value
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return repr(self.as_dict())
|
return repr(self.as_dict())
|
||||||
|
|
||||||
def as_dict(self):
|
def as_dict(self):
|
||||||
return {x.name: getattr(self, x.name) for x in self.__table__.columns}
|
return {x.name: getattr(self, x.name) for x in self.__table__.columns}
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get(key):
|
def get(key):
|
||||||
try:
|
try:
|
||||||
return db.session.query(ModelSetting).filter_by(key=key).first().value.strip()
|
return db.session.query(ModelSetting).filter_by(key=key).first().value.strip()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error('Exception:%s %s', e, key)
|
logger.error('Exception:%s %s', e, key)
|
||||||
logger.error(traceback.format_exc())
|
logger.error(traceback.format_exc())
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_int(key):
|
def get_int(key):
|
||||||
try:
|
try:
|
||||||
return int(ModelSetting.get(key))
|
return int(ModelSetting.get(key))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error('Exception:%s %s', e, key)
|
logger.error('Exception:%s %s', e, key)
|
||||||
logger.error(traceback.format_exc())
|
logger.error(traceback.format_exc())
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_bool(key):
|
def get_bool(key):
|
||||||
try:
|
try:
|
||||||
return ModelSetting.get(key) == 'True'
|
return ModelSetting.get(key) == 'True'
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error('Exception:%s %s', e, key)
|
logger.error('Exception:%s %s', e, key)
|
||||||
logger.error(traceback.format_exc())
|
logger.error(traceback.format_exc())
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def set(key, value):
|
def set(key, value):
|
||||||
try:
|
try:
|
||||||
item = db.session.query(ModelSetting).filter_by(key=key).with_for_update().first()
|
item = db.session.query(ModelSetting).filter_by(key=key).with_for_update().first()
|
||||||
if item is not None:
|
if item is not None:
|
||||||
item.value = value.strip()
|
item.value = value.strip()
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
else:
|
else:
|
||||||
db.session.add(ModelSetting(key, value.strip()))
|
db.session.add(ModelSetting(key, value.strip()))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error('Exception:%s', e)
|
logger.error('Exception:%s', e)
|
||||||
logger.error(traceback.format_exc())
|
logger.error(traceback.format_exc())
|
||||||
logger.error('Error Key:%s Value:%s', key, value)
|
logger.error('Error Key:%s Value:%s', key, value)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def to_dict():
|
def to_dict():
|
||||||
try:
|
try:
|
||||||
return Util.db_list_to_dict(db.session.query(ModelSetting).all())
|
return Util.db_list_to_dict(db.session.query(ModelSetting).all())
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error('Exception:%s', e)
|
logger.error('Exception:%s', e)
|
||||||
logger.error(traceback.format_exc())
|
logger.error(traceback.format_exc())
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def setting_save(req):
|
def setting_save(req):
|
||||||
try:
|
try:
|
||||||
for key, value in req.form.items():
|
for key, value in req.form.items():
|
||||||
if key in ['scheduler', 'is_running']:
|
if key in ['scheduler', 'is_running']:
|
||||||
continue
|
continue
|
||||||
if key.startswith('tmp_'):
|
if key.startswith('tmp_'):
|
||||||
continue
|
continue
|
||||||
logger.debug('Key:%s Value:%s', key, value)
|
logger.debug('Key:%s Value:%s', key, value)
|
||||||
entity = db.session.query(ModelSetting).filter_by(key=key).with_for_update().first()
|
entity = db.session.query(ModelSetting).filter_by(key=key).with_for_update().first()
|
||||||
entity.value = value
|
entity.value = value
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return True
|
return True
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error('Exception:%s', e)
|
logger.error('Exception:%s', e)
|
||||||
logger.error(traceback.format_exc())
|
logger.error(traceback.format_exc())
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_list(key):
|
def get_list(key):
|
||||||
try:
|
try:
|
||||||
value = ModelSetting.get(key)
|
value = ModelSetting.get(key)
|
||||||
values = [x.strip().strip() for x in value.replace('\n', '|').split('|')]
|
values = [x.strip().strip() for x in value.replace('\n', '|').split('|')]
|
||||||
values = Util.get_list_except_empty(values)
|
values = Util.get_list_except_empty(values)
|
||||||
return values
|
return values
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error('Exception:%s %s', e, key)
|
logger.error('Exception:%s %s', e, key)
|
||||||
logger.error(traceback.format_exc())
|
logger.error(traceback.format_exc())
|
||||||
|
|||||||
344
my_youtube_dl.py
344
my_youtube_dl.py
@@ -18,194 +18,194 @@ from .plugin import logger
|
|||||||
|
|
||||||
|
|
||||||
class Status(Enum):
|
class Status(Enum):
|
||||||
READY = 0
|
READY = 0
|
||||||
START = 1
|
START = 1
|
||||||
DOWNLOADING = 2
|
DOWNLOADING = 2
|
||||||
ERROR = 3
|
ERROR = 3
|
||||||
FINISHED = 4
|
FINISHED = 4
|
||||||
STOP = 5
|
STOP = 5
|
||||||
COMPLETED = 6
|
COMPLETED = 6
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
str_list = [
|
str_list = [
|
||||||
'준비',
|
'준비',
|
||||||
'분석중',
|
'분석중',
|
||||||
'다운로드중',
|
'다운로드중',
|
||||||
'실패',
|
'실패',
|
||||||
'변환중',
|
'변환중',
|
||||||
'중지',
|
'중지',
|
||||||
'완료'
|
'완료'
|
||||||
]
|
]
|
||||||
return str_list[self.value]
|
return str_list[self.value]
|
||||||
|
|
||||||
|
|
||||||
class Youtube_dl(object):
|
class Youtube_dl(object):
|
||||||
_index = 0
|
_index = 0
|
||||||
_last_msg = ''
|
_last_msg = ''
|
||||||
|
|
||||||
def __init__(self, plugin, url, filename, temp_path, save_path=None, opts=None):
|
def __init__(self, plugin, url, filename, temp_path, save_path=None, opts=None):
|
||||||
if save_path is None:
|
if save_path is None:
|
||||||
save_path = temp_path
|
save_path = temp_path
|
||||||
if opts is None:
|
if opts is None:
|
||||||
opts = {}
|
opts = {}
|
||||||
self.plugin = plugin
|
self.plugin = plugin
|
||||||
self.url = url
|
self.url = url
|
||||||
self.filename = filename
|
self.filename = filename
|
||||||
if not os.path.isdir(temp_path):
|
if not os.path.isdir(temp_path):
|
||||||
os.makedirs(temp_path)
|
os.makedirs(temp_path)
|
||||||
self.temp_path = tempfile.mkdtemp(prefix='youtube-dl_', dir=temp_path)
|
self.temp_path = tempfile.mkdtemp(prefix='youtube-dl_', dir=temp_path)
|
||||||
if not os.path.isdir(save_path):
|
if not os.path.isdir(save_path):
|
||||||
os.makedirs(save_path)
|
os.makedirs(save_path)
|
||||||
self.save_path = save_path
|
self.save_path = save_path
|
||||||
self.opts = opts
|
self.opts = opts
|
||||||
self.index = Youtube_dl._index
|
self.index = Youtube_dl._index
|
||||||
Youtube_dl._index += 1
|
Youtube_dl._index += 1
|
||||||
self._status = Status.READY
|
self._status = Status.READY
|
||||||
self._thread = None
|
self._thread = None
|
||||||
self.key = None
|
self.key = None
|
||||||
self.start_time = None # 시작 시간
|
self.start_time = None # 시작 시간
|
||||||
self.end_time = None # 종료 시간
|
self.end_time = None # 종료 시간
|
||||||
self.info_dict = { # info_dict에서 얻는 정보
|
self.info_dict = { # info_dict에서 얻는 정보
|
||||||
'extractor': None, # 타입
|
'extractor': None, # 타입
|
||||||
'title': None, # 제목
|
'title': None, # 제목
|
||||||
'uploader': None, # 업로더
|
'uploader': None, # 업로더
|
||||||
'uploader_url': None # 업로더 주소
|
'uploader_url': None # 업로더 주소
|
||||||
}
|
}
|
||||||
# info_dict에서 얻는 정보(entries)
|
# info_dict에서 얻는 정보(entries)
|
||||||
# self.info_dict['playlist_index'] = None
|
# self.info_dict['playlist_index'] = None
|
||||||
# self.info_dict['duration'] = None # 길이
|
# self.info_dict['duration'] = None # 길이
|
||||||
# self.info_dict['format'] = None # 포맷
|
# self.info_dict['format'] = None # 포맷
|
||||||
# self.info_dict['thumbnail'] = None # 썸네일
|
# self.info_dict['thumbnail'] = None # 썸네일
|
||||||
self.progress_hooks = { # progress_hooks에서 얻는 정보
|
self.progress_hooks = { # progress_hooks에서 얻는 정보
|
||||||
'downloaded_bytes': None, # 다운로드한 크기
|
'downloaded_bytes': None, # 다운로드한 크기
|
||||||
'total_bytes': None, # 전체 크기
|
'total_bytes': None, # 전체 크기
|
||||||
'eta': None, # 예상 시간(s)
|
'eta': None, # 예상 시간(s)
|
||||||
'speed': None # 다운로드 속도(bytes/s)
|
'speed': None # 다운로드 속도(bytes/s)
|
||||||
}
|
}
|
||||||
|
|
||||||
def start(self):
|
def start(self):
|
||||||
if self.status != Status.READY:
|
if self.status != Status.READY:
|
||||||
return False
|
return False
|
||||||
self._thread = Thread(target=self.run)
|
self._thread = Thread(target=self.run)
|
||||||
self._thread.start()
|
self._thread.start()
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
import youtube_dl
|
import youtube_dl
|
||||||
import glob2
|
import glob2
|
||||||
try:
|
try:
|
||||||
self.start_time = datetime.now()
|
self.start_time = datetime.now()
|
||||||
self.status = Status.START
|
self.status = Status.START
|
||||||
info_dict = Youtube_dl.get_info_dict(self.url, self.opts.get('proxy')) # 동영상 정보 가져오기
|
info_dict = Youtube_dl.get_info_dict(self.url, self.opts.get('proxy')) # 동영상 정보 가져오기
|
||||||
if info_dict is None: # 가져오기 실패
|
if info_dict is None: # 가져오기 실패
|
||||||
self.status = Status.ERROR
|
self.status = Status.ERROR
|
||||||
return
|
return
|
||||||
self.info_dict['extractor'] = info_dict['extractor']
|
self.info_dict['extractor'] = info_dict['extractor']
|
||||||
self.info_dict['title'] = info_dict['title']
|
self.info_dict['title'] = info_dict['title']
|
||||||
self.info_dict['uploader'] = info_dict['uploader']
|
self.info_dict['uploader'] = info_dict['uploader']
|
||||||
self.info_dict['uploader_url'] = info_dict['uploader_url']
|
self.info_dict['uploader_url'] = info_dict['uploader_url']
|
||||||
ydl_opts = {
|
ydl_opts = {
|
||||||
'logger': MyLogger(),
|
'logger': MyLogger(),
|
||||||
'progress_hooks': [self.my_hook],
|
'progress_hooks': [self.my_hook],
|
||||||
# 'match_filter': self.match_filter_func,
|
# 'match_filter': self.match_filter_func,
|
||||||
'outtmpl': os.path.join(self.temp_path, self.filename),
|
'outtmpl': os.path.join(self.temp_path, self.filename),
|
||||||
'ignoreerrors': True,
|
'ignoreerrors': True,
|
||||||
'cachedir': False
|
'cachedir': False
|
||||||
}
|
}
|
||||||
ydl_opts.update(self.opts)
|
ydl_opts.update(self.opts)
|
||||||
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
|
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
|
||||||
ydl.download([self.url])
|
ydl.download([self.url])
|
||||||
if self.status == Status.FINISHED: # 다운로드 성공
|
if self.status == Status.FINISHED: # 다운로드 성공
|
||||||
for i in glob2.glob(self.temp_path + '/**/*'):
|
for i in glob2.glob(self.temp_path + '/**/*'):
|
||||||
path = i.replace(self.temp_path, self.save_path, 1)
|
path = i.replace(self.temp_path, self.save_path, 1)
|
||||||
if os.path.isdir(i):
|
if os.path.isdir(i):
|
||||||
if not os.path.isdir(path):
|
if not os.path.isdir(path):
|
||||||
os.mkdir(path)
|
os.mkdir(path)
|
||||||
continue
|
continue
|
||||||
celery_shutil.move(i, path) # 파일 이동
|
celery_shutil.move(i, path) # 파일 이동
|
||||||
self.status = Status.COMPLETED
|
self.status = Status.COMPLETED
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.status = Status.ERROR
|
self.status = Status.ERROR
|
||||||
logger.error('Exception:%s', e)
|
logger.error('Exception:%s', e)
|
||||||
logger.error(traceback.format_exc())
|
logger.error(traceback.format_exc())
|
||||||
finally:
|
finally:
|
||||||
celery_shutil.rmtree(self.temp_path) # 임시폴더 삭제
|
celery_shutil.rmtree(self.temp_path) # 임시폴더 삭제
|
||||||
if self.status != Status.STOP:
|
if self.status != Status.STOP:
|
||||||
self.end_time = datetime.now()
|
self.end_time = datetime.now()
|
||||||
|
|
||||||
def stop(self):
|
def stop(self):
|
||||||
if self.status in (Status.ERROR, Status.STOP, Status.COMPLETED):
|
if self.status in (Status.ERROR, Status.STOP, Status.COMPLETED):
|
||||||
return False
|
return False
|
||||||
self.status = Status.STOP
|
self.status = Status.STOP
|
||||||
self.end_time = datetime.now()
|
self.end_time = datetime.now()
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_version():
|
def get_version():
|
||||||
import youtube_dl
|
import youtube_dl
|
||||||
return youtube_dl.version.__version__
|
return youtube_dl.version.__version__
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_info_dict(url, proxy=None):
|
def get_info_dict(url, proxy=None):
|
||||||
import youtube_dl
|
import youtube_dl
|
||||||
try:
|
try:
|
||||||
ydl_opts = {
|
ydl_opts = {
|
||||||
'simulate': True,
|
'simulate': True,
|
||||||
'dump_single_json': True,
|
'dump_single_json': True,
|
||||||
'extract_flat': 'in_playlist',
|
'extract_flat': 'in_playlist',
|
||||||
'logger': MyLogger()
|
'logger': MyLogger()
|
||||||
}
|
}
|
||||||
if proxy:
|
if proxy:
|
||||||
ydl_opts['proxy'] = proxy
|
ydl_opts['proxy'] = proxy
|
||||||
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
|
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
|
||||||
ydl.download([url])
|
ydl.download([url])
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error('Exception:%s', e)
|
logger.error('Exception:%s', e)
|
||||||
logger.error(traceback.format_exc())
|
logger.error(traceback.format_exc())
|
||||||
return None
|
return None
|
||||||
return json.loads(Youtube_dl._last_msg)
|
return json.loads(Youtube_dl._last_msg)
|
||||||
|
|
||||||
def my_hook(self, d):
|
def my_hook(self, d):
|
||||||
if self.status != Status.STOP:
|
if self.status != Status.STOP:
|
||||||
self.status = {
|
self.status = {
|
||||||
'downloading': Status.DOWNLOADING,
|
'downloading': Status.DOWNLOADING,
|
||||||
'error': Status.ERROR,
|
'error': Status.ERROR,
|
||||||
'finished': Status.FINISHED # 다운로드 완료. 변환 시작
|
'finished': Status.FINISHED # 다운로드 완료. 변환 시작
|
||||||
}[d['status']]
|
}[d['status']]
|
||||||
if d['status'] != 'error':
|
if d['status'] != 'error':
|
||||||
self.filename = os.path.basename(d.get('filename'))
|
self.filename = os.path.basename(d.get('filename'))
|
||||||
self.progress_hooks['downloaded_bytes'] = d.get('downloaded_bytes')
|
self.progress_hooks['downloaded_bytes'] = d.get('downloaded_bytes')
|
||||||
self.progress_hooks['total_bytes'] = d.get('total_bytes')
|
self.progress_hooks['total_bytes'] = d.get('total_bytes')
|
||||||
self.progress_hooks['eta'] = d.get('eta')
|
self.progress_hooks['eta'] = d.get('eta')
|
||||||
self.progress_hooks['speed'] = d.get('speed')
|
self.progress_hooks['speed'] = d.get('speed')
|
||||||
|
|
||||||
def match_filter_func(self, info_dict):
|
def match_filter_func(self, info_dict):
|
||||||
self.info_dict['playlist_index'] = info_dict['playlist_index']
|
self.info_dict['playlist_index'] = info_dict['playlist_index']
|
||||||
self.info_dict['duration'] = info_dict['duration']
|
self.info_dict['duration'] = info_dict['duration']
|
||||||
self.info_dict['format'] = info_dict['format']
|
self.info_dict['format'] = info_dict['format']
|
||||||
self.info_dict['thumbnail'] = info_dict['thumbnail']
|
self.info_dict['thumbnail'] = info_dict['thumbnail']
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def status(self):
|
def status(self):
|
||||||
return self._status
|
return self._status
|
||||||
|
|
||||||
@status.setter
|
@status.setter
|
||||||
def status(self, value):
|
def status(self, value):
|
||||||
from .plugin import socketio_emit
|
from .plugin import socketio_emit
|
||||||
self._status = value
|
self._status = value
|
||||||
socketio_emit('status', self)
|
socketio_emit('status', self)
|
||||||
|
|
||||||
|
|
||||||
class MyLogger(object):
|
class MyLogger(object):
|
||||||
def debug(self, msg):
|
def debug(self, msg):
|
||||||
Youtube_dl._last_msg = msg
|
Youtube_dl._last_msg = msg
|
||||||
if msg.find('') != -1 or msg.find('{') != -1:
|
if msg.find('') != -1 or msg.find('{') != -1:
|
||||||
return # 과도한 로그 방지
|
return # 과도한 로그 방지
|
||||||
logger.debug(msg)
|
logger.debug(msg)
|
||||||
|
|
||||||
def warning(self, msg):
|
def warning(self, msg):
|
||||||
logger.warning(msg)
|
logger.warning(msg)
|
||||||
|
|
||||||
def error(self, msg):
|
def error(self, msg):
|
||||||
logger.error(msg)
|
logger.error(msg)
|
||||||
|
|||||||
466
plugin.py
466
plugin.py
@@ -26,65 +26,65 @@ from .my_youtube_dl import Youtube_dl
|
|||||||
blueprint = Blueprint(package_name, package_name, url_prefix='/%s' % package_name, template_folder=os.path.join(os.path.dirname(__file__), 'templates'))
|
blueprint = Blueprint(package_name, package_name, url_prefix='/%s' % package_name, template_folder=os.path.join(os.path.dirname(__file__), 'templates'))
|
||||||
|
|
||||||
menu = {
|
menu = {
|
||||||
'main': [package_name, 'youtube-dl'],
|
'main': [package_name, 'youtube-dl'],
|
||||||
'sub': [
|
'sub': [
|
||||||
['setting', '설정'], ['download', '다운로드'], ['list', '목록'], ['log', '로그']
|
['setting', '설정'], ['download', '다운로드'], ['list', '목록'], ['log', '로그']
|
||||||
],
|
],
|
||||||
'category': 'vod'
|
'category': 'vod'
|
||||||
}
|
}
|
||||||
|
|
||||||
plugin_info = {
|
plugin_info = {
|
||||||
'version': '1.6.3',
|
'version': '1.6.3',
|
||||||
'name': 'youtube-dl',
|
'name': 'youtube-dl',
|
||||||
'category_name': 'vod',
|
'category_name': 'vod',
|
||||||
'developer': 'joyfuI',
|
'developer': 'joyfuI',
|
||||||
'description': '유튜브, 네이버TV 등 동영상 사이트에서 동영상 다운로드',
|
'description': '유튜브, 네이버TV 등 동영상 사이트에서 동영상 다운로드',
|
||||||
'home': 'https://github.com/joyfuI/youtube-dl',
|
'home': 'https://github.com/joyfuI/youtube-dl',
|
||||||
'more': ''
|
'more': ''
|
||||||
}
|
}
|
||||||
|
|
||||||
def plugin_load():
|
def plugin_load():
|
||||||
Logic.plugin_load()
|
Logic.plugin_load()
|
||||||
if ModelSetting.get_bool('activate_cors'):
|
if ModelSetting.get_bool('activate_cors'):
|
||||||
import flask_cors
|
import flask_cors
|
||||||
flask_cors.CORS(blueprint)
|
flask_cors.CORS(blueprint)
|
||||||
|
|
||||||
def plugin_unload():
|
def plugin_unload():
|
||||||
Logic.plugin_unload()
|
Logic.plugin_unload()
|
||||||
|
|
||||||
#########################################################
|
#########################################################
|
||||||
# WEB Menu
|
# WEB Menu
|
||||||
#########################################################
|
#########################################################
|
||||||
@blueprint.route('/')
|
@blueprint.route('/')
|
||||||
def home():
|
def home():
|
||||||
return redirect('/%s/list' % package_name)
|
return redirect('/%s/list' % package_name)
|
||||||
|
|
||||||
@blueprint.route('/<sub>')
|
@blueprint.route('/<sub>')
|
||||||
@login_required
|
@login_required
|
||||||
def first_menu(sub):
|
def first_menu(sub):
|
||||||
try:
|
try:
|
||||||
arg = {'package_name': package_name}
|
arg = {'package_name': package_name}
|
||||||
|
|
||||||
if sub == 'setting':
|
if sub == 'setting':
|
||||||
arg.update(ModelSetting.to_dict())
|
arg.update(ModelSetting.to_dict())
|
||||||
arg['youtube_dl_version'] = Youtube_dl.get_version()
|
arg['youtube_dl_version'] = Youtube_dl.get_version()
|
||||||
return render_template('%s_%s.html' % (package_name, sub), arg=arg)
|
return render_template('%s_%s.html' % (package_name, sub), arg=arg)
|
||||||
|
|
||||||
elif sub == 'download':
|
elif sub == 'download':
|
||||||
arg['file_name'] = ModelSetting.get('default_filename')
|
arg['file_name'] = ModelSetting.get('default_filename')
|
||||||
arg['preset_list'] = LogicNormal.get_preset_list()
|
arg['preset_list'] = LogicNormal.get_preset_list()
|
||||||
arg['postprocessor_list'] = LogicNormal.get_postprocessor_list()
|
arg['postprocessor_list'] = LogicNormal.get_postprocessor_list()
|
||||||
return render_template('%s_%s.html' % (package_name, sub), arg=arg)
|
return render_template('%s_%s.html' % (package_name, sub), arg=arg)
|
||||||
|
|
||||||
elif sub == 'list':
|
elif sub == 'list':
|
||||||
return render_template('%s_%s.html' % (package_name, sub), arg=arg)
|
return render_template('%s_%s.html' % (package_name, sub), arg=arg)
|
||||||
|
|
||||||
elif sub == 'log':
|
elif sub == 'log':
|
||||||
return render_template('log.html', package=package_name)
|
return render_template('log.html', package=package_name)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error('Exception:%s', e)
|
logger.error('Exception:%s', e)
|
||||||
logger.error(traceback.format_exc())
|
logger.error(traceback.format_exc())
|
||||||
return render_template('sample.html', title='%s - %s' % (package_name, sub))
|
return render_template('sample.html', title='%s - %s' % (package_name, sub))
|
||||||
|
|
||||||
#########################################################
|
#########################################################
|
||||||
# For UI
|
# For UI
|
||||||
@@ -92,60 +92,60 @@ def first_menu(sub):
|
|||||||
@blueprint.route('/ajax/<sub>', methods=['POST'])
|
@blueprint.route('/ajax/<sub>', methods=['POST'])
|
||||||
@login_required
|
@login_required
|
||||||
def ajax(sub):
|
def ajax(sub):
|
||||||
logger.debug('AJAX %s %s', package_name, sub)
|
logger.debug('AJAX %s %s', package_name, sub)
|
||||||
try:
|
try:
|
||||||
# 공통 요청
|
# 공통 요청
|
||||||
if sub == 'setting_save':
|
if sub == 'setting_save':
|
||||||
ret = ModelSetting.setting_save(request)
|
ret = ModelSetting.setting_save(request)
|
||||||
return jsonify(ret)
|
return jsonify(ret)
|
||||||
|
|
||||||
# UI 요청
|
# UI 요청
|
||||||
elif sub == 'download':
|
elif sub == 'download':
|
||||||
url = request.form['url']
|
url = request.form['url']
|
||||||
filename = request.form['filename']
|
filename = request.form['filename']
|
||||||
temp_path = ModelSetting.get('temp_path')
|
temp_path = ModelSetting.get('temp_path')
|
||||||
save_path = ModelSetting.get('save_path')
|
save_path = ModelSetting.get('save_path')
|
||||||
format_code = request.form['format']
|
format_code = request.form['format']
|
||||||
postprocessor = request.form['postprocessor']
|
postprocessor = request.form['postprocessor']
|
||||||
proxy = ModelSetting.get('proxy')
|
proxy = ModelSetting.get('proxy')
|
||||||
opts = {}
|
opts = {}
|
||||||
if format_code:
|
if format_code:
|
||||||
opts['format'] = format_code
|
opts['format'] = format_code
|
||||||
video_convertor, extract_audio = LogicNormal.get_postprocessor()
|
video_convertor, extract_audio = LogicNormal.get_postprocessor()
|
||||||
if postprocessor in video_convertor:
|
if postprocessor in video_convertor:
|
||||||
opts['postprocessors'] = [{
|
opts['postprocessors'] = [{
|
||||||
'key': 'FFmpegVideoConvertor',
|
'key': 'FFmpegVideoConvertor',
|
||||||
'preferedformat': postprocessor
|
'preferedformat': postprocessor
|
||||||
}]
|
}]
|
||||||
elif postprocessor in extract_audio:
|
elif postprocessor in extract_audio:
|
||||||
opts['postprocessors'] = [{
|
opts['postprocessors'] = [{
|
||||||
'key': 'FFmpegExtractAudio',
|
'key': 'FFmpegExtractAudio',
|
||||||
'preferredcodec': postprocessor,
|
'preferredcodec': postprocessor,
|
||||||
'preferredquality': '192'
|
'preferredquality': '192'
|
||||||
}]
|
}]
|
||||||
if proxy:
|
if proxy:
|
||||||
opts['proxy'] = proxy
|
opts['proxy'] = proxy
|
||||||
youtube_dl = Youtube_dl(package_name, url, filename, temp_path, save_path, opts)
|
youtube_dl = Youtube_dl(package_name, url, filename, temp_path, save_path, opts)
|
||||||
LogicNormal.youtube_dl_list.append(youtube_dl) # 리스트 추가
|
LogicNormal.youtube_dl_list.append(youtube_dl) # 리스트 추가
|
||||||
youtube_dl.start()
|
youtube_dl.start()
|
||||||
socketio_emit('add', youtube_dl)
|
socketio_emit('add', youtube_dl)
|
||||||
return jsonify([])
|
return jsonify([])
|
||||||
|
|
||||||
elif sub == 'list':
|
elif sub == 'list':
|
||||||
ret = []
|
ret = []
|
||||||
for i in LogicNormal.youtube_dl_list:
|
for i in LogicNormal.youtube_dl_list:
|
||||||
data = LogicNormal.get_data(i)
|
data = LogicNormal.get_data(i)
|
||||||
if data is not None:
|
if data is not None:
|
||||||
ret.append(data)
|
ret.append(data)
|
||||||
return jsonify(ret)
|
return jsonify(ret)
|
||||||
|
|
||||||
elif sub == 'stop':
|
elif sub == 'stop':
|
||||||
index = int(request.form['index'])
|
index = int(request.form['index'])
|
||||||
LogicNormal.youtube_dl_list[index].stop()
|
LogicNormal.youtube_dl_list[index].stop()
|
||||||
return jsonify([])
|
return jsonify([])
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error('Exception:%s', e)
|
logger.error('Exception:%s', e)
|
||||||
logger.error(traceback.format_exc())
|
logger.error(traceback.format_exc())
|
||||||
|
|
||||||
#########################################################
|
#########################################################
|
||||||
# API
|
# API
|
||||||
@@ -154,157 +154,157 @@ def ajax(sub):
|
|||||||
@blueprint.route('/api/<sub>', methods=['GET', 'POST'])
|
@blueprint.route('/api/<sub>', methods=['GET', 'POST'])
|
||||||
@check_api
|
@check_api
|
||||||
def api(sub):
|
def api(sub):
|
||||||
plugin = request.form.get('plugin')
|
plugin = request.form.get('plugin')
|
||||||
logger.debug('API %s %s: %s', package_name, sub, plugin)
|
logger.debug('API %s %s: %s', package_name, sub, plugin)
|
||||||
if not plugin: # 요청한 플러그인명이 빈문자열이거나 None면
|
if not plugin: # 요청한 플러그인명이 빈문자열이거나 None면
|
||||||
abort(403) # 403 에러(거부)
|
abort(403) # 403 에러(거부)
|
||||||
try:
|
try:
|
||||||
# 동영상 정보를 반환하는 API
|
# 동영상 정보를 반환하는 API
|
||||||
if sub == 'info_dict':
|
if sub == 'info_dict':
|
||||||
url = request.form.get('url')
|
url = request.form.get('url')
|
||||||
ret = {
|
ret = {
|
||||||
'errorCode': 0,
|
'errorCode': 0,
|
||||||
'info_dict': None
|
'info_dict': None
|
||||||
}
|
}
|
||||||
if None in (url,):
|
if None in (url,):
|
||||||
return LogicNormal.abort(ret, 1) # 필수 요청 변수가 없음
|
return LogicNormal.abort(ret, 1) # 필수 요청 변수가 없음
|
||||||
if not url.startswith('http'):
|
if not url.startswith('http'):
|
||||||
return LogicNormal.abort(ret, 2) # 잘못된 동영상 주소
|
return LogicNormal.abort(ret, 2) # 잘못된 동영상 주소
|
||||||
info_dict = Youtube_dl.get_info_dict(url, ModelSetting.get('proxy'))
|
info_dict = Youtube_dl.get_info_dict(url, ModelSetting.get('proxy'))
|
||||||
if info_dict is None:
|
if info_dict is None:
|
||||||
return LogicNormal.abort(ret, 10) # 실패
|
return LogicNormal.abort(ret, 10) # 실패
|
||||||
ret['info_dict'] = info_dict
|
ret['info_dict'] = info_dict
|
||||||
return jsonify(ret)
|
return jsonify(ret)
|
||||||
|
|
||||||
# 다운로드 준비를 요청하는 API
|
# 다운로드 준비를 요청하는 API
|
||||||
elif sub == 'download':
|
elif sub == 'download':
|
||||||
key = request.form.get('key')
|
key = request.form.get('key')
|
||||||
url = request.form.get('url')
|
url = request.form.get('url')
|
||||||
filename = request.form.get('filename', ModelSetting.get('default_filename'))
|
filename = request.form.get('filename', ModelSetting.get('default_filename'))
|
||||||
save_path = request.form.get('save_path', ModelSetting.get('save_path'))
|
save_path = request.form.get('save_path', ModelSetting.get('save_path'))
|
||||||
format_code = request.form.get('format', None)
|
format_code = request.form.get('format', None)
|
||||||
preferedformat = request.form.get('preferedformat', None)
|
preferedformat = request.form.get('preferedformat', None)
|
||||||
preferredcodec = request.form.get('preferredcodec', None)
|
preferredcodec = request.form.get('preferredcodec', None)
|
||||||
preferredquality = request.form.get('preferredquality', 192)
|
preferredquality = request.form.get('preferredquality', 192)
|
||||||
archive = request.form.get('archive', None)
|
archive = request.form.get('archive', None)
|
||||||
start = request.form.get('start', False)
|
start = request.form.get('start', False)
|
||||||
ret = {
|
ret = {
|
||||||
'errorCode': 0,
|
'errorCode': 0,
|
||||||
'index': None
|
'index': None
|
||||||
}
|
}
|
||||||
if None in (key, url):
|
if None in (key, url):
|
||||||
return LogicNormal.abort(ret, 1) # 필수 요청 변수가 없음
|
return LogicNormal.abort(ret, 1) # 필수 요청 변수가 없음
|
||||||
if not url.startswith('http'):
|
if not url.startswith('http'):
|
||||||
return LogicNormal.abort(ret, 2) # 잘못된 동영상 주소
|
return LogicNormal.abort(ret, 2) # 잘못된 동영상 주소
|
||||||
opts = {}
|
opts = {}
|
||||||
if format_code is not None:
|
if format_code is not None:
|
||||||
opts['format'] = format_code
|
opts['format'] = format_code
|
||||||
postprocessor = []
|
postprocessor = []
|
||||||
if preferedformat is not None:
|
if preferedformat is not None:
|
||||||
postprocessor.append({
|
postprocessor.append({
|
||||||
'key': 'FFmpegVideoConvertor',
|
'key': 'FFmpegVideoConvertor',
|
||||||
'preferedformat': preferedformat
|
'preferedformat': preferedformat
|
||||||
})
|
})
|
||||||
if preferredcodec is not None:
|
if preferredcodec is not None:
|
||||||
if preferredcodec not in ('best', 'mp3', 'aac', 'flac', 'm4a', 'opus', 'vorbis', 'wav'):
|
if preferredcodec not in ('best', 'mp3', 'aac', 'flac', 'm4a', 'opus', 'vorbis', 'wav'):
|
||||||
return LogicNormal.abort(ret, 5) # 허용되지 않은 값이 있음
|
return LogicNormal.abort(ret, 5) # 허용되지 않은 값이 있음
|
||||||
postprocessor.append({
|
postprocessor.append({
|
||||||
'key': 'FFmpegExtractAudio',
|
'key': 'FFmpegExtractAudio',
|
||||||
'preferredcodec': preferredcodec,
|
'preferredcodec': preferredcodec,
|
||||||
'preferredquality': str(preferredquality)
|
'preferredquality': str(preferredquality)
|
||||||
})
|
})
|
||||||
if postprocessor:
|
if postprocessor:
|
||||||
opts['postprocessors'] = postprocessor
|
opts['postprocessors'] = postprocessor
|
||||||
proxy = ModelSetting.get('proxy')
|
proxy = ModelSetting.get('proxy')
|
||||||
if proxy:
|
if proxy:
|
||||||
opts['proxy'] = proxy
|
opts['proxy'] = proxy
|
||||||
if archive is not None:
|
if archive is not None:
|
||||||
opts['download_archive'] = archive
|
opts['download_archive'] = archive
|
||||||
youtube_dl = Youtube_dl(plugin, url, filename, ModelSetting.get('temp_path'), save_path, opts)
|
youtube_dl = Youtube_dl(plugin, url, filename, ModelSetting.get('temp_path'), save_path, opts)
|
||||||
youtube_dl.key = key
|
youtube_dl.key = key
|
||||||
LogicNormal.youtube_dl_list.append(youtube_dl) # 리스트 추가
|
LogicNormal.youtube_dl_list.append(youtube_dl) # 리스트 추가
|
||||||
ret['index'] = youtube_dl.index
|
ret['index'] = youtube_dl.index
|
||||||
if start:
|
if start:
|
||||||
youtube_dl.start()
|
youtube_dl.start()
|
||||||
socketio_emit('add', youtube_dl)
|
socketio_emit('add', youtube_dl)
|
||||||
return jsonify(ret)
|
return jsonify(ret)
|
||||||
|
|
||||||
# 다운로드 시작을 요청하는 API
|
# 다운로드 시작을 요청하는 API
|
||||||
elif sub == 'start':
|
elif sub == 'start':
|
||||||
index = request.form.get('index')
|
index = request.form.get('index')
|
||||||
key = request.form.get('key')
|
key = request.form.get('key')
|
||||||
ret = {
|
ret = {
|
||||||
'errorCode': 0,
|
'errorCode': 0,
|
||||||
'status': None
|
'status': None
|
||||||
}
|
}
|
||||||
if None in (index, key):
|
if None in (index, key):
|
||||||
return LogicNormal.abort(ret, 1) # 필수 요청 변수가 없음
|
return LogicNormal.abort(ret, 1) # 필수 요청 변수가 없음
|
||||||
index = int(index)
|
index = int(index)
|
||||||
if not (0 <= index < len(LogicNormal.youtube_dl_list)):
|
if not (0 <= index < len(LogicNormal.youtube_dl_list)):
|
||||||
return LogicNormal.abort(ret, 3) # 인덱스 범위를 벗어남
|
return LogicNormal.abort(ret, 3) # 인덱스 범위를 벗어남
|
||||||
youtube_dl = LogicNormal.youtube_dl_list[index]
|
youtube_dl = LogicNormal.youtube_dl_list[index]
|
||||||
if youtube_dl.key != key:
|
if youtube_dl.key != key:
|
||||||
return LogicNormal.abort(ret, 4) # 키가 일치하지 않음
|
return LogicNormal.abort(ret, 4) # 키가 일치하지 않음
|
||||||
ret['status'] = youtube_dl.status.name
|
ret['status'] = youtube_dl.status.name
|
||||||
if not youtube_dl.start():
|
if not youtube_dl.start():
|
||||||
return LogicNormal.abort(ret, 10) # 실패
|
return LogicNormal.abort(ret, 10) # 실패
|
||||||
return jsonify(ret)
|
return jsonify(ret)
|
||||||
|
|
||||||
# 다운로드 중지를 요청하는 API
|
# 다운로드 중지를 요청하는 API
|
||||||
elif sub == 'stop':
|
elif sub == 'stop':
|
||||||
index = request.form.get('index')
|
index = request.form.get('index')
|
||||||
key = request.form.get('key')
|
key = request.form.get('key')
|
||||||
ret = {
|
ret = {
|
||||||
'errorCode': 0,
|
'errorCode': 0,
|
||||||
'status': None
|
'status': None
|
||||||
}
|
}
|
||||||
if None in (index, key):
|
if None in (index, key):
|
||||||
return LogicNormal.abort(ret, 1) # 필수 요청 변수가 없음
|
return LogicNormal.abort(ret, 1) # 필수 요청 변수가 없음
|
||||||
index = int(index)
|
index = int(index)
|
||||||
if not (0 <= index < len(LogicNormal.youtube_dl_list)):
|
if not (0 <= index < len(LogicNormal.youtube_dl_list)):
|
||||||
return LogicNormal.abort(ret, 3) # 인덱스 범위를 벗어남
|
return LogicNormal.abort(ret, 3) # 인덱스 범위를 벗어남
|
||||||
youtube_dl = LogicNormal.youtube_dl_list[index]
|
youtube_dl = LogicNormal.youtube_dl_list[index]
|
||||||
if youtube_dl.key != key:
|
if youtube_dl.key != key:
|
||||||
return LogicNormal.abort(ret, 4) # 키가 일치하지 않음
|
return LogicNormal.abort(ret, 4) # 키가 일치하지 않음
|
||||||
ret['status'] = youtube_dl.status.name
|
ret['status'] = youtube_dl.status.name
|
||||||
if not youtube_dl.stop():
|
if not youtube_dl.stop():
|
||||||
return LogicNormal.abort(ret, 10) # 실패
|
return LogicNormal.abort(ret, 10) # 실패
|
||||||
return jsonify(ret)
|
return jsonify(ret)
|
||||||
|
|
||||||
# 현재 상태를 반환하는 API
|
# 현재 상태를 반환하는 API
|
||||||
elif sub == 'status':
|
elif sub == 'status':
|
||||||
index = request.form.get('index')
|
index = request.form.get('index')
|
||||||
key = request.form.get('key')
|
key = request.form.get('key')
|
||||||
ret = {
|
ret = {
|
||||||
'errorCode': 0,
|
'errorCode': 0,
|
||||||
'status': None,
|
'status': None,
|
||||||
'start_time': None,
|
'start_time': None,
|
||||||
'end_time': None,
|
'end_time': None,
|
||||||
'temp_path': None,
|
'temp_path': None,
|
||||||
'save_path': None
|
'save_path': None
|
||||||
}
|
}
|
||||||
if None in (index, key):
|
if None in (index, key):
|
||||||
return LogicNormal.abort(ret, 1) # 필수 요청 변수가 없음
|
return LogicNormal.abort(ret, 1) # 필수 요청 변수가 없음
|
||||||
index = int(index)
|
index = int(index)
|
||||||
if not (0 <= index < len(LogicNormal.youtube_dl_list)):
|
if not (0 <= index < len(LogicNormal.youtube_dl_list)):
|
||||||
return LogicNormal.abort(ret, 3) # 인덱스 범위를 벗어남
|
return LogicNormal.abort(ret, 3) # 인덱스 범위를 벗어남
|
||||||
youtube_dl = LogicNormal.youtube_dl_list[index]
|
youtube_dl = LogicNormal.youtube_dl_list[index]
|
||||||
if youtube_dl.key != key:
|
if youtube_dl.key != key:
|
||||||
return LogicNormal.abort(ret, 4) # 키가 일치하지 않음
|
return LogicNormal.abort(ret, 4) # 키가 일치하지 않음
|
||||||
ret['status'] = youtube_dl.status.name
|
ret['status'] = youtube_dl.status.name
|
||||||
ret['start_time'] = youtube_dl.start_time.strftime('%Y-%m-%dT%H:%M:%S') if youtube_dl.start_time is not None else None
|
ret['start_time'] = youtube_dl.start_time.strftime('%Y-%m-%dT%H:%M:%S') if youtube_dl.start_time is not None else None
|
||||||
ret['end_time'] = youtube_dl.end_time.strftime('%Y-%m-%dT%H:%M:%S') if youtube_dl.end_time is not None else None
|
ret['end_time'] = youtube_dl.end_time.strftime('%Y-%m-%dT%H:%M:%S') if youtube_dl.end_time is not None else None
|
||||||
ret['temp_path'] = youtube_dl.temp_path
|
ret['temp_path'] = youtube_dl.temp_path
|
||||||
ret['save_path'] = youtube_dl.save_path
|
ret['save_path'] = youtube_dl.save_path
|
||||||
return jsonify(ret)
|
return jsonify(ret)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error('Exception:%s', e)
|
logger.error('Exception:%s', e)
|
||||||
logger.error(traceback.format_exc())
|
logger.error(traceback.format_exc())
|
||||||
abort(500) # 500 에러(서버 오류)
|
abort(500) # 500 에러(서버 오류)
|
||||||
abort(404) # 404 에러(페이지 없음)
|
abort(404) # 404 에러(페이지 없음)
|
||||||
|
|
||||||
#########################################################
|
#########################################################
|
||||||
# socketio
|
# socketio
|
||||||
#########################################################
|
#########################################################
|
||||||
def socketio_emit(cmd, data):
|
def socketio_emit(cmd, data):
|
||||||
socketio.emit(cmd, LogicNormal.get_data(data), namespace='/%s' % package_name, broadcast=True)
|
socketio.emit(cmd, LogicNormal.get_data(data), namespace='/%s' % package_name, broadcast=True)
|
||||||
|
|||||||
@@ -1,96 +1,96 @@
|
|||||||
{% macro setting_select2(id, title, options, col='9', desc=None, value=None) %}
|
{% macro setting_select2(id, title, options, col='9', desc=None, value=None) %}
|
||||||
{{ macros.setting_top(title) }}
|
{{ macros.setting_top(title) }}
|
||||||
<div class="input-group col-sm-{{ col }}">
|
<div class="input-group col-sm-{{ col }}">
|
||||||
<select id="{{ id }}" name="{{ id }}" class="form-control form-control-sm">
|
<select id="{{ id }}" name="{{ id }}" class="form-control form-control-sm">
|
||||||
{% set ns = namespace(optgroup=none) %}
|
{% set ns = namespace(optgroup=none) %}
|
||||||
{% for item in options %}
|
{% for item in options %}
|
||||||
{% if ns.optgroup != item[2] %}
|
{% if ns.optgroup != item[2] %}
|
||||||
{% if ns.optgroup is not none %}
|
{% if ns.optgroup is not none %}
|
||||||
</optgroup>
|
</optgroup>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% if item[2] is not none %}
|
{% if item[2] is not none %}
|
||||||
<optgroup label="{{ item[2] }}">
|
<optgroup label="{{ item[2] }}">
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% set ns.optgroup = item[2] %}
|
{% set ns.optgroup = item[2] %}
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% if value is not none and value == item[0] %}
|
{% if value is not none and value == item[0] %}
|
||||||
<option value="{{ item[0] }}" selected>{{ item[1] }}</option>
|
<option value="{{ item[0] }}" selected>{{ item[1] }}</option>
|
||||||
{% else %}
|
{% else %}
|
||||||
<option value="{{ item[0] }}">{{ item[1] }}</option>
|
<option value="{{ item[0] }}">{{ item[1] }}</option>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
{% if ns.optgroup is not none %}
|
{% if ns.optgroup is not none %}
|
||||||
</optgroup>
|
</optgroup>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
{{ macros.setting_bottom(desc) }}
|
{{ macros.setting_bottom(desc) }}
|
||||||
{% endmacro %}
|
{% endmacro %}
|
||||||
|
|
||||||
{% extends "base.html" %}
|
{% extends "base.html" %}
|
||||||
{% block content %}
|
{% block content %}
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
{{ macros.setting_input_text('url', 'URL', placeholder='http:// 주소', desc='유튜브, 네이버TV 등 동영상 주소') }}
|
{{ macros.setting_input_text('url', 'URL', placeholder='http:// 주소', desc='유튜브, 네이버TV 등 동영상 주소') }}
|
||||||
{{ macros.setting_input_text('filename', '파일명', value=arg['file_name'], desc='템플릿 규칙은 https://github.com/ytdl-org/youtube-dl/blob/master/README.md#output-template 참고') }}
|
{{ macros.setting_input_text('filename', '파일명', value=arg['file_name'], desc='템플릿 규칙은 https://github.com/ytdl-org/youtube-dl/blob/master/README.md#output-template 참고') }}
|
||||||
{{ macros.setting_select('preset', '동영상 포맷 프리셋', arg['preset_list'], col='3') }}
|
{{ macros.setting_select('preset', '동영상 포맷 프리셋', arg['preset_list'], col='3') }}
|
||||||
{{ macros.setting_input_text('format', '동영상 포맷', desc=['포맷 지정은 https://github.com/ytdl-org/youtube-dl/blob/master/README.md#format-selection 참고', '빈칸으로 두면 최고 화질로 다운로드합니다.']) }}
|
{{ macros.setting_input_text('format', '동영상 포맷', desc=['포맷 지정은 https://github.com/ytdl-org/youtube-dl/blob/master/README.md#format-selection 참고', '빈칸으로 두면 최고 화질로 다운로드합니다.']) }}
|
||||||
{{ setting_select2('postprocessor', '후처리', arg['postprocessor_list'], col='3', desc='다운로드 후 FFmpeg로 후처리합니다.') }}
|
{{ setting_select2('postprocessor', '후처리', arg['postprocessor_list'], col='3', desc='다운로드 후 FFmpeg로 후처리합니다.') }}
|
||||||
{{ macros.setting_button([['download_start', '다운로드']]) }}
|
{{ macros.setting_button([['download_start', '다운로드']]) }}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
"use strict";
|
"use strict";
|
||||||
const package_name = '{{ arg["package_name"] }}';
|
const package_name = '{{ arg["package_name"] }}';
|
||||||
|
|
||||||
$(function () {
|
$(function () {
|
||||||
// 프리셋 변경
|
// 프리셋 변경
|
||||||
$('#preset').change(function () {
|
$('#preset').change(function () {
|
||||||
if ($(this).val() === '_custom') {
|
if ($(this).val() === '_custom') {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
$('#format').val($(this).val());
|
$('#format').val($(this).val());
|
||||||
});
|
});
|
||||||
$('#format').change(function () {
|
$('#format').change(function () {
|
||||||
$('#preset').val('_custom');
|
$('#preset').val('_custom');
|
||||||
});
|
});
|
||||||
|
|
||||||
// 후처리 변경
|
// 후처리 변경
|
||||||
$('#postprocessor').change(function () {
|
$('#postprocessor').change(function () {
|
||||||
if ($(this).find($('option[value="' + $(this).val() + '"]')).parent().attr('label') === '오디오 추출') {
|
if ($(this).find($('option[value="' + $(this).val() + '"]')).parent().attr('label') === '오디오 추출') {
|
||||||
$('#preset').val('bestaudio/best').change();
|
$('#preset').val('bestaudio/best').change();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// 다운로드
|
// 다운로드
|
||||||
$('#download_start').click(function () {
|
$('#download_start').click(function () {
|
||||||
let url = $('#url').val();
|
let url = $('#url').val();
|
||||||
if (url.startsWith('http') === false) {
|
if (url.startsWith('http') === false) {
|
||||||
$.notify('<strong>URL을 입력하세요.</strong>', {
|
$.notify('<strong>URL을 입력하세요.</strong>', {
|
||||||
type: 'warning'
|
type: 'warning'
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
$.ajax({
|
$.ajax({
|
||||||
url: '/' + package_name + '/ajax/download',
|
url: '/' + package_name + '/ajax/download',
|
||||||
type: 'POST',
|
type: 'POST',
|
||||||
cache: false,
|
cache: false,
|
||||||
data: {
|
data: {
|
||||||
url: url,
|
url: url,
|
||||||
filename: $('#filename').val(),
|
filename: $('#filename').val(),
|
||||||
format: $('#format').val(),
|
format: $('#format').val(),
|
||||||
postprocessor: $('#postprocessor').val()
|
postprocessor: $('#postprocessor').val()
|
||||||
},
|
},
|
||||||
dataType: 'json',
|
dataType: 'json',
|
||||||
success: function () {
|
success: function () {
|
||||||
$.notify('<strong>분석중..</strong>', {
|
$.notify('<strong>분석중..</strong>', {
|
||||||
type: 'info'
|
type: 'info'
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return false;
|
return false;
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -2,162 +2,165 @@
|
|||||||
{% block content %}
|
{% block content %}
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
.row > div {
|
.row > div {
|
||||||
padding-top: 3px;
|
padding-top: 3px;
|
||||||
padding-bottom: 3px;
|
padding-bottom: 3px;
|
||||||
}
|
}
|
||||||
.row {
|
|
||||||
align-items: center;
|
.row {
|
||||||
word-break: break-all;
|
align-items: center;
|
||||||
}
|
word-break: break-all;
|
||||||
.row > div:nth-child(odd) {
|
}
|
||||||
text-align: right;
|
|
||||||
}
|
.row > div:nth-child(odd) {
|
||||||
.row > div:nth-child(even) {
|
text-align: right;
|
||||||
text-align: left;
|
}
|
||||||
}
|
|
||||||
|
.row > div:nth-child(even) {
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
<table id="result_table" class="table table-sm tableRowHover">
|
<table id="result_table" class="table table-sm tableRowHover">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th style="width: 5%">IDX</th>
|
<th style="width: 5%">IDX</th>
|
||||||
<th style="width: 8%">Plugin</th>
|
<th style="width: 8%">Plugin</th>
|
||||||
<th style="width: 10%">시작시간</th>
|
<th style="width: 10%">시작시간</th>
|
||||||
<th style="width: 10%">타입</th>
|
<th style="width: 10%">타입</th>
|
||||||
<th style="width: 28%">제목</th>
|
<th style="width: 28%">제목</th>
|
||||||
<th style="width: 8%">상태</th>
|
<th style="width: 8%">상태</th>
|
||||||
<th style="width: 15%">진행률</th>
|
<th style="width: 15%">진행률</th>
|
||||||
<th style="width: 8%">진행시간</th>
|
<th style="width: 8%">진행시간</th>
|
||||||
<th style="width: 8%">Action</th>
|
<th style="width: 8%">Action</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody id="list"></tbody>
|
<tbody id="list"></tbody>
|
||||||
</table>
|
</table>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
"use strict";
|
"use strict";
|
||||||
const package_name = '{{ arg["package_name"] }}';
|
const package_name = '{{ arg["package_name"] }}';
|
||||||
|
|
||||||
$(function () {
|
$(function () {
|
||||||
let socket = io.connect(location.origin + '/' + package_name);
|
let socket = io.connect(location.origin + '/' + package_name);
|
||||||
|
|
||||||
socket.on('add', function (data) {
|
socket.on('add', function (data) {
|
||||||
$('#list').append(make_item(data));
|
$('#list').append(make_item(data));
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.on('status', function (data) {
|
socket.on('status', function (data) {
|
||||||
status_html(data);
|
status_html(data);
|
||||||
});
|
});
|
||||||
|
|
||||||
$.ajax({
|
$.ajax({
|
||||||
url: '/' + package_name + '/ajax/list',
|
url: '/' + package_name + '/ajax/list',
|
||||||
type: 'POST',
|
type: 'POST',
|
||||||
cache: false,
|
cache: false,
|
||||||
data: { },
|
data: {},
|
||||||
dataType: 'json',
|
dataType: 'json',
|
||||||
success: function (data) {
|
success: function (data) {
|
||||||
let str = '';
|
let str = '';
|
||||||
for (let i of data) {
|
for (let i of data) {
|
||||||
str += make_item(i);
|
str += make_item(i);
|
||||||
}
|
}
|
||||||
$('#list').html(str);
|
$('#list').html(str);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
$('#list').on('click', '.youtube-dl_stop', function () {
|
$('#list').on('click', '.youtube-dl_stop', function () {
|
||||||
let index = $(this).data('index');
|
let index = $(this).data('index');
|
||||||
$.ajax({
|
$.ajax({
|
||||||
url: '/' + package_name + '/ajax/stop',
|
url: '/' + package_name + '/ajax/stop',
|
||||||
type: 'POST',
|
type: 'POST',
|
||||||
cache: false,
|
cache: false,
|
||||||
data: {
|
data: {
|
||||||
index: index
|
index: index
|
||||||
},
|
},
|
||||||
dataType: 'json',
|
dataType: 'json',
|
||||||
success: function () {
|
success: function () {
|
||||||
location.reload(); // 새로고침
|
location.reload(); // 새로고침
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return false;
|
return false;
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
function make_item(data) {
|
function make_item(data) {
|
||||||
let str = `<tr id="item_${data.index}" aria-expanded="true" style="cursor: pointer" data-toggle="collapse" data-target="#collapse_${data.index}">`;
|
let str = `<tr id="item_${data.index}" aria-expanded="true" style="cursor: pointer" data-toggle="collapse" data-target="#collapse_${data.index}">`;
|
||||||
str += get_item(data);
|
str += get_item(data);
|
||||||
str += '</tr>';
|
str += '</tr>';
|
||||||
str += `<tr id="collapse_${data.index}" class="collapse tableRowHoverOff" style="cursor: pointer">`;
|
str += `<tr id="collapse_${data.index}" class="collapse tableRowHoverOff" style="cursor: pointer">`;
|
||||||
str += '<td colspan="9">';
|
str += '<td colspan="9">';
|
||||||
str += `<div id="detail_${data.index}">`;
|
str += `<div id="detail_${data.index}">`;
|
||||||
str += get_detail(data);
|
str += get_detail(data);
|
||||||
str += '</div>';
|
str += '</div>';
|
||||||
str += '</td>';
|
str += '</td>';
|
||||||
str += '</tr>';
|
str += '</tr>';
|
||||||
return str;
|
return str;
|
||||||
}
|
}
|
||||||
|
|
||||||
function get_item(data) {
|
function get_item(data) {
|
||||||
let str = `<td>${data.index + 1}</td>`;
|
let str = `<td>${data.index + 1}</td>`;
|
||||||
str += `<td>${data.plugin}</td>`;
|
str += `<td>${data.plugin}</td>`;
|
||||||
str += `<td>${data.start_time}</td>`;
|
str += `<td>${data.start_time}</td>`;
|
||||||
str += `<td>${data.extractor}</td>`;
|
str += `<td>${data.extractor}</td>`;
|
||||||
str += `<td>${data.title}</td>`;
|
str += `<td>${data.title}</td>`;
|
||||||
str += `<td>${data.status_ko}</td>`;
|
str += `<td>${data.status_ko}</td>`;
|
||||||
let visi = 'hidden';
|
let visi = 'hidden';
|
||||||
if (parseInt(data.percent) > 0 && data.status_str !== 'STOP') {
|
if (parseInt(data.percent) > 0 && data.status_str !== 'STOP') {
|
||||||
visi = 'visible';
|
visi = 'visible';
|
||||||
}
|
}
|
||||||
str += `<td><div class="progress"><div class="progress-bar" style="visibility: ${visi}; width: ${data.percent}%">${data.percent}%</div></div></td>`;
|
str += `<td><div class="progress"><div class="progress-bar" style="visibility: ${visi}; width: ${data.percent}%">${data.percent}%</div></div></td>`;
|
||||||
str += `<td>${data.download_time}</td>`;
|
str += `<td>${data.download_time}</td>`;
|
||||||
str += '<td class="tableRowHoverOff">';
|
str += '<td class="tableRowHoverOff">';
|
||||||
if (data.status_str === 'START' || data.status_str === 'DOWNLOADING' || data.status_str === 'FINISHED') {
|
if (data.status_str === 'START' || data.status_str === 'DOWNLOADING' || data.status_str === 'FINISHED') {
|
||||||
str += `<button class="align-middle btn btn-outline-danger btn-sm youtube-dl_stop" data-index="${data.index}">중지</button>`;
|
str += `<button class="align-middle btn btn-outline-danger btn-sm youtube-dl_stop" data-index="${data.index}">중지</button>`;
|
||||||
}
|
}
|
||||||
str += '</td>';
|
str += '</td>';
|
||||||
return str;
|
return str;
|
||||||
}
|
}
|
||||||
|
|
||||||
function get_detail(data) {
|
function get_detail(data) {
|
||||||
let str = info_html('URL', data.url, data.url);
|
let str = info_html('URL', data.url, data.url);
|
||||||
str += info_html('업로더', data.uploader, data.uploader_url);
|
str += info_html('업로더', data.uploader, data.uploader_url);
|
||||||
str += info_html('임시폴더', data.temp_path);
|
str += info_html('임시폴더', data.temp_path);
|
||||||
str += info_html('저장폴더', data.save_path);
|
str += info_html('저장폴더', data.save_path);
|
||||||
str += info_html('종료시간', data.end_time);
|
str += info_html('종료시간', data.end_time);
|
||||||
if (data.status_str === 'DOWNLOADING') {
|
if (data.status_str === 'DOWNLOADING') {
|
||||||
str += info_html('', '<b>현재 다운로드 중인 파일에 대한 정보</b>');
|
str += info_html('', '<b>현재 다운로드 중인 파일에 대한 정보</b>');
|
||||||
str += info_html('파일명', data.filename);
|
str += info_html('파일명', data.filename);
|
||||||
str += info_html('진행률(current/total)', `${data.percent}% (${data.downloaded_bytes_str} / ${data.total_bytes_str})`);
|
str += info_html('진행률(current/total)', `${data.percent}% (${data.downloaded_bytes_str} / ${data.total_bytes_str})`);
|
||||||
str += info_html('남은 시간', `${data.eta}초`);
|
str += info_html('남은 시간', `${data.eta}초`);
|
||||||
str += info_html('다운 속도', data.speed_str);
|
str += info_html('다운 속도', data.speed_str);
|
||||||
}
|
}
|
||||||
return str;
|
return str;
|
||||||
}
|
}
|
||||||
|
|
||||||
function info_html(left, right, option) {
|
function info_html(left, right, option) {
|
||||||
let str = '<div class="row">';
|
let str = '<div class="row">';
|
||||||
let link = (left === 'URL' || left === '업로더');
|
let link = (left === 'URL' || left === '업로더');
|
||||||
str += '<div class="col-sm-2">';
|
str += '<div class="col-sm-2">';
|
||||||
str += `<b>${left}</b>`;
|
str += `<b>${left}</b>`;
|
||||||
str += '</div>';
|
str += '</div>';
|
||||||
str += '<div class="col-sm-10">';
|
str += '<div class="col-sm-10">';
|
||||||
str += '<div class="input-group col-sm-9">';
|
str += '<div class="input-group col-sm-9">';
|
||||||
str += '<span class="text-left" style="padding-left: 10px; padding-top: 3px">';
|
str += '<span class="text-left" style="padding-left: 10px; padding-top: 3px">';
|
||||||
if (link) {
|
if (link) {
|
||||||
str += `<a href="${option}" target="_blank">`;
|
str += `<a href="${option}" target="_blank">`;
|
||||||
}
|
}
|
||||||
str += right;
|
str += right;
|
||||||
if (link) {
|
if (link) {
|
||||||
str += '</a>';
|
str += '</a>';
|
||||||
}
|
}
|
||||||
str += '</span></div></div></div>';
|
str += '</span></div></div></div>';
|
||||||
return str;
|
return str;
|
||||||
}
|
}
|
||||||
|
|
||||||
function status_html(data) {
|
function status_html(data) {
|
||||||
$('#item_' + data.index).html(get_item(data));
|
$('#item_' + data.index).html(get_item(data));
|
||||||
$('#detail_' + data.index).html(get_detail(data));
|
$('#detail_' + data.index).html(get_detail(data));
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -2,20 +2,20 @@
|
|||||||
{% block content %}
|
{% block content %}
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
{{ macros.setting_input_text('youtube_dl_version', 'youtube-dl 버전', value=arg['youtube_dl_version']) }}
|
{{ macros.setting_input_text('youtube_dl_version', 'youtube-dl 버전', value=arg['youtube_dl_version']) }}
|
||||||
<form id="setting">
|
<form id="setting">
|
||||||
{{ macros.setting_input_text('temp_path', '임시 폴더', value=arg['temp_path'], placeholder='임시 폴더 경로', desc='다운로드 파일이 임시로 저장될 폴더 입니다.') }}
|
{{ macros.setting_input_text('temp_path', '임시 폴더', value=arg['temp_path'], placeholder='임시 폴더 경로', desc='다운로드 파일이 임시로 저장될 폴더 입니다.') }}
|
||||||
{{ macros.setting_input_text('save_path', '저장 폴더', value=arg['save_path'], placeholder='저장 폴더 경로', desc='정상적으로 완료된 파일이 이동할 폴더 입니다.') }}
|
{{ macros.setting_input_text('save_path', '저장 폴더', value=arg['save_path'], placeholder='저장 폴더 경로', desc='정상적으로 완료된 파일이 이동할 폴더 입니다.') }}
|
||||||
{{ macros.setting_input_text('default_filename', '기본 파일명', value=arg['default_filename'], placeholder='저장 폴더 경로', desc=['템플릿 규칙은 https://github.com/ytdl-org/youtube-dl/blob/master/README.md#output-template 참고', '기본값은 "%(title)s-%(id)s.%(ext)s"입니다.']) }}
|
{{ macros.setting_input_text('default_filename', '기본 파일명', value=arg['default_filename'], placeholder='저장 폴더 경로', desc=['템플릿 규칙은 https://github.com/ytdl-org/youtube-dl/blob/master/README.md#output-template 참고', '기본값은 "%(title)s-%(id)s.%(ext)s"입니다.']) }}
|
||||||
{{ macros.setting_input_text('proxy', '프록시', value=arg['proxy'], placeholder='프록시 주소', desc=['HTTP/HTTPS/SOCKS를 지원합니다. 예) socks5://127.0.0.1:1080/', '빈칸으로 두면 프록시를 사용하지 않습니다.']) }}
|
{{ macros.setting_input_text('proxy', '프록시', value=arg['proxy'], placeholder='프록시 주소', desc=['HTTP/HTTPS/SOCKS를 지원합니다. 예) socks5://127.0.0.1:1080/', '빈칸으로 두면 프록시를 사용하지 않습니다.']) }}
|
||||||
{{ macros.setting_checkbox('activate_cors', 'CORS 허용', value=arg['activate_cors'], desc='API로의 크로스 도메인 요청을 허용합니다. 설정 저장 후 재시작이 필요합니다.') }}
|
{{ macros.setting_checkbox('activate_cors', 'CORS 허용', value=arg['activate_cors'], desc='API로의 크로스 도메인 요청을 허용합니다. 설정 저장 후 재시작이 필요합니다.') }}
|
||||||
{{ macros.setting_button([['global_setting_save_btn', '저장']]) }}
|
{{ macros.setting_button([['global_setting_save_btn', '저장']]) }}
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
"use strict";
|
"use strict";
|
||||||
const package_name = '{{ arg["package_name"] }}';
|
const package_name = '{{ arg["package_name"] }}';
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
Reference in New Issue
Block a user