diff --git a/README.md b/README.md index 3c8142a..f69a9b2 100644 --- a/README.md +++ b/README.md @@ -11,9 +11,12 @@ SJVA에서 "시스템 → 플러그인 → 플러그인 수동 설치" 칸에 다른 분들이 만든 플러그인을 참고하며 주먹구구식으로 만들었습니다;; -드디어! API를 추가했습니다. 다른 플러그인에서 동영상 정보나 다운로드를 요청할 수 있습니다. +API도 제공합니다. 다른 플러그인에서 동영상 정보나 다운로드를 요청할 수 있습니다. 다른 플러그인이 멋대로 다운로드를 중지할 수 없도록 다운로드를 요청할 때 임의의 키를 넘겨 받습니다. 이 중지 요청 시 키가 일치해야 요청이 실행됩니다. -이걸로 뭔갈 만드실 분이 계실지... +과연 이걸로 뭔가를 만드실 분이 계실지... + +일반적인 유튜브 오디오 비트레이트가 192kbps라서 오디오 추출 시 비트레이트를 192kbps로 설정했습니다. +API에선 직접 비트레이트를 설정할 수 있습니다. ## API ### 공통사항 @@ -30,13 +33,13 @@ SJVA에서 "시스템 → 플러그인 → 플러그인 수동 설치" 칸에 * `10` - 실패. 요청은 성공하였으나 실행 결과가 실패 #### Status 타입 상태를 나타냄 -* "`READY`" - 준비 -* "`START`" - 분석중 -* "`DOWNLOADING`" - 다운로드중 -* "`ERROR`" - 실패 -* "`FINISHED`" - 변환중 -* "`STOP`" - 중지 -* "`COMPLETED`" - 완료 +* `"READY"` - 준비 +* `"START"` - 분석중 +* `"DOWNLOADING"` - 다운로드중 +* `"ERROR"` - 실패 +* `"FINISHED"` - 변환중 +* `"STOP"` - 중지 +* `"COMPLETED"` - 완료 ### /youtube-dl/api/info_dict 동영상 정보를 반환하는 API @@ -53,7 +56,7 @@ SJVA에서 "시스템 → 플러그인 → 플러그인 수동 설치" 칸에 동영상 정보(`info_dict` 키)에는 youtube-dl에서 생성한 info_dict 정보가 그대로 들어있습니다. 따라서 이 부분은 직접 주소를 넣어가며 반환되는 정보를 확인해보는게 좋습니다. 간단한 예로 `thumbnail` 키엔 썸네일 주소, `uploader` 키엔 업로더 이름, `title` 키엔 동영상 제목, `duration` 키엔 동영상 길이 등이 들어 있습니다. -그리고 만약 주소가 플레이리스트라면 `_type` 키에 "`playlist`"라는 값이 들어 있습니다. 이때는 `entries` 키에 리스트가 들어있어 동영상들의 제목과 ID를 확인할 수 있습니다. +그리고 만약 주소가 플레이리스트라면 `_type` 키에 `"playlist"`라는 값이 들어 있습니다. 이때는 `entries` 키에 리스트가 들어있어 동영상들의 제목과 ID를 확인할 수 있습니다. ### /youtube-dl/api/download 다운로드 준비를 요청하는 API @@ -63,11 +66,14 @@ SJVA에서 "시스템 → 플러그인 → 플러그인 수동 설치" 칸에 `plugin` | 플러그인 이름 | O | String `key` | 임의의 키. 이후 다운로드를 제어할 때 이 키가 필요함 | O | String `url` | 동영상 주소 | O | String -`filename` | 파일명. 템플릿 규칙은 https://github.com/ytdl-org/youtube-dl/blob/master/README.md#output-template 참고. 기본값: 사용자 설정 | X | String -`temp_path` | 임시 폴더 경로. 기본값: 사용자 설정 | X | String -`save_path` | 저장 폴더 경로. 기본값: 사용자 설정 | X | String -`format_code` | 동영상 포맷. 포맷 지정은 https://github.com/ytdl-org/youtube-dl/blob/master/README.md#format-selection 참고. 기본값: 최고 화질 | X | String -`start` | 다운로드 준비 후 바로 다운로드를 시작할지 여부. 기본값: false | X | Boolean +`filename` | 파일명. 템플릿 규칙은 https://github.com/ytdl-org/youtube-dl/blob/master/README.md#output-template 참고. 미지정 시 사용자 설정 | X | String +`temp_path` | 임시 폴더 경로. 미지정 시 사용자 설정 | X | String +`save_path` | 저장 폴더 경로. 미지정 시 사용자 설정 | X | String +`format_code` | 동영상 포맷. 포맷 지정은 https://github.com/ytdl-org/youtube-dl/blob/master/README.md#format-selection 참고. 미지정 시 최고 화질 | X | String +`preferedformat` | 변환할 비디오 포맷. 가능한 포맷은 https://ffmpeg.org/general.html#File-Formats 참고. 미지정 시 변환하지 않음 | X | String +`preferredcodec` | 추출할 오디오 코덱. 가능한 값은 `"mp3"`, `"aac"`, `"flac"`, `"m4a"`, `"opus"`, `"vorbis"`, `"wav"`. 미지정 시 추출하지 않음 | X | String +`preferredquality` | 추출한 오디오의 비트레이트. `preferredcodec` 키가 있을 때만 유효. 기본값: `"192"` | X | String +`start` | 다운로드 준비 후 바로 다운로드를 시작할지 여부. 기본값: `false` | X | Boolean #### Response 키 | 설명 | 타입 --- | --- | --- @@ -124,6 +130,11 @@ SJVA에서 "시스템 → 플러그인 → 플러그인 수동 설치" 칸에 물론 해당 정보가 없으면 null입니다. ## Changelog +v1.3.0 +* 후처리 기능 추가 + 이제 비디오 변환이나 오디오 추출이 가능합니다. + 오디오 추출의 경우 비트레이트는 192kbps로 설정되어 있습니다. + v1.2.5 * 기본 파일명 설정 추가 * API에서 일부 키를 선택으로 변경 diff --git a/info.json b/info.json index d3037d7..570cf32 100644 --- a/info.json +++ b/info.json @@ -1 +1 @@ -{"description": "\uc720\ud29c\ube0c, \ub124\uc774\ubc84TV \ub4f1 \ub3d9\uc601\uc0c1 \uc0ac\uc774\ud2b8\uc5d0\uc11c \ub3d9\uc601\uc0c1 \ub2e4\uc6b4\ub85c\ub4dc", "name": "youtube-dl", "more": "", "version": "1.2.5", "home": "https://github.com/joyfuI/youtube-dl", "category_name": "vod", "developer": "joyfuI"} \ No newline at end of file +{"description": "\uc720\ud29c\ube0c, \ub124\uc774\ubc84TV \ub4f1 \ub3d9\uc601\uc0c1 \uc0ac\uc774\ud2b8\uc5d0\uc11c \ub3d9\uc601\uc0c1 \ub2e4\uc6b4\ub85c\ub4dc", "name": "youtube-dl", "more": "", "version": "1.3.0", "home": "https://github.com/joyfuI/youtube-dl", "category_name": "vod", "developer": "joyfuI"} \ No newline at end of file diff --git a/logic.py b/logic.py index f7d816a..a39bbdf 100644 --- a/logic.py +++ b/logic.py @@ -102,13 +102,57 @@ class Logic(object): ['worstvideo+worstaudio/worst', '최저 화질'], ['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)'], - ['webm', 'webm'], ['bestvideo[filesize<50M]+bestaudio/best[filesize<50M]', '50MB 미만'], - ['bestaudio', '오디오만'], + ['bestaudio/best', '오디오만'], ['_custom', '사용자 정의'] ] return preset_list + @staticmethod + def get_postprocessor_list(): + postprocessor_list = [ + ['', '후처리 안함'], + ['_optgroup', '비디오 변환'], + ['mp4', 'MP4'], + ['flv', 'FLV'], + ['webm', 'WebM'], + ['ogg', 'Ogg'], + ['mkv', 'MKV'], + ['ts', 'TS'], + ['avi', 'AVI'], + ['wmv', 'WMV'], + ['mov', 'MOV'], + ['gif', 'GIF'], + ['_optgroup', ''], + ['_optgroup', '오디오 추출'], + ['mp3', 'MP3'], + ['aac', 'AAC'], + ['flac', 'FLAC'], + ['m4a', 'M4A'], + ['opus', 'Opus'], + ['vorbis', 'Vorbis'], + ['wav', 'WAV'], + ['_optgroup', ''] + ] + return postprocessor_list + + @staticmethod + def get_postprocessor(): + video_convertor = [] + extract_audio = [] + optgroup = None + for i in Logic.get_postprocessor_list(): + if i[0] == '_optgroup': + if i[1] != '': # optgroup 태그 열기 + optgroup = i[1] + else: # optgroup 태그 닫기 + optgroup = None + elif optgroup == '비디오 변환': + video_convertor.append(i[0]) + elif optgroup == '오디오 추출': + extract_audio.append(i[0]) + return video_convertor, extract_audio + @staticmethod def get_data(youtube_dl): try: diff --git a/my_youtube_dl.py b/my_youtube_dl.py index b2a7604..4a359ea 100644 --- a/my_youtube_dl.py +++ b/my_youtube_dl.py @@ -43,7 +43,7 @@ class Youtube_dl(object): _index = 0 _last_msg = '' - def __init__(self, plugin, url, filename, temp_path, save_path, format_code=None): + def __init__(self, plugin, url, filename, temp_path, save_path, format_code=None, postprocessor=None): self.plugin = plugin self.url = url self.filename = filename @@ -54,6 +54,7 @@ class Youtube_dl(object): os.makedirs(save_path) self.save_path = save_path self.format_code = format_code + self.postprocessor = postprocessor self.index = Youtube_dl._index Youtube_dl._index += 1 self.status = Status.READY @@ -67,12 +68,10 @@ class Youtube_dl(object): self.uploader = None # 업로더 self.uploader_url = None # 업로더 주소 # info_dict에서 얻는 정보(entries) - """ - self.playlist_index = None - self.duration = None # 길이 - self.format = None # 포맷 - self.thumbnail = None # 썸네일 - """ + # self.playlist_index = None + # self.duration = None # 길이 + # self.format = None # 포맷 + # self.thumbnail = None # 썸네일 # progress_hooks에서 얻는 정보 self.downloaded_bytes = None # 다운로드한 크기 self.total_bytes = None # 전체 크기 @@ -107,6 +106,8 @@ class Youtube_dl(object): } if self.format_code is not None: ydl_opts['format'] = self.format_code + if self.postprocessor is not None: + ydl_opts['postprocessors'] = self.postprocessor with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([self.url]) if self.status == Status.FINISHED: # 다운로드 성공 diff --git a/plugin.py b/plugin.py index f4400c6..3424ab2 100644 --- a/plugin.py +++ b/plugin.py @@ -36,7 +36,7 @@ menu = { } plugin_info = { - 'version': '1.2.5', + 'version': '1.3.0', 'name': 'youtube-dl', 'category_name': 'vod', 'developer': 'joyfuI', @@ -73,6 +73,7 @@ def detail(sub): elif sub == 'download': arg['file_name'] = Logic.get_setting_value('default_filename') arg['preset_list'] = Logic.get_preset_list() + arg['postprocessor_list'] = Logic.get_postprocessor_list() return render_template('%s_download.html' % package_name, arg=arg) elif sub == 'list': @@ -103,7 +104,20 @@ def ajax(sub): temp_path = Logic.get_setting_value('temp_path') save_path = Logic.get_setting_value('save_path') format_code = request.form['format'] if request.form['format'] else None - youtube_dl = Youtube_dl(package_name, url, filename, temp_path, save_path, format_code) + postprocessor = request.form['postprocessor'] if request.form['postprocessor'] else None + video_convertor, extract_audio = Logic.get_postprocessor() + if postprocessor in video_convertor: + postprocessor = [{ + 'key': 'FFmpegVideoConvertor', + 'preferedformat': postprocessor + }] + elif postprocessor in extract_audio: + postprocessor = [{ + 'key': 'FFmpegExtractAudio', + 'preferredcodec': postprocessor, + 'preferredquality': '192' + }] + youtube_dl = Youtube_dl(package_name, url, filename, temp_path, save_path, format_code, postprocessor) Logic.youtube_dl_list.append(youtube_dl) # 리스트 추가 youtube_dl.start() return jsonify([]) @@ -161,6 +175,9 @@ def api(sub): temp_path = request.form.get('temp_path', Logic.get_setting_value('temp_path')) save_path = request.form.get('save_path', Logic.get_setting_value('save_path')) format_code = request.form.get('format_code', None) + preferedformat = request.form.get('preferedformat', None) + preferredcodec = request.form.get('preferredcodec', None) + preferredquality = request.form.get('preferredquality', '192') start = request.form.get('start', False) ret = { 'errorCode': 0, @@ -170,7 +187,19 @@ def api(sub): return Logic.abort(ret, 1) # 필수 요청 변수가 없음 if not url.startswith('http'): return Logic.abort(ret, 2) # 잘못된 동영상 주소 - youtube_dl = Youtube_dl(plugin, url, filename, temp_path, save_path, format_code) + postprocessor = [] + if preferedformat is not None: + postprocessor.append({ + 'key': 'FFmpegVideoConvertor', + 'preferedformat': preferedformat + }) + if preferredcodec is not None: + postprocessor.append({ + 'key': 'FFmpegExtractAudio', + 'preferredcodec': preferredcodec, + 'preferredquality': preferredquality + }) + youtube_dl = Youtube_dl(plugin, url, filename, temp_path, save_path, format_code, postprocessor) youtube_dl._key = key Logic.youtube_dl_list.append(youtube_dl) # 리스트 추가 ret['index'] = youtube_dl.index diff --git a/templates/youtube-dl_download.html b/templates/youtube-dl_download.html index d469e4f..1e68430 100644 --- a/templates/youtube-dl_download.html +++ b/templates/youtube-dl_download.html @@ -6,7 +6,7 @@ {{ 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_input_text('format', '동영상 포맷', desc=['포맷 지정은 https://github.com/ytdl-org/youtube-dl/blob/master/README.md#format-selection 참고', '빈칸으로 두면 최고 화질로 다운로드합니다.']) }} - + {{ macros.setting_select('postprocessor', '후처리', arg['postprocessor_list'], col='3', desc='다운로드 후 FFmpeg로 후처리합니다.') }} {{ macros.setting_button([['download_start', '다운로드']]) }} @@ -15,9 +15,26 @@ var package_name = '{{ arg["package_name"] }}'; $(function () { + // 후처리 목록 + var optgroup = null; + $('#postprocessor > option').map(function () { + var i = $(this); + if (i.val() === '_optgroup') { + if (i.text() !== '') { // optgroup 태그 열기 + optgroup = $(''); + i.before(optgroup).remove(); + } else { // optgroup 태그 닫기 + optgroup = null; + i.remove(); + } + } else if (optgroup !== null) { // optgroup 태그로 이동 + optgroup.append(i); + } + }); + // 프리셋 변경 $('#preset').change(function (e) { - if ($(this).val() == '_custom') { + if ($(this).val() === '_custom') { return; } $('#format').val($(this).val()); @@ -26,9 +43,17 @@ $('#preset').val('_custom'); }); + // 후처리 변경 + $('#postprocessor').change(function (e) { + if ($(this).find($('option[value="' + $(this).val() + '"]')).parent().attr('label') === '오디오 추출') { + $('#preset').val('bestaudio/best').change(); + } + }); + // 다운로드 $('#download_start').click(function (e) { - if ($('#url').val().startsWith('http') == false) { + var url = $('#url').val(); + if (url.startsWith('http') === false) { $.notify('URL을 입력하세요.', { type: 'warning' }); @@ -39,9 +64,10 @@ type: 'POST', cache: false, data: { - url: $('#url').val(), + url: url, filename: $('#filename').val(), - format: $('#format').val() + format: $('#format').val(), + postprocessor: $('#postprocessor').val() }, dataType: 'json', success: function (data) { diff --git a/templates/youtube-dl_list.html b/templates/youtube-dl_list.html index bb3bce8..755e805 100644 --- a/templates/youtube-dl_list.html +++ b/templates/youtube-dl_list.html @@ -51,12 +51,13 @@ data: { }, dataType: 'json', success: function (data) { - $('#list').html(''); + var list = $('#list'); + list.html(''); var str = ''; for (var i in data) { str += make_item(data[i]); } - $('#list').html(str); + list.html(str); } }); @@ -87,19 +88,19 @@ str += '' + data.title + ''; str += '' + data.status_ko + ''; var visi = 'hidden'; - if (parseInt(data.percent) > 0 && data.status_str != 'STOP') { + if (parseInt(data.percent) > 0 && data.status_str !== 'STOP') { visi = 'visible'; } str += '
' + data.percent + '%
'; str += '' + data.download_time + ''; str += ''; - 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 += ''; } str += ''; str += ''; str += ''; - str += ''; + str += ''; str += '
'; str += get_detail(data); str += '
'; @@ -114,7 +115,7 @@ str += info_html('임시폴더', data.temp_path); str += info_html('저장폴더', data.save_path); str += info_html('종료시간', data.end_time); - if (data.status_str == 'DOWNLOADING') { + if (data.status_str === 'DOWNLOADING') { str += info_html('', '현재 다운로드 중인 파일에 대한 정보'); str += info_html('파일명', data.filename); str += info_html('진행률(current/total)', data.percent + '% (' + data.downloaded_bytes_str + ' / ' + data.total_bytes_str + ')'); @@ -126,17 +127,18 @@ function info_html(left, right, option) { var str = '
'; + var link = (left === 'URL' || left === '업로더'); str += '
'; str += '' + left + ''; str += '
'; str += '
'; str += '
'; str += ''; - if (left == 'URL' || left == '업로더') { + if (link) { str += ''; } str += right; - if (left == 'URL' || left == '업로더') { + if (link) { str += ''; } str += '
';