niconico.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import threading
  2. from . import get_suitable_downloader
  3. from .common import FileDownloader
  4. from ..utils import sanitized_Request
  5. class NiconicoDmcFD(FileDownloader):
  6. """ Downloading niconico douga from DMC with heartbeat """
  7. def real_download(self, filename, info_dict):
  8. from ..extractor.niconico import NiconicoIE
  9. self.to_screen('[%s] Downloading from DMC' % self.FD_NAME)
  10. ie = NiconicoIE(self.ydl)
  11. info_dict, heartbeat_info_dict = ie._get_heartbeat_info(info_dict)
  12. fd = get_suitable_downloader(info_dict, params=self.params)(self.ydl, self.params)
  13. success = download_complete = False
  14. timer = [None]
  15. heartbeat_lock = threading.Lock()
  16. heartbeat_url = heartbeat_info_dict['url']
  17. heartbeat_data = heartbeat_info_dict['data'].encode()
  18. heartbeat_interval = heartbeat_info_dict.get('interval', 30)
  19. request = sanitized_Request(heartbeat_url, heartbeat_data)
  20. def heartbeat():
  21. try:
  22. self.ydl.urlopen(request).read()
  23. except Exception:
  24. self.to_screen('[%s] Heartbeat failed' % self.FD_NAME)
  25. with heartbeat_lock:
  26. if not download_complete:
  27. timer[0] = threading.Timer(heartbeat_interval, heartbeat)
  28. timer[0].start()
  29. heartbeat_info_dict['ping']()
  30. self.to_screen('[%s] Heartbeat with %d second interval ...' % (self.FD_NAME, heartbeat_interval))
  31. try:
  32. heartbeat()
  33. if type(fd).__name__ == 'HlsFD':
  34. info_dict.update(ie._extract_m3u8_formats(info_dict['url'], info_dict['id'])[0])
  35. success = fd.real_download(filename, info_dict)
  36. finally:
  37. if heartbeat_lock:
  38. with heartbeat_lock:
  39. timer[0].cancel()
  40. download_complete = True
  41. return success