twitcasting.py 12 KB

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