2020-10-31 22:58:53 +00:00
|
|
|
# coding: utf-8
|
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
2020-10-31 22:18:40 +00:00
|
|
|
import time
|
|
|
|
import threading
|
|
|
|
import traceback
|
|
|
|
|
|
|
|
from .utils import (
|
|
|
|
sanitized_Request
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
class Heartbeat(object):
|
|
|
|
def __init__(self, ydl, params):
|
|
|
|
self.ydl = ydl
|
|
|
|
|
|
|
|
data = params.get('data')
|
|
|
|
if type(data) is str:
|
|
|
|
data = data.encode()
|
|
|
|
self.request = sanitized_Request(
|
|
|
|
params.get('url'),
|
|
|
|
data=data,
|
|
|
|
headers=params.get('headers', {}),
|
|
|
|
method=params.get('method')
|
|
|
|
)
|
|
|
|
|
2020-10-31 22:19:57 +00:00
|
|
|
self.interval = params.get('interval', 30)
|
2020-11-01 12:23:39 +00:00
|
|
|
self.cancelled = False
|
2020-10-31 22:18:40 +00:00
|
|
|
self.thread = threading.Thread(target=self.__heartbeat, daemon=True)
|
|
|
|
|
|
|
|
def start(self):
|
|
|
|
if self.ydl.params.get('verbose'):
|
|
|
|
self.ydl.to_screen('[heartbeat] Heartbeat every %s seconds' % self.interval)
|
|
|
|
self.thread.start()
|
|
|
|
|
2020-11-01 12:23:39 +00:00
|
|
|
def cancel(self):
|
|
|
|
self.cancelled = True
|
2020-10-31 22:18:40 +00:00
|
|
|
|
|
|
|
def check_download_status(self, progress):
|
|
|
|
status = progress.get('status')
|
|
|
|
if status == 'finished' or status == 'error':
|
2020-11-01 12:23:39 +00:00
|
|
|
self.cancel()
|
2020-10-31 22:18:40 +00:00
|
|
|
|
|
|
|
def __heartbeat(self):
|
2020-11-01 12:23:39 +00:00
|
|
|
while not self.cancelled:
|
2020-10-31 22:18:40 +00:00
|
|
|
try:
|
|
|
|
if self.ydl.params.get('verbose'):
|
|
|
|
self.ydl.to_screen('[heartbeat]')
|
|
|
|
self.ydl.urlopen(self.request)
|
|
|
|
except Exception:
|
|
|
|
if self.ydl.params.get('verbose'):
|
|
|
|
traceback.print_exc()
|
|
|
|
self.ydl.to_screen("[heartbeat] Heartbeat failed")
|
|
|
|
time.sleep(self.interval)
|