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