niconico.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. import json
  2. import threading
  3. import time
  4. from . import get_suitable_downloader
  5. from .common import FileDownloader
  6. from .external import FFmpegFD
  7. from ..networking import Request
  8. from ..utils import DownloadError, str_or_none, try_get
  9. class NiconicoDmcFD(FileDownloader):
  10. """ Downloading niconico douga from DMC with heartbeat """
  11. def real_download(self, filename, info_dict):
  12. from ..extractor.niconico import NiconicoIE
  13. self.to_screen(f'[{self.FD_NAME}] Downloading from DMC')
  14. ie = NiconicoIE(self.ydl)
  15. info_dict, heartbeat_info_dict = ie._get_heartbeat_info(info_dict)
  16. fd = get_suitable_downloader(info_dict, params=self.params)(self.ydl, self.params)
  17. success = download_complete = False
  18. timer = [None]
  19. heartbeat_lock = threading.Lock()
  20. heartbeat_url = heartbeat_info_dict['url']
  21. heartbeat_data = heartbeat_info_dict['data'].encode()
  22. heartbeat_interval = heartbeat_info_dict.get('interval', 30)
  23. request = Request(heartbeat_url, heartbeat_data)
  24. def heartbeat():
  25. try:
  26. self.ydl.urlopen(request).read()
  27. except Exception:
  28. self.to_screen(f'[{self.FD_NAME}] Heartbeat failed')
  29. with heartbeat_lock:
  30. if not download_complete:
  31. timer[0] = threading.Timer(heartbeat_interval, heartbeat)
  32. timer[0].start()
  33. heartbeat_info_dict['ping']()
  34. self.to_screen('[%s] Heartbeat with %d second interval ...' % (self.FD_NAME, heartbeat_interval))
  35. try:
  36. heartbeat()
  37. if type(fd).__name__ == 'HlsFD':
  38. info_dict.update(ie._extract_m3u8_formats(info_dict['url'], info_dict['id'])[0])
  39. success = fd.real_download(filename, info_dict)
  40. finally:
  41. if heartbeat_lock:
  42. with heartbeat_lock:
  43. timer[0].cancel()
  44. download_complete = True
  45. return success
  46. class NiconicoLiveFD(FileDownloader):
  47. """ Downloads niconico live without being stopped """
  48. def real_download(self, filename, info_dict):
  49. video_id = info_dict['video_id']
  50. ws_url = info_dict['url']
  51. ws_extractor = info_dict['ws']
  52. ws_origin_host = info_dict['origin']
  53. live_quality = info_dict.get('live_quality', 'high')
  54. live_latency = info_dict.get('live_latency', 'high')
  55. dl = FFmpegFD(self.ydl, self.params or {})
  56. new_info_dict = info_dict.copy()
  57. new_info_dict.update({
  58. 'protocol': 'm3u8',
  59. })
  60. def communicate_ws(reconnect):
  61. if reconnect:
  62. ws = self.ydl.urlopen(Request(ws_url, headers={'Origin': f'https://{ws_origin_host}'}))
  63. if self.ydl.params.get('verbose', False):
  64. self.to_screen('[debug] Sending startWatching request')
  65. ws.send(json.dumps({
  66. 'type': 'startWatching',
  67. 'data': {
  68. 'stream': {
  69. 'quality': live_quality,
  70. 'protocol': 'hls+fmp4',
  71. 'latency': live_latency,
  72. 'chasePlay': False,
  73. },
  74. 'room': {
  75. 'protocol': 'webSocket',
  76. 'commentable': True,
  77. },
  78. 'reconnect': True,
  79. },
  80. }))
  81. else:
  82. ws = ws_extractor
  83. with ws:
  84. while True:
  85. recv = ws.recv()
  86. if not recv:
  87. continue
  88. data = json.loads(recv)
  89. if not data or not isinstance(data, dict):
  90. continue
  91. if data.get('type') == 'ping':
  92. # pong back
  93. ws.send(r'{"type":"pong"}')
  94. ws.send(r'{"type":"keepSeat"}')
  95. elif data.get('type') == 'disconnect':
  96. self.write_debug(data)
  97. return True
  98. elif data.get('type') == 'error':
  99. self.write_debug(data)
  100. message = try_get(data, lambda x: x['body']['code'], str) or recv
  101. return DownloadError(message)
  102. elif self.ydl.params.get('verbose', False):
  103. if len(recv) > 100:
  104. recv = recv[:100] + '...'
  105. self.to_screen(f'[debug] Server said: {recv}')
  106. def ws_main():
  107. reconnect = False
  108. while True:
  109. try:
  110. ret = communicate_ws(reconnect)
  111. if ret is True:
  112. return
  113. except BaseException as e:
  114. self.to_screen('[{}] {}: Connection error occured, reconnecting after 10 seconds: {}'.format('niconico:live', video_id, str_or_none(e)))
  115. time.sleep(10)
  116. continue
  117. finally:
  118. reconnect = True
  119. thread = threading.Thread(target=ws_main, daemon=True)
  120. thread.start()
  121. return dl.download(filename, new_info_dict)