twitcasting.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. import base64
  2. import itertools
  3. import re
  4. from .common import InfoExtractor
  5. from ..dependencies import websockets
  6. from ..utils import (
  7. ExtractorError,
  8. UserNotLive,
  9. clean_html,
  10. float_or_none,
  11. get_element_by_class,
  12. get_element_by_id,
  13. parse_duration,
  14. qualities,
  15. str_to_int,
  16. traverse_obj,
  17. try_get,
  18. unified_timestamp,
  19. urlencode_postdata,
  20. urljoin,
  21. )
  22. class TwitCastingIE(InfoExtractor):
  23. _VALID_URL = r'https?://(?:[^/?#]+\.)?twitcasting\.tv/(?P<uploader_id>[^/?#]+)/(?:movie|twplayer)/(?P<id>\d+)'
  24. _M3U8_HEADERS = {
  25. 'Origin': 'https://twitcasting.tv',
  26. 'Referer': 'https://twitcasting.tv/',
  27. }
  28. _TESTS = [{
  29. 'url': 'https://twitcasting.tv/ivetesangalo/movie/2357609',
  30. 'md5': '745243cad58c4681dc752490f7540d7f',
  31. 'info_dict': {
  32. 'id': '2357609',
  33. 'ext': 'mp4',
  34. 'title': 'Live #2357609',
  35. 'uploader_id': 'ivetesangalo',
  36. 'description': 'Twitter Oficial da cantora brasileira Ivete Sangalo.',
  37. 'thumbnail': r're:^https?://.*\.jpg$',
  38. 'upload_date': '20110822',
  39. 'timestamp': 1313978424,
  40. 'duration': 32,
  41. 'view_count': int,
  42. },
  43. 'params': {
  44. 'skip_download': True,
  45. },
  46. }, {
  47. 'url': 'https://twitcasting.tv/mttbernardini/movie/3689740',
  48. 'info_dict': {
  49. 'id': '3689740',
  50. 'ext': 'mp4',
  51. 'title': 'Live playing something #3689740',
  52. 'uploader_id': 'mttbernardini',
  53. 'description': 'md5:1dc7efa2f1ab932fcd119265cebeec69',
  54. 'thumbnail': r're:^https?://.*\.jpg$',
  55. 'upload_date': '20120211',
  56. 'timestamp': 1328995624,
  57. 'duration': 681,
  58. 'view_count': int,
  59. },
  60. 'params': {
  61. 'skip_download': True,
  62. 'videopassword': 'abc',
  63. },
  64. }, {
  65. 'url': 'https://twitcasting.tv/loft_heaven/movie/685979292',
  66. 'info_dict': {
  67. 'id': '685979292',
  68. 'ext': 'mp4',
  69. 'title': '【無料配信】南波一海のhear/here “ナタリー望月哲さんに聞く編集と「渋谷系狂騒曲」”',
  70. 'uploader_id': 'loft_heaven',
  71. 'description': 'md5:3a0c7b53019df987ce545c935538bacf',
  72. 'upload_date': '20210604',
  73. 'timestamp': 1622802114,
  74. 'thumbnail': r're:^https?://.*\.jpg$',
  75. 'duration': 6964,
  76. 'view_count': int,
  77. },
  78. 'params': {
  79. 'skip_download': True,
  80. },
  81. }]
  82. def _parse_data_movie_playlist(self, dmp, video_id):
  83. # attempt 1: parse as JSON directly
  84. try:
  85. return self._parse_json(dmp, video_id)
  86. except ExtractorError:
  87. pass
  88. # attempt 2: decode reversed base64
  89. decoded = base64.b64decode(dmp[::-1])
  90. return self._parse_json(decoded, video_id)
  91. def _real_extract(self, url):
  92. uploader_id, video_id = self._match_valid_url(url).groups()
  93. webpage, urlh = self._download_webpage_handle(url, video_id)
  94. video_password = self.get_param('videopassword')
  95. request_data = None
  96. if video_password:
  97. request_data = urlencode_postdata({
  98. 'password': video_password,
  99. **self._hidden_inputs(webpage),
  100. }, encoding='utf-8')
  101. webpage, urlh = self._download_webpage_handle(
  102. url, video_id, data=request_data,
  103. headers={'Origin': 'https://twitcasting.tv'},
  104. note='Trying video password')
  105. if urlh.url != url and request_data:
  106. webpage = self._download_webpage(
  107. urlh.url, video_id, data=request_data,
  108. headers={'Origin': 'https://twitcasting.tv'},
  109. note='Retrying authentication')
  110. # has to check here as the first request can contain password input form even if the password is correct
  111. if re.search(r'<form\s+method="POST">\s*<input\s+[^>]+?name="password"', webpage):
  112. raise ExtractorError('This video is protected by a password, use the --video-password option', expected=True)
  113. title = (clean_html(get_element_by_id('movietitle', webpage))
  114. or self._html_search_meta(['og:title', 'twitter:title'], webpage, fatal=True))
  115. video_js_data = try_get(
  116. webpage,
  117. lambda x: self._parse_data_movie_playlist(self._search_regex(
  118. r'data-movie-playlist=\'([^\']+?)\'',
  119. x, 'movie playlist', default=None), video_id)['2'], list)
  120. thumbnail = traverse_obj(video_js_data, (0, 'thumbnailUrl')) or self._og_search_thumbnail(webpage)
  121. description = clean_html(get_element_by_id(
  122. 'authorcomment', webpage)) or self._html_search_meta(
  123. ['description', 'og:description', 'twitter:description'], webpage)
  124. duration = (try_get(video_js_data, lambda x: sum(float_or_none(y.get('duration')) for y in x) / 1000)
  125. or parse_duration(clean_html(get_element_by_class('tw-player-duration-time', webpage))))
  126. view_count = str_to_int(self._search_regex(
  127. (r'Total\s*:\s*Views\s*([\d,]+)', r'総視聴者\s*:\s*([\d,]+)\s*</'), webpage, 'views', None))
  128. timestamp = unified_timestamp(self._search_regex(
  129. r'data-toggle="true"[^>]+datetime="([^"]+)"',
  130. webpage, 'datetime', None))
  131. stream_server_data = self._download_json(
  132. f'https://twitcasting.tv/streamserver.php?target={uploader_id}&mode=client', video_id,
  133. 'Downloading live info', fatal=False)
  134. is_live = any(f'data-{x}' in webpage for x in ['is-onlive="true"', 'live-type="live"', 'status="online"'])
  135. if not traverse_obj(stream_server_data, 'llfmp4') and is_live:
  136. self.raise_login_required(method='cookies')
  137. base_dict = {
  138. 'title': title,
  139. 'description': description,
  140. 'thumbnail': thumbnail,
  141. 'timestamp': timestamp,
  142. 'uploader_id': uploader_id,
  143. 'duration': duration,
  144. 'view_count': view_count,
  145. 'is_live': is_live,
  146. }
  147. def find_dmu(x):
  148. data_movie_url = self._search_regex(
  149. r'data-movie-url=(["\'])(?P<url>(?:(?!\1).)+)\1',
  150. x, 'm3u8 url', group='url', default=None)
  151. if data_movie_url:
  152. return [data_movie_url]
  153. m3u8_urls = (try_get(webpage, find_dmu, list)
  154. or traverse_obj(video_js_data, (..., 'source', 'url'))
  155. or ([f'https://twitcasting.tv/{uploader_id}/metastream.m3u8'] if is_live else None))
  156. if not m3u8_urls:
  157. raise ExtractorError('Failed to get m3u8 playlist')
  158. if is_live:
  159. m3u8_url = m3u8_urls[0]
  160. formats = self._extract_m3u8_formats(
  161. m3u8_url, video_id, ext='mp4', m3u8_id='hls',
  162. live=True, headers=self._M3U8_HEADERS)
  163. if traverse_obj(stream_server_data, ('hls', 'source')):
  164. formats.extend(self._extract_m3u8_formats(
  165. m3u8_url, video_id, ext='mp4', m3u8_id='source',
  166. live=True, query={'mode': 'source'},
  167. note='Downloading source quality m3u8',
  168. headers=self._M3U8_HEADERS, fatal=False))
  169. if websockets:
  170. qq = qualities(['base', 'mobilesource', 'main'])
  171. streams = traverse_obj(stream_server_data, ('llfmp4', 'streams')) or {}
  172. for mode, ws_url in streams.items():
  173. formats.append({
  174. 'url': ws_url,
  175. 'format_id': f'ws-{mode}',
  176. 'ext': 'mp4',
  177. 'quality': qq(mode),
  178. 'source_preference': -10,
  179. # TwitCasting simply sends moof atom directly over WS
  180. 'protocol': 'websocket_frag',
  181. })
  182. infodict = {
  183. 'formats': formats,
  184. '_format_sort_fields': ('source', ),
  185. }
  186. elif len(m3u8_urls) == 1:
  187. formats = self._extract_m3u8_formats(
  188. m3u8_urls[0], video_id, 'mp4', headers=self._M3U8_HEADERS)
  189. infodict = {
  190. # No problem here since there's only one manifest
  191. 'formats': formats,
  192. 'http_headers': self._M3U8_HEADERS,
  193. }
  194. else:
  195. infodict = {
  196. '_type': 'multi_video',
  197. 'entries': [{
  198. 'id': f'{video_id}-{num}',
  199. 'url': m3u8_url,
  200. 'ext': 'mp4',
  201. # Requesting the manifests here will cause download to fail.
  202. # So use ffmpeg instead. See: https://github.com/yt-dlp/yt-dlp/issues/382
  203. 'protocol': 'm3u8',
  204. 'http_headers': self._M3U8_HEADERS,
  205. **base_dict,
  206. } for (num, m3u8_url) in enumerate(m3u8_urls)],
  207. }
  208. return {
  209. 'id': video_id,
  210. **base_dict,
  211. **infodict,
  212. }
  213. class TwitCastingLiveIE(InfoExtractor):
  214. _VALID_URL = r'https?://(?:[^/?#]+\.)?twitcasting\.tv/(?P<id>[^/?#]+)/?(?:[#?]|$)'
  215. _TESTS = [{
  216. 'url': 'https://twitcasting.tv/ivetesangalo',
  217. 'only_matching': True,
  218. }, {
  219. 'url': 'https://twitcasting.tv/c:unusedlive',
  220. 'expected_exception': 'UserNotLive',
  221. }]
  222. def _real_extract(self, url):
  223. uploader_id = self._match_id(url)
  224. self.to_screen(
  225. f'Downloading live video of user {uploader_id}. '
  226. f'Pass "https://twitcasting.tv/{uploader_id}/show" to download the history')
  227. is_live = traverse_obj(self._download_json(
  228. f'https://frontendapi.twitcasting.tv/watch/user/{uploader_id}',
  229. uploader_id, 'Checking live status', data=b'', fatal=False), ('is_live', {bool}))
  230. if is_live is False: # only raise here if API response was as expected
  231. raise UserNotLive(video_id=uploader_id)
  232. # Use /show/ page so that password-protected and members-only livestreams can be found
  233. webpage = self._download_webpage(
  234. f'https://twitcasting.tv/{uploader_id}/show/', uploader_id, 'Downloading live history')
  235. is_live = is_live or self._search_regex(
  236. r'(?s)(<span\s*class="tw-movie-thumbnail2-badge"\s*data-status="live">\s*LIVE)',
  237. webpage, 'is live?', default=False)
  238. # Current live is always the first match
  239. current_live = self._search_regex(
  240. r'(?s)<a\s+class="tw-movie-thumbnail2"\s+href="/[^/"]+/movie/(?P<video_id>\d+)"',
  241. webpage, 'current live ID', default=None, group='video_id')
  242. if not is_live or not current_live:
  243. raise UserNotLive(video_id=uploader_id)
  244. return self.url_result(f'https://twitcasting.tv/{uploader_id}/movie/{current_live}', TwitCastingIE)
  245. class TwitCastingUserIE(InfoExtractor):
  246. _VALID_URL = r'https?://(?:[^/?#]+\.)?twitcasting\.tv/(?P<id>[^/?#]+)/(:?show|archive)/?(?:[#?]|$)'
  247. _TESTS = [{
  248. 'url': 'https://twitcasting.tv/natsuiromatsuri/archive/',
  249. 'info_dict': {
  250. 'id': 'natsuiromatsuri',
  251. 'title': 'natsuiromatsuri - Live History',
  252. },
  253. 'playlist_mincount': 235,
  254. }, {
  255. 'url': 'https://twitcasting.tv/noriyukicas/show',
  256. 'only_matching': True,
  257. }]
  258. def _entries(self, uploader_id):
  259. base_url = next_url = f'https://twitcasting.tv/{uploader_id}/show'
  260. for page_num in itertools.count(1):
  261. webpage = self._download_webpage(
  262. next_url, uploader_id, query={'filter': 'watchable'}, note=f'Downloading page {page_num}')
  263. matches = re.finditer(
  264. r'(?s)<a\s+class="tw-movie-thumbnail2"\s+href="(?P<url>/[^/"]+/movie/\d+)"', webpage)
  265. for mobj in matches:
  266. yield self.url_result(urljoin(base_url, mobj.group('url')))
  267. next_url = self._search_regex(
  268. r'<a href="(/%s/show/%d-\d+)[?"]' % (re.escape(uploader_id), page_num),
  269. webpage, 'next url', default=None)
  270. next_url = urljoin(base_url, next_url)
  271. if not next_url:
  272. return
  273. def _real_extract(self, url):
  274. uploader_id = self._match_id(url)
  275. return self.playlist_result(
  276. self._entries(uploader_id), uploader_id, f'{uploader_id} - Live History')