youtube_live_chat.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. import json
  2. import time
  3. import urllib.error
  4. from .fragment import FragmentFD
  5. from ..utils import (
  6. RegexNotFoundError,
  7. RetryManager,
  8. dict_get,
  9. int_or_none,
  10. try_get,
  11. )
  12. class YoutubeLiveChatFD(FragmentFD):
  13. """ Downloads YouTube live chats fragment by fragment """
  14. def real_download(self, filename, info_dict):
  15. video_id = info_dict['video_id']
  16. self.to_screen('[%s] Downloading live chat' % self.FD_NAME)
  17. if not self.params.get('skip_download') and info_dict['protocol'] == 'youtube_live_chat':
  18. self.report_warning('Live chat download runs until the livestream ends. '
  19. 'If you wish to download the video simultaneously, run a separate hypervideo instance')
  20. test = self.params.get('test', False)
  21. ctx = {
  22. 'filename': filename,
  23. 'live': True,
  24. 'total_frags': None,
  25. }
  26. from ..extractor.youtube import YoutubeBaseInfoExtractor
  27. ie = YoutubeBaseInfoExtractor(self.ydl)
  28. start_time = int(time.time() * 1000)
  29. def dl_fragment(url, data=None, headers=None):
  30. http_headers = info_dict.get('http_headers', {})
  31. if headers:
  32. http_headers = http_headers.copy()
  33. http_headers.update(headers)
  34. return self._download_fragment(ctx, url, info_dict, http_headers, data)
  35. def parse_actions_replay(live_chat_continuation):
  36. offset = continuation_id = click_tracking_params = None
  37. processed_fragment = bytearray()
  38. for action in live_chat_continuation.get('actions', []):
  39. if 'replayChatItemAction' in action:
  40. replay_chat_item_action = action['replayChatItemAction']
  41. offset = int(replay_chat_item_action['videoOffsetTimeMsec'])
  42. processed_fragment.extend(
  43. json.dumps(action, ensure_ascii=False).encode() + b'\n')
  44. if offset is not None:
  45. continuation = try_get(
  46. live_chat_continuation,
  47. lambda x: x['continuations'][0]['liveChatReplayContinuationData'], dict)
  48. if continuation:
  49. continuation_id = continuation.get('continuation')
  50. click_tracking_params = continuation.get('clickTrackingParams')
  51. self._append_fragment(ctx, processed_fragment)
  52. return continuation_id, offset, click_tracking_params
  53. def try_refresh_replay_beginning(live_chat_continuation):
  54. # choose the second option that contains the unfiltered live chat replay
  55. refresh_continuation = try_get(
  56. live_chat_continuation,
  57. lambda x: x['header']['liveChatHeaderRenderer']['viewSelector']['sortFilterSubMenuRenderer']['subMenuItems'][1]['continuation']['reloadContinuationData'], dict)
  58. if refresh_continuation:
  59. # no data yet but required to call _append_fragment
  60. self._append_fragment(ctx, b'')
  61. refresh_continuation_id = refresh_continuation.get('continuation')
  62. offset = 0
  63. click_tracking_params = refresh_continuation.get('trackingParams')
  64. return refresh_continuation_id, offset, click_tracking_params
  65. return parse_actions_replay(live_chat_continuation)
  66. live_offset = 0
  67. def parse_actions_live(live_chat_continuation):
  68. nonlocal live_offset
  69. continuation_id = click_tracking_params = None
  70. processed_fragment = bytearray()
  71. for action in live_chat_continuation.get('actions', []):
  72. timestamp = self.parse_live_timestamp(action)
  73. if timestamp is not None:
  74. live_offset = timestamp - start_time
  75. # compatibility with replay format
  76. pseudo_action = {
  77. 'replayChatItemAction': {'actions': [action]},
  78. 'videoOffsetTimeMsec': str(live_offset),
  79. 'isLive': True,
  80. }
  81. processed_fragment.extend(
  82. json.dumps(pseudo_action, ensure_ascii=False).encode() + b'\n')
  83. continuation_data_getters = [
  84. lambda x: x['continuations'][0]['invalidationContinuationData'],
  85. lambda x: x['continuations'][0]['timedContinuationData'],
  86. ]
  87. continuation_data = try_get(live_chat_continuation, continuation_data_getters, dict)
  88. if continuation_data:
  89. continuation_id = continuation_data.get('continuation')
  90. click_tracking_params = continuation_data.get('clickTrackingParams')
  91. timeout_ms = int_or_none(continuation_data.get('timeoutMs'))
  92. if timeout_ms is not None:
  93. time.sleep(timeout_ms / 1000)
  94. self._append_fragment(ctx, processed_fragment)
  95. return continuation_id, live_offset, click_tracking_params
  96. def download_and_parse_fragment(url, frag_index, request_data=None, headers=None):
  97. for retry in RetryManager(self.params.get('fragment_retries'), self.report_retry, frag_index=frag_index):
  98. try:
  99. success = dl_fragment(url, request_data, headers)
  100. if not success:
  101. return False, None, None, None
  102. raw_fragment = self._read_fragment(ctx)
  103. try:
  104. data = ie.extract_yt_initial_data(video_id, raw_fragment.decode('utf-8', 'replace'))
  105. except RegexNotFoundError:
  106. data = None
  107. if not data:
  108. data = json.loads(raw_fragment)
  109. live_chat_continuation = try_get(
  110. data,
  111. lambda x: x['continuationContents']['liveChatContinuation'], dict) or {}
  112. func = (info_dict['protocol'] == 'youtube_live_chat' and parse_actions_live
  113. or frag_index == 1 and try_refresh_replay_beginning
  114. or parse_actions_replay)
  115. return (True, *func(live_chat_continuation))
  116. except urllib.error.HTTPError as err:
  117. retry.error = err
  118. continue
  119. return False, None, None, None
  120. self._prepare_and_start_frag_download(ctx, info_dict)
  121. success = dl_fragment(info_dict['url'])
  122. if not success:
  123. return False
  124. raw_fragment = self._read_fragment(ctx)
  125. try:
  126. data = ie.extract_yt_initial_data(video_id, raw_fragment.decode('utf-8', 'replace'))
  127. except RegexNotFoundError:
  128. return False
  129. continuation_id = try_get(
  130. data,
  131. lambda x: x['contents']['twoColumnWatchNextResults']['conversationBar']['liveChatRenderer']['continuations'][0]['reloadContinuationData']['continuation'])
  132. # no data yet but required to call _append_fragment
  133. self._append_fragment(ctx, b'')
  134. ytcfg = ie.extract_ytcfg(video_id, raw_fragment.decode('utf-8', 'replace'))
  135. if not ytcfg:
  136. return False
  137. api_key = try_get(ytcfg, lambda x: x['INNERTUBE_API_KEY'])
  138. innertube_context = try_get(ytcfg, lambda x: x['INNERTUBE_CONTEXT'])
  139. if not api_key or not innertube_context:
  140. return False
  141. visitor_data = try_get(innertube_context, lambda x: x['client']['visitorData'], str)
  142. if info_dict['protocol'] == 'youtube_live_chat_replay':
  143. url = 'https://www.youtube.com/youtubei/v1/live_chat/get_live_chat_replay?key=' + api_key
  144. chat_page_url = 'https://www.youtube.com/live_chat_replay?continuation=' + continuation_id
  145. elif info_dict['protocol'] == 'youtube_live_chat':
  146. url = 'https://www.youtube.com/youtubei/v1/live_chat/get_live_chat?key=' + api_key
  147. chat_page_url = 'https://www.youtube.com/live_chat?continuation=' + continuation_id
  148. frag_index = offset = 0
  149. click_tracking_params = None
  150. while continuation_id is not None:
  151. frag_index += 1
  152. request_data = {
  153. 'context': innertube_context,
  154. 'continuation': continuation_id,
  155. }
  156. if frag_index > 1:
  157. request_data['currentPlayerState'] = {'playerOffsetMs': str(max(offset - 5000, 0))}
  158. if click_tracking_params:
  159. request_data['context']['clickTracking'] = {'clickTrackingParams': click_tracking_params}
  160. headers = ie.generate_api_headers(ytcfg=ytcfg, visitor_data=visitor_data)
  161. headers.update({'content-type': 'application/json'})
  162. fragment_request_data = json.dumps(request_data, ensure_ascii=False).encode() + b'\n'
  163. success, continuation_id, offset, click_tracking_params = download_and_parse_fragment(
  164. url, frag_index, fragment_request_data, headers)
  165. else:
  166. success, continuation_id, offset, click_tracking_params = download_and_parse_fragment(
  167. chat_page_url, frag_index)
  168. if not success:
  169. return False
  170. if test:
  171. break
  172. return self._finish_frag_download(ctx, info_dict)
  173. @staticmethod
  174. def parse_live_timestamp(action):
  175. action_content = dict_get(
  176. action,
  177. ['addChatItemAction', 'addLiveChatTickerItemAction', 'addBannerToLiveChatCommand'])
  178. if not isinstance(action_content, dict):
  179. return None
  180. item = dict_get(action_content, ['item', 'bannerRenderer'])
  181. if not isinstance(item, dict):
  182. return None
  183. renderer = dict_get(item, [
  184. # text
  185. 'liveChatTextMessageRenderer', 'liveChatPaidMessageRenderer',
  186. 'liveChatMembershipItemRenderer', 'liveChatPaidStickerRenderer',
  187. # ticker
  188. 'liveChatTickerPaidMessageItemRenderer',
  189. 'liveChatTickerSponsorItemRenderer',
  190. # banner
  191. 'liveChatBannerRenderer',
  192. ])
  193. if not isinstance(renderer, dict):
  194. return None
  195. parent_item_getters = [
  196. lambda x: x['showItemEndpoint']['showLiveChatItemEndpoint']['renderer'],
  197. lambda x: x['contents'],
  198. ]
  199. parent_item = try_get(renderer, parent_item_getters, dict)
  200. if parent_item:
  201. renderer = dict_get(parent_item, [
  202. 'liveChatTextMessageRenderer', 'liveChatPaidMessageRenderer',
  203. 'liveChatMembershipItemRenderer', 'liveChatPaidStickerRenderer',
  204. ])
  205. if not isinstance(renderer, dict):
  206. return None
  207. return int_or_none(renderer.get('timestampUsec'), 1000)