Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feature] heartbeat, [niconico] fix: download video #86

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions youtube_dlc/downloader/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import random

from ..compat import compat_os_name
from ..heartbeat import Heartbeat
from ..utils import (
decodeArgument,
encodeFilename,
Expand Down Expand Up @@ -370,6 +371,12 @@ def download(self, filename, info_dict, subtitle=False):
'[download] Sleeping %s seconds...' % (
sleep_interval_sub))
time.sleep(sleep_interval_sub)

if info_dict.get('heartbeat'):
self.heartbeat = Heartbeat(self.ydl, info_dict.get('heartbeat'))
self.add_progress_hook(self.heartbeat.check_download_status)
self.heartbeat.start()

return self.real_download(filename, info_dict)

def real_download(self, filename, info_dict):
Expand Down
13 changes: 13 additions & 0 deletions youtube_dlc/extractor/niconico.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,18 @@ def yesno(boolean):
}
}).encode())

heartbeat_url = '{}/{}?_format=json&_method=PUT'.format(session_api_endpoint['url'], session_response['data']['session']['id'])
heartbeat_headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
heartbeat = {
'data': json.dumps(session_response['data']),
'headers': heartbeat_headers,
'interval': session_api_data['heartbeat_lifetime'] / 2000,
'url': heartbeat_url,
}

resolution = video_quality.get('resolution', {})

return {
Expand All @@ -264,6 +276,7 @@ def yesno(boolean):
'vbr': float_or_none(video_quality.get('bitrate'), 1000),
'height': resolution.get('height'),
'width': resolution.get('width'),
'heartbeat': heartbeat,
}

def _real_extract(self, url):
Expand Down
58 changes: 58 additions & 0 deletions youtube_dlc/heartbeat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# coding: utf-8
from __future__ import unicode_literals

import threading
import traceback

from .utils import (
compat_str,
encode_compat_str,
sanitized_Request
)


class Heartbeat(object):
def __init__(self, ydl, params):
self.ydl = ydl

data = params.get('data')
if isinstance(data, compat_str):
data = data.encode()
# Python 2 does not allow us to set HTTP method
# it is POST if Request has data, otherwise GET
self.request = sanitized_Request(
params.get('url'),
data=data,
headers=params.get('headers', {})
)

self.interval = params.get('interval', 30)
self.cancelled = False
self.parent_thread = threading.current_thread()
self.thread = threading.Thread(target=self.__heartbeat)

def start(self):
self.ydl.to_screen('[heartbeat] Heartbeat every %s seconds' % self.interval)
self.thread.start()

def cancel(self):
self.cancelled = True

def check_download_status(self, progress):
status = progress.get('status')
if status == 'finished' or status == 'error':
self.cancel()

def __heartbeat(self):
while not self.cancelled:
try:
if self.ydl.params.get('verbose'):
self.ydl.to_screen('[heartbeat]')
self.ydl.urlopen(self.request)
except Exception:
self.ydl.report_warning("Heartbeat failed")
if self.ydl.params.get('verbose'):
self.ydl.to_stderr(encode_compat_str(traceback.format_exc()))
self.parent_thread.join(self.interval)
if not self.parent_thread.is_alive():
break