youtube.py 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import itertools
  4. import json
  5. import os.path
  6. import random
  7. import re
  8. import time
  9. import traceback
  10. from .common import InfoExtractor, SearchInfoExtractor
  11. from ..jsinterp import JSInterpreter
  12. from ..swfinterp import SWFInterpreter
  13. from ..compat import (
  14. compat_chr,
  15. compat_parse_qs,
  16. compat_urllib_parse,
  17. compat_urllib_parse_unquote,
  18. compat_urllib_parse_unquote_plus,
  19. compat_urllib_parse_urlparse,
  20. compat_urlparse,
  21. compat_str,
  22. )
  23. from ..utils import (
  24. clean_html,
  25. encode_dict,
  26. error_to_compat_str,
  27. ExtractorError,
  28. float_or_none,
  29. get_element_by_attribute,
  30. get_element_by_id,
  31. int_or_none,
  32. mimetype2ext,
  33. orderedSet,
  34. parse_duration,
  35. remove_quotes,
  36. remove_start,
  37. sanitized_Request,
  38. smuggle_url,
  39. str_to_int,
  40. unescapeHTML,
  41. unified_strdate,
  42. unsmuggle_url,
  43. uppercase_escape,
  44. ISO3166Utils,
  45. )
  46. class YoutubeBaseInfoExtractor(InfoExtractor):
  47. """Provide base functions for Youtube extractors"""
  48. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  49. _TWOFACTOR_URL = 'https://accounts.google.com/signin/challenge'
  50. _NETRC_MACHINE = 'youtube'
  51. # If True it will raise an error if no login info is provided
  52. _LOGIN_REQUIRED = False
  53. def _set_language(self):
  54. self._set_cookie(
  55. '.youtube.com', 'PREF', 'f1=50000000&hl=en',
  56. # YouTube sets the expire time to about two months
  57. expire_time=time.time() + 2 * 30 * 24 * 3600)
  58. def _ids_to_results(self, ids):
  59. return [
  60. self.url_result(vid_id, 'Youtube', video_id=vid_id)
  61. for vid_id in ids]
  62. def _login(self):
  63. """
  64. Attempt to log in to YouTube.
  65. True is returned if successful or skipped.
  66. False is returned if login failed.
  67. If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
  68. """
  69. (username, password) = self._get_login_info()
  70. # No authentication to be performed
  71. if username is None:
  72. if self._LOGIN_REQUIRED:
  73. raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  74. return True
  75. login_page = self._download_webpage(
  76. self._LOGIN_URL, None,
  77. note='Downloading login page',
  78. errnote='unable to fetch login page', fatal=False)
  79. if login_page is False:
  80. return
  81. galx = self._search_regex(r'(?s)<input.+?name="GALX".+?value="(.+?)"',
  82. login_page, 'Login GALX parameter')
  83. # Log in
  84. login_form_strs = {
  85. 'continue': 'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
  86. 'Email': username,
  87. 'GALX': galx,
  88. 'Passwd': password,
  89. 'PersistentCookie': 'yes',
  90. '_utf8': '霱',
  91. 'bgresponse': 'js_disabled',
  92. 'checkConnection': '',
  93. 'checkedDomains': 'youtube',
  94. 'dnConn': '',
  95. 'pstMsg': '0',
  96. 'rmShown': '1',
  97. 'secTok': '',
  98. 'signIn': 'Sign in',
  99. 'timeStmp': '',
  100. 'service': 'youtube',
  101. 'uilel': '3',
  102. 'hl': 'en_US',
  103. }
  104. login_data = compat_urllib_parse.urlencode(encode_dict(login_form_strs)).encode('ascii')
  105. req = sanitized_Request(self._LOGIN_URL, login_data)
  106. login_results = self._download_webpage(
  107. req, None,
  108. note='Logging in', errnote='unable to log in', fatal=False)
  109. if login_results is False:
  110. return False
  111. if re.search(r'id="errormsg_0_Passwd"', login_results) is not None:
  112. raise ExtractorError('Please use your account password and a two-factor code instead of an application-specific password.', expected=True)
  113. # Two-Factor
  114. # TODO add SMS and phone call support - these require making a request and then prompting the user
  115. if re.search(r'(?i)<form[^>]* id="challenge"', login_results) is not None:
  116. tfa_code = self._get_tfa_info('2-step verification code')
  117. if not tfa_code:
  118. self._downloader.report_warning(
  119. 'Two-factor authentication required. Provide it either interactively or with --twofactor <code>'
  120. '(Note that only TOTP (Google Authenticator App) codes work at this time.)')
  121. return False
  122. tfa_code = remove_start(tfa_code, 'G-')
  123. tfa_form_strs = self._form_hidden_inputs('challenge', login_results)
  124. tfa_form_strs.update({
  125. 'Pin': tfa_code,
  126. 'TrustDevice': 'on',
  127. })
  128. tfa_data = compat_urllib_parse.urlencode(encode_dict(tfa_form_strs)).encode('ascii')
  129. tfa_req = sanitized_Request(self._TWOFACTOR_URL, tfa_data)
  130. tfa_results = self._download_webpage(
  131. tfa_req, None,
  132. note='Submitting TFA code', errnote='unable to submit tfa', fatal=False)
  133. if tfa_results is False:
  134. return False
  135. if re.search(r'(?i)<form[^>]* id="challenge"', tfa_results) is not None:
  136. self._downloader.report_warning('Two-factor code expired or invalid. Please try again, or use a one-use backup code instead.')
  137. return False
  138. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', tfa_results) is not None:
  139. self._downloader.report_warning('unable to log in - did the page structure change?')
  140. return False
  141. if re.search(r'smsauth-interstitial-reviewsettings', tfa_results) is not None:
  142. self._downloader.report_warning('Your Google account has a security notice. Please log in on your web browser, resolve the notice, and try again.')
  143. return False
  144. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
  145. self._downloader.report_warning('unable to log in: bad username or password')
  146. return False
  147. return True
  148. def _real_initialize(self):
  149. if self._downloader is None:
  150. return
  151. self._set_language()
  152. if not self._login():
  153. return
  154. class YoutubeEntryListBaseInfoExtractor(YoutubeBaseInfoExtractor):
  155. # Extract entries from page with "Load more" button
  156. def _entries(self, page, playlist_id):
  157. more_widget_html = content_html = page
  158. for page_num in itertools.count(1):
  159. for entry in self._process_page(content_html):
  160. yield entry
  161. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  162. if not mobj:
  163. break
  164. more = self._download_json(
  165. 'https://youtube.com/%s' % mobj.group('more'), playlist_id,
  166. 'Downloading page #%s' % page_num,
  167. transform_source=uppercase_escape)
  168. content_html = more['content_html']
  169. if not content_html.strip():
  170. # Some webpages show a "Load more" button but they don't
  171. # have more videos
  172. break
  173. more_widget_html = more['load_more_widget_html']
  174. class YoutubePlaylistBaseInfoExtractor(YoutubeEntryListBaseInfoExtractor):
  175. def _process_page(self, content):
  176. for video_id, video_title in self.extract_videos_from_page(content):
  177. yield self.url_result(video_id, 'Youtube', video_id, video_title)
  178. def extract_videos_from_page(self, page):
  179. ids_in_page = []
  180. titles_in_page = []
  181. for mobj in re.finditer(self._VIDEO_RE, page):
  182. # The link with index 0 is not the first video of the playlist (not sure if still actual)
  183. if 'index' in mobj.groupdict() and mobj.group('id') == '0':
  184. continue
  185. video_id = mobj.group('id')
  186. video_title = unescapeHTML(mobj.group('title'))
  187. if video_title:
  188. video_title = video_title.strip()
  189. try:
  190. idx = ids_in_page.index(video_id)
  191. if video_title and not titles_in_page[idx]:
  192. titles_in_page[idx] = video_title
  193. except ValueError:
  194. ids_in_page.append(video_id)
  195. titles_in_page.append(video_title)
  196. return zip(ids_in_page, titles_in_page)
  197. class YoutubePlaylistsBaseInfoExtractor(YoutubeEntryListBaseInfoExtractor):
  198. def _process_page(self, content):
  199. for playlist_id in orderedSet(re.findall(r'href="/?playlist\?list=([0-9A-Za-z-_]{10,})"', content)):
  200. yield self.url_result(
  201. 'https://www.youtube.com/playlist?list=%s' % playlist_id, 'YoutubePlaylist')
  202. def _real_extract(self, url):
  203. playlist_id = self._match_id(url)
  204. webpage = self._download_webpage(url, playlist_id)
  205. title = self._og_search_title(webpage, fatal=False)
  206. return self.playlist_result(self._entries(webpage, playlist_id), playlist_id, title)
  207. class YoutubeIE(YoutubeBaseInfoExtractor):
  208. IE_DESC = 'YouTube.com'
  209. _VALID_URL = r"""(?x)^
  210. (
  211. (?:https?://|//) # http(s):// or protocol-independent URL
  212. (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/|
  213. (?:www\.)?deturl\.com/www\.youtube\.com/|
  214. (?:www\.)?pwnyoutube\.com/|
  215. (?:www\.)?yourepeat\.com/|
  216. tube\.majestyc\.net/|
  217. youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
  218. (?:.*?\#/)? # handle anchor (#/) redirect urls
  219. (?: # the various things that can precede the ID:
  220. (?:(?:v|embed|e)/(?!videoseries)) # v/ or embed/ or e/
  221. |(?: # or the v= param in all its forms
  222. (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  223. (?:\?|\#!?) # the params delimiter ? or # or #!
  224. (?:.*?[&;])?? # any other preceding param (like /?s=tuff&v=xxxx or ?s=tuff&amp;v=V36LpHqtcDY)
  225. v=
  226. )
  227. ))
  228. |(?:
  229. youtu\.be| # just youtu.be/xxxx
  230. vid\.plus # or vid.plus/xxxx
  231. )/
  232. |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
  233. )
  234. )? # all until now is optional -> you can pass the naked ID
  235. ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
  236. (?!.*?&list=) # combined list/video URLs are handled by the playlist IE
  237. (?(1).+)? # if we found the ID, everything can follow
  238. $"""
  239. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  240. # tbr was extracted from com/google/youtube/model/VideoFormat.as in watch_as3.swf and converted from Bytes/S to KBits/S
  241. _formats = {
  242. '5': {'ext': 'flv', 'width': 400, 'height': 240, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263', 'tbr': 320},
  243. '6': {'ext': 'flv', 'width': 450, 'height': 270, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263', 'tbr': 896},
  244. '13': {'ext': '3gp', 'acodec': 'aac', 'vcodec': 'mp4v', 'tbr': 60},
  245. '17': {'ext': '3gp', 'width': 176, 'height': 144, 'acodec': 'aac', 'abr': 24, 'vcodec': 'mp4v', 'tbr': 80},
  246. '18': {'ext': 'mp4', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 96, 'vcodec': 'h264', 'tbr': 736},
  247. '22': {'ext': 'mp4', 'width': 1280, 'height': 720, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'tbr': 3192},
  248. '34': {'ext': 'flv', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'tbr': 928},
  249. '35': {'ext': 'flv', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'tbr': 1280},
  250. # itag 36 videos are either 320x180 (BaW_jenozKc) or 320x240 (__2ABJjxzNo), abr varies as well
  251. '36': {'ext': '3gp', 'width': 320, 'acodec': 'aac', 'vcodec': 'mp4v', 'tbr': 256},
  252. '37': {'ext': 'mp4', 'width': 1920, 'height': 1080, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'tbr': 6192},
  253. '38': {'ext': 'mp4', 'width': 4096, 'height': 3072, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'tbr': 10128},
  254. '43': {'ext': 'webm', 'width': 640, 'height': 360, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8', 'tbr': 928},
  255. '44': {'ext': 'webm', 'width': 854, 'height': 480, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8', 'tbr': 1280},
  256. '45': {'ext': 'webm', 'width': 1280, 'height': 720, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'tbr': 3192},
  257. '46': {'ext': 'webm', 'width': 1920, 'height': 1080, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
  258. '59': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'tbr': 1280},
  259. '78': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'tbr': 1280},
  260. # 3D videos
  261. '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20, 'tbr': 800},
  262. '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20, 'tbr': 1152},
  263. '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20, 'tbr': 3000},
  264. '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20, 'tbr': 6000},
  265. '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8', 'preference': -20},
  266. '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
  267. '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
  268. # Apple HTTP Live Streaming
  269. '91': {'format_note': 'HLS', 'tbr': 98.4375},
  270. '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10, 'tbr': 186.625},
  271. '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10, 'tbr': 951.5625},
  272. '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10, 'tbr': 1312.5},
  273. '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10, 'tbr': 3207.421875},
  274. '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10, 'tbr': 6349.21875},
  275. '97': {'format_note': 'HLS', 'tbr': 10128},
  276. '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  277. '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 24, 'vcodec': 'h264', 'preference': -10},
  278. # DASH mp4 video
  279. '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'h264', 'preference': -40, 'tbr': 261.71875},
  280. '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'h264', 'preference': -40, 'tbr': 951.5625},
  281. '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264', 'preference': -40, 'tbr': 1312.5},
  282. '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264', 'preference': -40, 'tbr': 3207.421875},
  283. '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264', 'preference': -40, 'tbr': 6349.21875},
  284. '138': {'ext': 'mp4', 'format_note': 'DASH video', 'vcodec': 'h264', 'preference': -40, 'tbr': 10128.0}, # Height can vary (https://github.com/rg3/youtube-dl/issues/4559)
  285. '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'vcodec': 'h264', 'preference': -40, 'tbr': 91.796875},
  286. '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'h264', 'preference': -40},
  287. '298': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60, 'preference': -40},
  288. '299': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60, 'preference': -40},
  289. '266': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'h264', 'preference': -40},
  290. # Dash mp4 audio
  291. '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 48, 'preference': -50, 'container': 'm4a_dash', 'tbr': 32},
  292. '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 128, 'preference': -50, 'container': 'm4a_dash', 'tbr': 128},
  293. '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 256, 'preference': -50, 'container': 'm4a_dash', 'tbr': 320},
  294. # Dash webm
  295. '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  296. '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  297. '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  298. '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  299. '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  300. '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  301. '278': {'ext': 'webm', 'height': 144, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp9', 'preference': -40},
  302. '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'vp9', 'preference': -40},
  303. '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'vp9', 'preference': -40},
  304. '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9', 'preference': -40},
  305. '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9', 'preference': -40},
  306. '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9', 'preference': -40},
  307. '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9', 'preference': -40},
  308. '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9', 'preference': -40},
  309. '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9', 'preference': -40},
  310. # itag 272 videos are either 3840x2160 (e.g. RtoitU2A-3E) or 7680x4320 (sLprVF6d7Ug)
  311. '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'preference': -40},
  312. '302': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60, 'preference': -40},
  313. '303': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60, 'preference': -40},
  314. '308': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60, 'preference': -40},
  315. '313': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'preference': -40},
  316. '315': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60, 'preference': -40},
  317. # Dash webm audio
  318. '171': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 128, 'preference': -50},
  319. '172': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 256, 'preference': -50},
  320. # Dash webm audio with opus inside
  321. '249': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 50, 'preference': -50},
  322. '250': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 70, 'preference': -50},
  323. '251': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 160, 'preference': -50},
  324. # RTMP (unnamed)
  325. '_rtmp': {'protocol': 'rtmp'},
  326. # formats extracted from com/google/youtube/model/VideoFormat.as in watch_as3.swf
  327. '20': {'tbr': 24000},
  328. '23': {'tbr': 62.5},
  329. '24': {'tbr': 125},
  330. '25': {'tbr': 312.5},
  331. '33': {'tbr': 132},
  332. '40': {'tbr': 40},
  333. '61': {'tbr': 928},
  334. '62': {'tbr': 1280},
  335. '63': {'tbr': 3192},
  336. '64': {'tbr': 6192},
  337. '65': {'tbr': 10128},
  338. '81': {'ext': 'mp4', 'tbr': 928},
  339. '88': {'tbr': 7192},
  340. '98': {'tbr': 320},
  341. '119': {'ext': 'mp4', 'tbr': 320},
  342. '304': {'format_note': 'DASH'},
  343. '305': {'format_note': 'DASH'},
  344. }
  345. _SUBTITLE_FORMATS = ('ttml', 'vtt')
  346. IE_NAME = 'youtube'
  347. _TESTS = [
  348. {
  349. 'url': 'http://www.youtube.com/watch?v=BaW_jenozKc&t=1s&end=9',
  350. 'info_dict': {
  351. 'id': 'BaW_jenozKc',
  352. 'ext': 'mp4',
  353. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  354. 'uploader': 'Philipp Hagemeister',
  355. 'uploader_id': 'phihag',
  356. 'upload_date': '20121002',
  357. 'description': 'test chars: "\'/\\ä↭𝕐\ntest URL: https://github.com/rg3/youtube-dl/issues/1892\n\nThis is a test video for youtube-dl.\n\nFor more information, contact phihag@phihag.de .',
  358. 'categories': ['Science & Technology'],
  359. 'tags': ['youtube-dl'],
  360. 'like_count': int,
  361. 'dislike_count': int,
  362. 'start_time': 1,
  363. 'end_time': 9,
  364. }
  365. },
  366. {
  367. 'url': 'http://www.youtube.com/watch?v=UxxajLWwzqY',
  368. 'note': 'Test generic use_cipher_signature video (#897)',
  369. 'info_dict': {
  370. 'id': 'UxxajLWwzqY',
  371. 'ext': 'mp4',
  372. 'upload_date': '20120506',
  373. 'title': 'Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]',
  374. 'alt_title': 'I Love It (feat. Charli XCX)',
  375. 'description': 'md5:782e8651347686cba06e58f71ab51773',
  376. 'tags': ['Icona Pop i love it', 'sweden', 'pop music', 'big beat records', 'big beat', 'charli',
  377. 'xcx', 'charli xcx', 'girls', 'hbo', 'i love it', "i don't care", 'icona', 'pop',
  378. 'iconic ep', 'iconic', 'love', 'it'],
  379. 'uploader': 'Icona Pop',
  380. 'uploader_id': 'IconaPop',
  381. 'creator': 'Icona Pop',
  382. }
  383. },
  384. {
  385. 'url': 'https://www.youtube.com/watch?v=07FYdnEawAQ',
  386. 'note': 'Test VEVO video with age protection (#956)',
  387. 'info_dict': {
  388. 'id': '07FYdnEawAQ',
  389. 'ext': 'mp4',
  390. 'upload_date': '20130703',
  391. 'title': 'Justin Timberlake - Tunnel Vision (Explicit)',
  392. 'alt_title': 'Tunnel Vision',
  393. 'description': 'md5:64249768eec3bc4276236606ea996373',
  394. 'uploader': 'justintimberlakeVEVO',
  395. 'uploader_id': 'justintimberlakeVEVO',
  396. 'creator': 'Justin Timberlake',
  397. 'age_limit': 18,
  398. }
  399. },
  400. {
  401. 'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
  402. 'note': 'Embed-only video (#1746)',
  403. 'info_dict': {
  404. 'id': 'yZIXLfi8CZQ',
  405. 'ext': 'mp4',
  406. 'upload_date': '20120608',
  407. 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
  408. 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
  409. 'uploader': 'SET India',
  410. 'uploader_id': 'setindia',
  411. 'age_limit': 18,
  412. }
  413. },
  414. {
  415. 'url': 'http://www.youtube.com/watch?v=BaW_jenozKc&v=UxxajLWwzqY',
  416. 'note': 'Use the first video ID in the URL',
  417. 'info_dict': {
  418. 'id': 'BaW_jenozKc',
  419. 'ext': 'mp4',
  420. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  421. 'uploader': 'Philipp Hagemeister',
  422. 'uploader_id': 'phihag',
  423. 'upload_date': '20121002',
  424. 'description': 'test chars: "\'/\\ä↭𝕐\ntest URL: https://github.com/rg3/youtube-dl/issues/1892\n\nThis is a test video for youtube-dl.\n\nFor more information, contact phihag@phihag.de .',
  425. 'categories': ['Science & Technology'],
  426. 'tags': ['youtube-dl'],
  427. 'like_count': int,
  428. 'dislike_count': int,
  429. },
  430. 'params': {
  431. 'skip_download': True,
  432. },
  433. },
  434. {
  435. 'url': 'http://www.youtube.com/watch?v=a9LDPn-MO4I',
  436. 'note': '256k DASH audio (format 141) via DASH manifest',
  437. 'info_dict': {
  438. 'id': 'a9LDPn-MO4I',
  439. 'ext': 'm4a',
  440. 'upload_date': '20121002',
  441. 'uploader_id': '8KVIDEO',
  442. 'description': '',
  443. 'uploader': '8KVIDEO',
  444. 'title': 'UHDTV TEST 8K VIDEO.mp4'
  445. },
  446. 'params': {
  447. 'youtube_include_dash_manifest': True,
  448. 'format': '141',
  449. },
  450. },
  451. # DASH manifest with encrypted signature
  452. {
  453. 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
  454. 'info_dict': {
  455. 'id': 'IB3lcPjvWLA',
  456. 'ext': 'm4a',
  457. 'title': 'Afrojack, Spree Wilson - The Spark ft. Spree Wilson',
  458. 'description': 'md5:12e7067fa6735a77bdcbb58cb1187d2d',
  459. 'uploader': 'AfrojackVEVO',
  460. 'uploader_id': 'AfrojackVEVO',
  461. 'upload_date': '20131011',
  462. },
  463. 'params': {
  464. 'youtube_include_dash_manifest': True,
  465. 'format': '141',
  466. },
  467. },
  468. # JS player signature function name containing $
  469. {
  470. 'url': 'https://www.youtube.com/watch?v=nfWlot6h_JM',
  471. 'info_dict': {
  472. 'id': 'nfWlot6h_JM',
  473. 'ext': 'm4a',
  474. 'title': 'Taylor Swift - Shake It Off',
  475. 'alt_title': 'Shake It Off',
  476. 'description': 'md5:95f66187cd7c8b2c13eb78e1223b63c3',
  477. 'uploader': 'TaylorSwiftVEVO',
  478. 'uploader_id': 'TaylorSwiftVEVO',
  479. 'upload_date': '20140818',
  480. 'creator': 'Taylor Swift',
  481. },
  482. 'params': {
  483. 'youtube_include_dash_manifest': True,
  484. 'format': '141',
  485. },
  486. },
  487. # Controversy video
  488. {
  489. 'url': 'https://www.youtube.com/watch?v=T4XJQO3qol8',
  490. 'info_dict': {
  491. 'id': 'T4XJQO3qol8',
  492. 'ext': 'mp4',
  493. 'upload_date': '20100909',
  494. 'uploader': 'The Amazing Atheist',
  495. 'uploader_id': 'TheAmazingAtheist',
  496. 'title': 'Burning Everyone\'s Koran',
  497. 'description': 'SUBSCRIBE: http://www.youtube.com/saturninefilms\n\nEven Obama has taken a stand against freedom on this issue: http://www.huffingtonpost.com/2010/09/09/obama-gma-interview-quran_n_710282.html',
  498. }
  499. },
  500. # Normal age-gate video (No vevo, embed allowed)
  501. {
  502. 'url': 'http://youtube.com/watch?v=HtVdAasjOgU',
  503. 'info_dict': {
  504. 'id': 'HtVdAasjOgU',
  505. 'ext': 'mp4',
  506. 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
  507. 'description': 're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
  508. 'uploader': 'The Witcher',
  509. 'uploader_id': 'WitcherGame',
  510. 'upload_date': '20140605',
  511. 'age_limit': 18,
  512. },
  513. },
  514. # Age-gate video with encrypted signature
  515. {
  516. 'url': 'http://www.youtube.com/watch?v=6kLq3WMV1nU',
  517. 'info_dict': {
  518. 'id': '6kLq3WMV1nU',
  519. 'ext': 'mp4',
  520. 'title': 'Dedication To My Ex (Miss That) (Lyric Video)',
  521. 'description': 'md5:33765bb339e1b47e7e72b5490139bb41',
  522. 'uploader': 'LloydVEVO',
  523. 'uploader_id': 'LloydVEVO',
  524. 'upload_date': '20110629',
  525. 'age_limit': 18,
  526. },
  527. },
  528. # video_info is None (https://github.com/rg3/youtube-dl/issues/4421)
  529. {
  530. 'url': '__2ABJjxzNo',
  531. 'info_dict': {
  532. 'id': '__2ABJjxzNo',
  533. 'ext': 'mp4',
  534. 'upload_date': '20100430',
  535. 'uploader_id': 'deadmau5',
  536. 'creator': 'deadmau5',
  537. 'description': 'md5:12c56784b8032162bb936a5f76d55360',
  538. 'uploader': 'deadmau5',
  539. 'title': 'Deadmau5 - Some Chords (HD)',
  540. 'alt_title': 'Some Chords',
  541. },
  542. 'expected_warnings': [
  543. 'DASH manifest missing',
  544. ]
  545. },
  546. # Olympics (https://github.com/rg3/youtube-dl/issues/4431)
  547. {
  548. 'url': 'lqQg6PlCWgI',
  549. 'info_dict': {
  550. 'id': 'lqQg6PlCWgI',
  551. 'ext': 'mp4',
  552. 'upload_date': '20150827',
  553. 'uploader_id': 'olympic',
  554. 'description': 'HO09 - Women - GER-AUS - Hockey - 31 July 2012 - London 2012 Olympic Games',
  555. 'uploader': 'Olympics',
  556. 'title': 'Hockey - Women - GER-AUS - London 2012 Olympic Games',
  557. },
  558. 'params': {
  559. 'skip_download': 'requires avconv',
  560. }
  561. },
  562. # Non-square pixels
  563. {
  564. 'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
  565. 'info_dict': {
  566. 'id': '_b-2C3KPAM0',
  567. 'ext': 'mp4',
  568. 'stretched_ratio': 16 / 9.,
  569. 'upload_date': '20110310',
  570. 'uploader_id': 'AllenMeow',
  571. 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
  572. 'uploader': '孫艾倫',
  573. 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
  574. },
  575. },
  576. # url_encoded_fmt_stream_map is empty string
  577. {
  578. 'url': 'qEJwOuvDf7I',
  579. 'info_dict': {
  580. 'id': 'qEJwOuvDf7I',
  581. 'ext': 'webm',
  582. 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
  583. 'description': '',
  584. 'upload_date': '20150404',
  585. 'uploader_id': 'spbelect',
  586. 'uploader': 'Наблюдатели Петербурга',
  587. },
  588. 'params': {
  589. 'skip_download': 'requires avconv',
  590. },
  591. 'skip': 'This live event has ended.',
  592. },
  593. # Extraction from multiple DASH manifests (https://github.com/rg3/youtube-dl/pull/6097)
  594. {
  595. 'url': 'https://www.youtube.com/watch?v=FIl7x6_3R5Y',
  596. 'info_dict': {
  597. 'id': 'FIl7x6_3R5Y',
  598. 'ext': 'mp4',
  599. 'title': 'md5:7b81415841e02ecd4313668cde88737a',
  600. 'description': 'md5:116377fd2963b81ec4ce64b542173306',
  601. 'upload_date': '20150625',
  602. 'uploader_id': 'dorappi2000',
  603. 'uploader': 'dorappi2000',
  604. 'formats': 'mincount:33',
  605. },
  606. },
  607. # DASH manifest with segment_list
  608. {
  609. 'url': 'https://www.youtube.com/embed/CsmdDsKjzN8',
  610. 'md5': '8ce563a1d667b599d21064e982ab9e31',
  611. 'info_dict': {
  612. 'id': 'CsmdDsKjzN8',
  613. 'ext': 'mp4',
  614. 'upload_date': '20150501', # According to '<meta itemprop="datePublished"', but in other places it's 20150510
  615. 'uploader': 'Airtek',
  616. 'description': 'Retransmisión en directo de la XVIII media maratón de Zaragoza.',
  617. 'uploader_id': 'UCzTzUmjXxxacNnL8I3m4LnQ',
  618. 'title': 'Retransmisión XVIII Media maratón Zaragoza 2015',
  619. },
  620. 'params': {
  621. 'youtube_include_dash_manifest': True,
  622. 'format': '135', # bestvideo
  623. }
  624. },
  625. {
  626. # Multifeed videos (multiple cameras), URL is for Main Camera
  627. 'url': 'https://www.youtube.com/watch?v=jqWvoWXjCVs',
  628. 'info_dict': {
  629. 'id': 'jqWvoWXjCVs',
  630. 'title': 'teamPGP: Rocket League Noob Stream',
  631. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  632. },
  633. 'playlist': [{
  634. 'info_dict': {
  635. 'id': 'jqWvoWXjCVs',
  636. 'ext': 'mp4',
  637. 'title': 'teamPGP: Rocket League Noob Stream (Main Camera)',
  638. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  639. 'upload_date': '20150721',
  640. 'uploader': 'Beer Games Beer',
  641. 'uploader_id': 'beergamesbeer',
  642. },
  643. }, {
  644. 'info_dict': {
  645. 'id': '6h8e8xoXJzg',
  646. 'ext': 'mp4',
  647. 'title': 'teamPGP: Rocket League Noob Stream (kreestuh)',
  648. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  649. 'upload_date': '20150721',
  650. 'uploader': 'Beer Games Beer',
  651. 'uploader_id': 'beergamesbeer',
  652. },
  653. }, {
  654. 'info_dict': {
  655. 'id': 'PUOgX5z9xZw',
  656. 'ext': 'mp4',
  657. 'title': 'teamPGP: Rocket League Noob Stream (grizzle)',
  658. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  659. 'upload_date': '20150721',
  660. 'uploader': 'Beer Games Beer',
  661. 'uploader_id': 'beergamesbeer',
  662. },
  663. }, {
  664. 'info_dict': {
  665. 'id': 'teuwxikvS5k',
  666. 'ext': 'mp4',
  667. 'title': 'teamPGP: Rocket League Noob Stream (zim)',
  668. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  669. 'upload_date': '20150721',
  670. 'uploader': 'Beer Games Beer',
  671. 'uploader_id': 'beergamesbeer',
  672. },
  673. }],
  674. 'params': {
  675. 'skip_download': True,
  676. },
  677. },
  678. {
  679. # Multifeed video with comma in title (see https://github.com/rg3/youtube-dl/issues/8536)
  680. 'url': 'https://www.youtube.com/watch?v=gVfLd0zydlo',
  681. 'info_dict': {
  682. 'id': 'gVfLd0zydlo',
  683. 'title': 'DevConf.cz 2016 Day 2 Workshops 1 14:00 - 15:30',
  684. },
  685. 'playlist_count': 2,
  686. },
  687. {
  688. 'url': 'http://vid.plus/FlRa-iH7PGw',
  689. 'only_matching': True,
  690. },
  691. {
  692. # Title with JS-like syntax "};" (see https://github.com/rg3/youtube-dl/issues/7468)
  693. # Also tests cut-off URL expansion in video description (see
  694. # https://github.com/rg3/youtube-dl/issues/1892,
  695. # https://github.com/rg3/youtube-dl/issues/8164)
  696. 'url': 'https://www.youtube.com/watch?v=lsguqyKfVQg',
  697. 'info_dict': {
  698. 'id': 'lsguqyKfVQg',
  699. 'ext': 'mp4',
  700. 'title': '{dark walk}; Loki/AC/Dishonored; collab w/Elflover21',
  701. 'alt_title': 'Dark Walk',
  702. 'description': 'md5:8085699c11dc3f597ce0410b0dcbb34a',
  703. 'upload_date': '20151119',
  704. 'uploader_id': 'IronSoulElf',
  705. 'uploader': 'IronSoulElf',
  706. 'creator': 'Todd Haberman, Daniel Law Heath & Aaron Kaplan',
  707. },
  708. 'params': {
  709. 'skip_download': True,
  710. },
  711. },
  712. {
  713. # Tags with '};' (see https://github.com/rg3/youtube-dl/issues/7468)
  714. 'url': 'https://www.youtube.com/watch?v=Ms7iBXnlUO8',
  715. 'only_matching': True,
  716. },
  717. {
  718. # Video with yt:stretch=17:0
  719. 'url': 'https://www.youtube.com/watch?v=Q39EVAstoRM',
  720. 'info_dict': {
  721. 'id': 'Q39EVAstoRM',
  722. 'ext': 'mp4',
  723. 'title': 'Clash Of Clans#14 Dicas De Ataque Para CV 4',
  724. 'description': 'md5:ee18a25c350637c8faff806845bddee9',
  725. 'upload_date': '20151107',
  726. 'uploader_id': 'UCCr7TALkRbo3EtFzETQF1LA',
  727. 'uploader': 'CH GAMER DROID',
  728. },
  729. 'params': {
  730. 'skip_download': True,
  731. },
  732. },
  733. {
  734. 'url': 'https://www.youtube.com/watch?feature=player_embedded&amp;amp;v=V36LpHqtcDY',
  735. 'only_matching': True,
  736. }
  737. ]
  738. def __init__(self, *args, **kwargs):
  739. super(YoutubeIE, self).__init__(*args, **kwargs)
  740. self._player_cache = {}
  741. def report_video_info_webpage_download(self, video_id):
  742. """Report attempt to download video info webpage."""
  743. self.to_screen('%s: Downloading video info webpage' % video_id)
  744. def report_information_extraction(self, video_id):
  745. """Report attempt to extract video information."""
  746. self.to_screen('%s: Extracting video information' % video_id)
  747. def report_unavailable_format(self, video_id, format):
  748. """Report extracted video URL."""
  749. self.to_screen('%s: Format %s not available' % (video_id, format))
  750. def report_rtmp_download(self):
  751. """Indicate the download will use the RTMP protocol."""
  752. self.to_screen('RTMP download detected')
  753. def _signature_cache_id(self, example_sig):
  754. """ Return a string representation of a signature """
  755. return '.'.join(compat_str(len(part)) for part in example_sig.split('.'))
  756. def _extract_signature_function(self, video_id, player_url, example_sig):
  757. id_m = re.match(
  758. r'.*?-(?P<id>[a-zA-Z0-9_-]+)(?:/watch_as3|/html5player(?:-new)?|/base)?\.(?P<ext>[a-z]+)$',
  759. player_url)
  760. if not id_m:
  761. raise ExtractorError('Cannot identify player %r' % player_url)
  762. player_type = id_m.group('ext')
  763. player_id = id_m.group('id')
  764. # Read from filesystem cache
  765. func_id = '%s_%s_%s' % (
  766. player_type, player_id, self._signature_cache_id(example_sig))
  767. assert os.path.basename(func_id) == func_id
  768. cache_spec = self._downloader.cache.load('youtube-sigfuncs', func_id)
  769. if cache_spec is not None:
  770. return lambda s: ''.join(s[i] for i in cache_spec)
  771. download_note = (
  772. 'Downloading player %s' % player_url
  773. if self._downloader.params.get('verbose') else
  774. 'Downloading %s player %s' % (player_type, player_id)
  775. )
  776. if player_type == 'js':
  777. code = self._download_webpage(
  778. player_url, video_id,
  779. note=download_note,
  780. errnote='Download of %s failed' % player_url)
  781. res = self._parse_sig_js(code)
  782. elif player_type == 'swf':
  783. urlh = self._request_webpage(
  784. player_url, video_id,
  785. note=download_note,
  786. errnote='Download of %s failed' % player_url)
  787. code = urlh.read()
  788. res = self._parse_sig_swf(code)
  789. else:
  790. assert False, 'Invalid player type %r' % player_type
  791. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  792. cache_res = res(test_string)
  793. cache_spec = [ord(c) for c in cache_res]
  794. self._downloader.cache.store('youtube-sigfuncs', func_id, cache_spec)
  795. return res
  796. def _print_sig_code(self, func, example_sig):
  797. def gen_sig_code(idxs):
  798. def _genslice(start, end, step):
  799. starts = '' if start == 0 else str(start)
  800. ends = (':%d' % (end + step)) if end + step >= 0 else ':'
  801. steps = '' if step == 1 else (':%d' % step)
  802. return 's[%s%s%s]' % (starts, ends, steps)
  803. step = None
  804. # Quelch pyflakes warnings - start will be set when step is set
  805. start = '(Never used)'
  806. for i, prev in zip(idxs[1:], idxs[:-1]):
  807. if step is not None:
  808. if i - prev == step:
  809. continue
  810. yield _genslice(start, prev, step)
  811. step = None
  812. continue
  813. if i - prev in [-1, 1]:
  814. step = i - prev
  815. start = prev
  816. continue
  817. else:
  818. yield 's[%d]' % prev
  819. if step is None:
  820. yield 's[%d]' % i
  821. else:
  822. yield _genslice(start, i, step)
  823. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  824. cache_res = func(test_string)
  825. cache_spec = [ord(c) for c in cache_res]
  826. expr_code = ' + '.join(gen_sig_code(cache_spec))
  827. signature_id_tuple = '(%s)' % (
  828. ', '.join(compat_str(len(p)) for p in example_sig.split('.')))
  829. code = ('if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
  830. ' return %s\n') % (signature_id_tuple, expr_code)
  831. self.to_screen('Extracted signature function:\n' + code)
  832. def _parse_sig_js(self, jscode):
  833. funcname = self._search_regex(
  834. r'\.sig\|\|([a-zA-Z0-9$]+)\(', jscode,
  835. 'Initial JS player signature function name')
  836. jsi = JSInterpreter(jscode)
  837. initial_function = jsi.extract_function(funcname)
  838. return lambda s: initial_function([s])
  839. def _parse_sig_swf(self, file_contents):
  840. swfi = SWFInterpreter(file_contents)
  841. TARGET_CLASSNAME = 'SignatureDecipher'
  842. searched_class = swfi.extract_class(TARGET_CLASSNAME)
  843. initial_function = swfi.extract_function(searched_class, 'decipher')
  844. return lambda s: initial_function([s])
  845. def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
  846. """Turn the encrypted s field into a working signature"""
  847. if player_url is None:
  848. raise ExtractorError('Cannot decrypt signature without player_url')
  849. if player_url.startswith('//'):
  850. player_url = 'https:' + player_url
  851. try:
  852. player_id = (player_url, self._signature_cache_id(s))
  853. if player_id not in self._player_cache:
  854. func = self._extract_signature_function(
  855. video_id, player_url, s
  856. )
  857. self._player_cache[player_id] = func
  858. func = self._player_cache[player_id]
  859. if self._downloader.params.get('youtube_print_sig_code'):
  860. self._print_sig_code(func, s)
  861. return func(s)
  862. except Exception as e:
  863. tb = traceback.format_exc()
  864. raise ExtractorError(
  865. 'Signature extraction failed: ' + tb, cause=e)
  866. def _get_subtitles(self, video_id, webpage):
  867. try:
  868. subs_doc = self._download_xml(
  869. 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  870. video_id, note=False)
  871. except ExtractorError as err:
  872. self._downloader.report_warning('unable to download video subtitles: %s' % error_to_compat_str(err))
  873. return {}
  874. sub_lang_list = {}
  875. for track in subs_doc.findall('track'):
  876. lang = track.attrib['lang_code']
  877. if lang in sub_lang_list:
  878. continue
  879. sub_formats = []
  880. for ext in self._SUBTITLE_FORMATS:
  881. params = compat_urllib_parse.urlencode({
  882. 'lang': lang,
  883. 'v': video_id,
  884. 'fmt': ext,
  885. 'name': track.attrib['name'].encode('utf-8'),
  886. })
  887. sub_formats.append({
  888. 'url': 'https://www.youtube.com/api/timedtext?' + params,
  889. 'ext': ext,
  890. })
  891. sub_lang_list[lang] = sub_formats
  892. if not sub_lang_list:
  893. self._downloader.report_warning('video doesn\'t have subtitles')
  894. return {}
  895. return sub_lang_list
  896. def _get_ytplayer_config(self, video_id, webpage):
  897. patterns = (
  898. # User data may contain arbitrary character sequences that may affect
  899. # JSON extraction with regex, e.g. when '};' is contained the second
  900. # regex won't capture the whole JSON. Yet working around by trying more
  901. # concrete regex first keeping in mind proper quoted string handling
  902. # to be implemented in future that will replace this workaround (see
  903. # https://github.com/rg3/youtube-dl/issues/7468,
  904. # https://github.com/rg3/youtube-dl/pull/7599)
  905. r';ytplayer\.config\s*=\s*({.+?});ytplayer',
  906. r';ytplayer\.config\s*=\s*({.+?});',
  907. )
  908. config = self._search_regex(
  909. patterns, webpage, 'ytplayer.config', default=None)
  910. if config:
  911. return self._parse_json(
  912. uppercase_escape(config), video_id, fatal=False)
  913. def _get_automatic_captions(self, video_id, webpage):
  914. """We need the webpage for getting the captions url, pass it as an
  915. argument to speed up the process."""
  916. self.to_screen('%s: Looking for automatic captions' % video_id)
  917. player_config = self._get_ytplayer_config(video_id, webpage)
  918. err_msg = 'Couldn\'t find automatic captions for %s' % video_id
  919. if not player_config:
  920. self._downloader.report_warning(err_msg)
  921. return {}
  922. try:
  923. args = player_config['args']
  924. caption_url = args.get('ttsurl')
  925. if caption_url:
  926. timestamp = args['timestamp']
  927. # We get the available subtitles
  928. list_params = compat_urllib_parse.urlencode({
  929. 'type': 'list',
  930. 'tlangs': 1,
  931. 'asrs': 1,
  932. })
  933. list_url = caption_url + '&' + list_params
  934. caption_list = self._download_xml(list_url, video_id)
  935. original_lang_node = caption_list.find('track')
  936. if original_lang_node is None:
  937. self._downloader.report_warning('Video doesn\'t have automatic captions')
  938. return {}
  939. original_lang = original_lang_node.attrib['lang_code']
  940. caption_kind = original_lang_node.attrib.get('kind', '')
  941. sub_lang_list = {}
  942. for lang_node in caption_list.findall('target'):
  943. sub_lang = lang_node.attrib['lang_code']
  944. sub_formats = []
  945. for ext in self._SUBTITLE_FORMATS:
  946. params = compat_urllib_parse.urlencode({
  947. 'lang': original_lang,
  948. 'tlang': sub_lang,
  949. 'fmt': ext,
  950. 'ts': timestamp,
  951. 'kind': caption_kind,
  952. })
  953. sub_formats.append({
  954. 'url': caption_url + '&' + params,
  955. 'ext': ext,
  956. })
  957. sub_lang_list[sub_lang] = sub_formats
  958. return sub_lang_list
  959. # Some videos don't provide ttsurl but rather caption_tracks and
  960. # caption_translation_languages (e.g. 20LmZk1hakA)
  961. caption_tracks = args['caption_tracks']
  962. caption_translation_languages = args['caption_translation_languages']
  963. caption_url = compat_parse_qs(caption_tracks.split(',')[0])['u'][0]
  964. parsed_caption_url = compat_urlparse.urlparse(caption_url)
  965. caption_qs = compat_parse_qs(parsed_caption_url.query)
  966. sub_lang_list = {}
  967. for lang in caption_translation_languages.split(','):
  968. lang_qs = compat_parse_qs(compat_urllib_parse_unquote_plus(lang))
  969. sub_lang = lang_qs.get('lc', [None])[0]
  970. if not sub_lang:
  971. continue
  972. sub_formats = []
  973. for ext in self._SUBTITLE_FORMATS:
  974. caption_qs.update({
  975. 'tlang': [sub_lang],
  976. 'fmt': [ext],
  977. })
  978. sub_url = compat_urlparse.urlunparse(parsed_caption_url._replace(
  979. query=compat_urllib_parse.urlencode(caption_qs, True)))
  980. sub_formats.append({
  981. 'url': sub_url,
  982. 'ext': ext,
  983. })
  984. sub_lang_list[sub_lang] = sub_formats
  985. return sub_lang_list
  986. # An extractor error can be raise by the download process if there are
  987. # no automatic captions but there are subtitles
  988. except (KeyError, ExtractorError):
  989. self._downloader.report_warning(err_msg)
  990. return {}
  991. def _mark_watched(self, video_id, video_info):
  992. playback_url = video_info.get('videostats_playback_base_url', [None])[0]
  993. if not playback_url:
  994. return
  995. parsed_playback_url = compat_urlparse.urlparse(playback_url)
  996. qs = compat_urlparse.parse_qs(parsed_playback_url.query)
  997. # cpn generation algorithm is reverse engineered from base.js.
  998. # In fact it works even with dummy cpn.
  999. CPN_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'
  1000. cpn = ''.join((CPN_ALPHABET[random.randint(0, 256) & 63] for _ in range(0, 16)))
  1001. qs.update({
  1002. 'ver': ['2'],
  1003. 'cpn': [cpn],
  1004. })
  1005. playback_url = compat_urlparse.urlunparse(
  1006. parsed_playback_url._replace(query=compat_urllib_parse.urlencode(qs, True)))
  1007. self._download_webpage(
  1008. playback_url, video_id, 'Marking watched',
  1009. 'Unable to mark watched', fatal=False)
  1010. @classmethod
  1011. def extract_id(cls, url):
  1012. mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
  1013. if mobj is None:
  1014. raise ExtractorError('Invalid URL: %s' % url)
  1015. video_id = mobj.group(2)
  1016. return video_id
  1017. def _extract_from_m3u8(self, manifest_url, video_id):
  1018. url_map = {}
  1019. def _get_urls(_manifest):
  1020. lines = _manifest.split('\n')
  1021. urls = filter(lambda l: l and not l.startswith('#'),
  1022. lines)
  1023. return urls
  1024. manifest = self._download_webpage(manifest_url, video_id, 'Downloading formats manifest')
  1025. formats_urls = _get_urls(manifest)
  1026. for format_url in formats_urls:
  1027. itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
  1028. url_map[itag] = format_url
  1029. return url_map
  1030. def _extract_annotations(self, video_id):
  1031. url = 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id
  1032. return self._download_webpage(url, video_id, note='Searching for annotations.', errnote='Unable to download video annotations.')
  1033. def _real_extract(self, url):
  1034. url, smuggled_data = unsmuggle_url(url, {})
  1035. proto = (
  1036. 'http' if self._downloader.params.get('prefer_insecure', False)
  1037. else 'https')
  1038. start_time = None
  1039. end_time = None
  1040. parsed_url = compat_urllib_parse_urlparse(url)
  1041. for component in [parsed_url.fragment, parsed_url.query]:
  1042. query = compat_parse_qs(component)
  1043. if start_time is None and 't' in query:
  1044. start_time = parse_duration(query['t'][0])
  1045. if start_time is None and 'start' in query:
  1046. start_time = parse_duration(query['start'][0])
  1047. if end_time is None and 'end' in query:
  1048. end_time = parse_duration(query['end'][0])
  1049. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  1050. mobj = re.search(self._NEXT_URL_RE, url)
  1051. if mobj:
  1052. url = proto + '://www.youtube.com/' + compat_urllib_parse_unquote(mobj.group(1)).lstrip('/')
  1053. video_id = self.extract_id(url)
  1054. # Get video webpage
  1055. url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1&bpctr=9999999999' % video_id
  1056. video_webpage = self._download_webpage(url, video_id)
  1057. # Attempt to extract SWF player URL
  1058. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  1059. if mobj is not None:
  1060. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  1061. else:
  1062. player_url = None
  1063. dash_mpds = []
  1064. def add_dash_mpd(video_info):
  1065. dash_mpd = video_info.get('dashmpd')
  1066. if dash_mpd and dash_mpd[0] not in dash_mpds:
  1067. dash_mpds.append(dash_mpd[0])
  1068. # Get video info
  1069. embed_webpage = None
  1070. is_live = None
  1071. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  1072. age_gate = True
  1073. # We simulate the access to the video from www.youtube.com/v/{video_id}
  1074. # this can be viewed without login into Youtube
  1075. url = proto + '://www.youtube.com/embed/%s' % video_id
  1076. embed_webpage = self._download_webpage(url, video_id, 'Downloading embed webpage')
  1077. data = compat_urllib_parse.urlencode({
  1078. 'video_id': video_id,
  1079. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  1080. 'sts': self._search_regex(
  1081. r'"sts"\s*:\s*(\d+)', embed_webpage, 'sts', default=''),
  1082. })
  1083. video_info_url = proto + '://www.youtube.com/get_video_info?' + data
  1084. video_info_webpage = self._download_webpage(
  1085. video_info_url, video_id,
  1086. note='Refetching age-gated info webpage',
  1087. errnote='unable to download video info webpage')
  1088. video_info = compat_parse_qs(video_info_webpage)
  1089. add_dash_mpd(video_info)
  1090. else:
  1091. age_gate = False
  1092. video_info = None
  1093. # Try looking directly into the video webpage
  1094. ytplayer_config = self._get_ytplayer_config(video_id, video_webpage)
  1095. if ytplayer_config:
  1096. args = ytplayer_config['args']
  1097. if args.get('url_encoded_fmt_stream_map'):
  1098. # Convert to the same format returned by compat_parse_qs
  1099. video_info = dict((k, [v]) for k, v in args.items())
  1100. add_dash_mpd(video_info)
  1101. if args.get('livestream') == '1' or args.get('live_playback') == 1:
  1102. is_live = True
  1103. if not video_info or self._downloader.params.get('youtube_include_dash_manifest', True):
  1104. # We also try looking in get_video_info since it may contain different dashmpd
  1105. # URL that points to a DASH manifest with possibly different itag set (some itags
  1106. # are missing from DASH manifest pointed by webpage's dashmpd, some - from DASH
  1107. # manifest pointed by get_video_info's dashmpd).
  1108. # The general idea is to take a union of itags of both DASH manifests (for example
  1109. # video with such 'manifest behavior' see https://github.com/rg3/youtube-dl/issues/6093)
  1110. self.report_video_info_webpage_download(video_id)
  1111. for el_type in ['&el=info', '&el=embedded', '&el=detailpage', '&el=vevo', '']:
  1112. video_info_url = (
  1113. '%s://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  1114. % (proto, video_id, el_type))
  1115. video_info_webpage = self._download_webpage(
  1116. video_info_url,
  1117. video_id, note=False,
  1118. errnote='unable to download video info webpage')
  1119. get_video_info = compat_parse_qs(video_info_webpage)
  1120. if get_video_info.get('use_cipher_signature') != ['True']:
  1121. add_dash_mpd(get_video_info)
  1122. if not video_info:
  1123. video_info = get_video_info
  1124. if 'token' in get_video_info:
  1125. # Different get_video_info requests may report different results, e.g.
  1126. # some may report video unavailability, but some may serve it without
  1127. # any complaint (see https://github.com/rg3/youtube-dl/issues/7362,
  1128. # the original webpage as well as el=info and el=embedded get_video_info
  1129. # requests report video unavailability due to geo restriction while
  1130. # el=detailpage succeeds and returns valid data). This is probably
  1131. # due to YouTube measures against IP ranges of hosting providers.
  1132. # Working around by preferring the first succeeded video_info containing
  1133. # the token if no such video_info yet was found.
  1134. if 'token' not in video_info:
  1135. video_info = get_video_info
  1136. break
  1137. if 'token' not in video_info:
  1138. if 'reason' in video_info:
  1139. if 'The uploader has not made this video available in your country.' in video_info['reason']:
  1140. regions_allowed = self._html_search_meta('regionsAllowed', video_webpage, default=None)
  1141. if regions_allowed:
  1142. raise ExtractorError('YouTube said: This video is available in %s only' % (
  1143. ', '.join(map(ISO3166Utils.short2full, regions_allowed.split(',')))),
  1144. expected=True)
  1145. raise ExtractorError(
  1146. 'YouTube said: %s' % video_info['reason'][0],
  1147. expected=True, video_id=video_id)
  1148. else:
  1149. raise ExtractorError(
  1150. '"token" parameter not in video info for unknown reason',
  1151. video_id=video_id)
  1152. # title
  1153. if 'title' in video_info:
  1154. video_title = video_info['title'][0]
  1155. else:
  1156. self._downloader.report_warning('Unable to extract video title')
  1157. video_title = '_'
  1158. # description
  1159. video_description = get_element_by_id("eow-description", video_webpage)
  1160. if video_description:
  1161. video_description = re.sub(r'''(?x)
  1162. <a\s+
  1163. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  1164. (?:title|href)="([^"]+)"\s+
  1165. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  1166. class="(?:yt-uix-redirect-link|yt-uix-sessionlink[^"]*)"[^>]*>
  1167. [^<]+\.{3}\s*
  1168. </a>
  1169. ''', r'\1', video_description)
  1170. video_description = clean_html(video_description)
  1171. else:
  1172. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  1173. if fd_mobj:
  1174. video_description = unescapeHTML(fd_mobj.group(1))
  1175. else:
  1176. video_description = ''
  1177. if 'multifeed_metadata_list' in video_info and not smuggled_data.get('force_singlefeed', False):
  1178. if not self._downloader.params.get('noplaylist'):
  1179. entries = []
  1180. feed_ids = []
  1181. multifeed_metadata_list = video_info['multifeed_metadata_list'][0]
  1182. for feed in multifeed_metadata_list.split(','):
  1183. # Unquote should take place before split on comma (,) since textual
  1184. # fields may contain comma as well (see
  1185. # https://github.com/rg3/youtube-dl/issues/8536)
  1186. feed_data = compat_parse_qs(compat_urllib_parse_unquote_plus(feed))
  1187. entries.append({
  1188. '_type': 'url_transparent',
  1189. 'ie_key': 'Youtube',
  1190. 'url': smuggle_url(
  1191. '%s://www.youtube.com/watch?v=%s' % (proto, feed_data['id'][0]),
  1192. {'force_singlefeed': True}),
  1193. 'title': '%s (%s)' % (video_title, feed_data['title'][0]),
  1194. })
  1195. feed_ids.append(feed_data['id'][0])
  1196. self.to_screen(
  1197. 'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
  1198. % (', '.join(feed_ids), video_id))
  1199. return self.playlist_result(entries, video_id, video_title, video_description)
  1200. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  1201. if 'view_count' in video_info:
  1202. view_count = int(video_info['view_count'][0])
  1203. else:
  1204. view_count = None
  1205. # Check for "rental" videos
  1206. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  1207. raise ExtractorError('"rental" videos not supported')
  1208. # Start extracting information
  1209. self.report_information_extraction(video_id)
  1210. # uploader
  1211. if 'author' not in video_info:
  1212. raise ExtractorError('Unable to extract uploader name')
  1213. video_uploader = compat_urllib_parse_unquote_plus(video_info['author'][0])
  1214. # uploader_id
  1215. video_uploader_id = None
  1216. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  1217. if mobj is not None:
  1218. video_uploader_id = mobj.group(1)
  1219. else:
  1220. self._downloader.report_warning('unable to extract uploader nickname')
  1221. # thumbnail image
  1222. # We try first to get a high quality image:
  1223. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  1224. video_webpage, re.DOTALL)
  1225. if m_thumb is not None:
  1226. video_thumbnail = m_thumb.group(1)
  1227. elif 'thumbnail_url' not in video_info:
  1228. self._downloader.report_warning('unable to extract video thumbnail')
  1229. video_thumbnail = None
  1230. else: # don't panic if we can't find it
  1231. video_thumbnail = compat_urllib_parse_unquote_plus(video_info['thumbnail_url'][0])
  1232. # upload date
  1233. upload_date = self._html_search_meta(
  1234. 'datePublished', video_webpage, 'upload date', default=None)
  1235. if not upload_date:
  1236. upload_date = self._search_regex(
  1237. [r'(?s)id="eow-date.*?>(.*?)</span>',
  1238. r'id="watch-uploader-info".*?>.*?(?:Published|Uploaded|Streamed live|Started) on (.+?)</strong>'],
  1239. video_webpage, 'upload date', default=None)
  1240. if upload_date:
  1241. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  1242. upload_date = unified_strdate(upload_date)
  1243. m_music = re.search(
  1244. r'<h4[^>]+class="title"[^>]*>\s*Music\s*</h4>\s*<ul[^>]*>\s*<li>(?P<title>.+?) by (?P<creator>.+?)(?:\(.+?\))?</li',
  1245. video_webpage)
  1246. if m_music:
  1247. video_alt_title = remove_quotes(unescapeHTML(m_music.group('title')))
  1248. video_creator = clean_html(m_music.group('creator'))
  1249. else:
  1250. video_alt_title = video_creator = None
  1251. m_cat_container = self._search_regex(
  1252. r'(?s)<h4[^>]*>\s*Category\s*</h4>\s*<ul[^>]*>(.*?)</ul>',
  1253. video_webpage, 'categories', default=None)
  1254. if m_cat_container:
  1255. category = self._html_search_regex(
  1256. r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
  1257. default=None)
  1258. video_categories = None if category is None else [category]
  1259. else:
  1260. video_categories = None
  1261. video_tags = [
  1262. unescapeHTML(m.group('content'))
  1263. for m in re.finditer(self._meta_regex('og:video:tag'), video_webpage)]
  1264. def _extract_count(count_name):
  1265. return str_to_int(self._search_regex(
  1266. r'-%s-button[^>]+><span[^>]+class="yt-uix-button-content"[^>]*>([\d,]+)</span>'
  1267. % re.escape(count_name),
  1268. video_webpage, count_name, default=None))
  1269. like_count = _extract_count('like')
  1270. dislike_count = _extract_count('dislike')
  1271. # subtitles
  1272. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  1273. automatic_captions = self.extract_automatic_captions(video_id, video_webpage)
  1274. if 'length_seconds' not in video_info:
  1275. self._downloader.report_warning('unable to extract video duration')
  1276. video_duration = None
  1277. else:
  1278. video_duration = int(compat_urllib_parse_unquote_plus(video_info['length_seconds'][0]))
  1279. # annotations
  1280. video_annotations = None
  1281. if self._downloader.params.get('writeannotations', False):
  1282. video_annotations = self._extract_annotations(video_id)
  1283. def _map_to_format_list(urlmap):
  1284. formats = []
  1285. for itag, video_real_url in urlmap.items():
  1286. dct = {
  1287. 'format_id': itag,
  1288. 'url': video_real_url,
  1289. 'player_url': player_url,
  1290. }
  1291. if itag in self._formats:
  1292. dct.update(self._formats[itag])
  1293. formats.append(dct)
  1294. return formats
  1295. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  1296. self.report_rtmp_download()
  1297. formats = [{
  1298. 'format_id': '_rtmp',
  1299. 'protocol': 'rtmp',
  1300. 'url': video_info['conn'][0],
  1301. 'player_url': player_url,
  1302. }]
  1303. elif len(video_info.get('url_encoded_fmt_stream_map', [''])[0]) >= 1 or len(video_info.get('adaptive_fmts', [''])[0]) >= 1:
  1304. encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts', [''])[0]
  1305. if 'rtmpe%3Dyes' in encoded_url_map:
  1306. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
  1307. fmt_list = video_info.get('fmt_list', [''])[0]
  1308. if fmt_list:
  1309. for fmt in fmt_list.split(','):
  1310. spec = fmt.split('/')
  1311. width, height = spec[1].split('x')
  1312. self._formats[spec[0]].update({
  1313. 'resolution': spec[1],
  1314. 'width': int_or_none(width),
  1315. 'height': int_or_none(height),
  1316. })
  1317. formats = []
  1318. for url_data_str in encoded_url_map.split(','):
  1319. url_data = compat_parse_qs(url_data_str)
  1320. if 'itag' not in url_data or 'url' not in url_data:
  1321. continue
  1322. format_id = url_data['itag'][0]
  1323. url = url_data['url'][0]
  1324. if 'sig' in url_data:
  1325. url += '&signature=' + url_data['sig'][0]
  1326. elif 's' in url_data:
  1327. encrypted_sig = url_data['s'][0]
  1328. ASSETS_RE = r'"assets":.+?"js":\s*("[^"]+")'
  1329. jsplayer_url_json = self._search_regex(
  1330. ASSETS_RE,
  1331. embed_webpage if age_gate else video_webpage,
  1332. 'JS player URL (1)', default=None)
  1333. if not jsplayer_url_json and not age_gate:
  1334. # We need the embed website after all
  1335. if embed_webpage is None:
  1336. embed_url = proto + '://www.youtube.com/embed/%s' % video_id
  1337. embed_webpage = self._download_webpage(
  1338. embed_url, video_id, 'Downloading embed webpage')
  1339. jsplayer_url_json = self._search_regex(
  1340. ASSETS_RE, embed_webpage, 'JS player URL')
  1341. player_url = json.loads(jsplayer_url_json)
  1342. if player_url is None:
  1343. player_url_json = self._search_regex(
  1344. r'ytplayer\.config.*?"url"\s*:\s*("[^"]+")',
  1345. video_webpage, 'age gate player URL')
  1346. player_url = json.loads(player_url_json)
  1347. if self._downloader.params.get('verbose'):
  1348. if player_url is None:
  1349. player_version = 'unknown'
  1350. player_desc = 'unknown'
  1351. else:
  1352. if player_url.endswith('swf'):
  1353. player_version = self._search_regex(
  1354. r'-(.+?)(?:/watch_as3)?\.swf$', player_url,
  1355. 'flash player', fatal=False)
  1356. player_desc = 'flash player %s' % player_version
  1357. else:
  1358. player_version = self._search_regex(
  1359. [r'html5player-([^/]+?)(?:/html5player(?:-new)?)?\.js', r'(?:www|player)-([^/]+)/base\.js'],
  1360. player_url,
  1361. 'html5 player', fatal=False)
  1362. player_desc = 'html5 player %s' % player_version
  1363. parts_sizes = self._signature_cache_id(encrypted_sig)
  1364. self.to_screen('{%s} signature length %s, %s' %
  1365. (format_id, parts_sizes, player_desc))
  1366. signature = self._decrypt_signature(
  1367. encrypted_sig, video_id, player_url, age_gate)
  1368. url += '&signature=' + signature
  1369. if 'ratebypass' not in url:
  1370. url += '&ratebypass=yes'
  1371. dct = {
  1372. 'format_id': format_id,
  1373. 'url': url,
  1374. 'player_url': player_url,
  1375. }
  1376. if format_id in self._formats:
  1377. dct.update(self._formats[format_id])
  1378. # Some itags are not included in DASH manifest thus corresponding formats will
  1379. # lack metadata (see https://github.com/rg3/youtube-dl/pull/5993).
  1380. # Trying to extract metadata from url_encoded_fmt_stream_map entry.
  1381. mobj = re.search(r'^(?P<width>\d+)[xX](?P<height>\d+)$', url_data.get('size', [''])[0])
  1382. width, height = (int(mobj.group('width')), int(mobj.group('height'))) if mobj else (None, None)
  1383. more_fields = {
  1384. 'filesize': int_or_none(url_data.get('clen', [None])[0]),
  1385. 'tbr': float_or_none(url_data.get('bitrate', [None])[0], 1000),
  1386. 'width': width,
  1387. 'height': height,
  1388. 'fps': int_or_none(url_data.get('fps', [None])[0]),
  1389. 'format_note': url_data.get('quality_label', [None])[0] or url_data.get('quality', [None])[0],
  1390. }
  1391. for key, value in more_fields.items():
  1392. if value:
  1393. dct[key] = value
  1394. type_ = url_data.get('type', [None])[0]
  1395. if type_:
  1396. type_split = type_.split(';')
  1397. kind_ext = type_split[0].split('/')
  1398. if len(kind_ext) == 2:
  1399. kind, _ = kind_ext
  1400. dct['ext'] = mimetype2ext(type_split[0])
  1401. if kind in ('audio', 'video'):
  1402. codecs = None
  1403. for mobj in re.finditer(
  1404. r'(?P<key>[a-zA-Z_-]+)=(?P<quote>["\']?)(?P<val>.+?)(?P=quote)(?:;|$)', type_):
  1405. if mobj.group('key') == 'codecs':
  1406. codecs = mobj.group('val')
  1407. break
  1408. if codecs:
  1409. codecs = codecs.split(',')
  1410. if len(codecs) == 2:
  1411. acodec, vcodec = codecs[1], codecs[0]
  1412. else:
  1413. acodec, vcodec = (codecs[0], 'none') if kind == 'audio' else ('none', codecs[0])
  1414. dct.update({
  1415. 'acodec': acodec,
  1416. 'vcodec': vcodec,
  1417. })
  1418. formats.append(dct)
  1419. elif video_info.get('hlsvp'):
  1420. manifest_url = video_info['hlsvp'][0]
  1421. url_map = self._extract_from_m3u8(manifest_url, video_id)
  1422. formats = _map_to_format_list(url_map)
  1423. # Accept-Encoding header causes failures in live streams on Youtube and Youtube Gaming
  1424. for a_format in formats:
  1425. a_format.setdefault('http_headers', {})['Youtubedl-no-compression'] = 'True'
  1426. else:
  1427. unavailable_message = self._html_search_regex(
  1428. r'(?s)<h1[^>]+id="unavailable-message"[^>]*>(.+?)</h1>',
  1429. video_webpage, 'unavailable message', default=None)
  1430. if unavailable_message:
  1431. raise ExtractorError(unavailable_message, expected=True)
  1432. raise ExtractorError('no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
  1433. # Look for the DASH manifest
  1434. if self._downloader.params.get('youtube_include_dash_manifest', True):
  1435. dash_mpd_fatal = True
  1436. for mpd_url in dash_mpds:
  1437. dash_formats = {}
  1438. try:
  1439. def decrypt_sig(mobj):
  1440. s = mobj.group(1)
  1441. dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
  1442. return '/signature/%s' % dec_s
  1443. mpd_url = re.sub(r'/s/([a-fA-F0-9\.]+)', decrypt_sig, mpd_url)
  1444. for df in self._extract_mpd_formats(
  1445. mpd_url, video_id, fatal=dash_mpd_fatal,
  1446. formats_dict=self._formats):
  1447. # Do not overwrite DASH format found in some previous DASH manifest
  1448. if df['format_id'] not in dash_formats:
  1449. dash_formats[df['format_id']] = df
  1450. # Additional DASH manifests may end up in HTTP Error 403 therefore
  1451. # allow them to fail without bug report message if we already have
  1452. # some DASH manifest succeeded. This is temporary workaround to reduce
  1453. # burst of bug reports until we figure out the reason and whether it
  1454. # can be fixed at all.
  1455. dash_mpd_fatal = False
  1456. except (ExtractorError, KeyError) as e:
  1457. self.report_warning(
  1458. 'Skipping DASH manifest: %r' % e, video_id)
  1459. if dash_formats:
  1460. # Remove the formats we found through non-DASH, they
  1461. # contain less info and it can be wrong, because we use
  1462. # fixed values (for example the resolution). See
  1463. # https://github.com/rg3/youtube-dl/issues/5774 for an
  1464. # example.
  1465. formats = [f for f in formats if f['format_id'] not in dash_formats.keys()]
  1466. formats.extend(dash_formats.values())
  1467. # Check for malformed aspect ratio
  1468. stretched_m = re.search(
  1469. r'<meta\s+property="og:video:tag".*?content="yt:stretch=(?P<w>[0-9]+):(?P<h>[0-9]+)">',
  1470. video_webpage)
  1471. if stretched_m:
  1472. w = float(stretched_m.group('w'))
  1473. h = float(stretched_m.group('h'))
  1474. # yt:stretch may hold invalid ratio data (e.g. for Q39EVAstoRM ratio is 17:0).
  1475. # We will only process correct ratios.
  1476. if w > 0 and h > 0:
  1477. ratio = w / h
  1478. for f in formats:
  1479. if f.get('vcodec') != 'none':
  1480. f['stretched_ratio'] = ratio
  1481. self._sort_formats(formats)
  1482. self.mark_watched(video_id, video_info)
  1483. return {
  1484. 'id': video_id,
  1485. 'uploader': video_uploader,
  1486. 'uploader_id': video_uploader_id,
  1487. 'upload_date': upload_date,
  1488. 'creator': video_creator,
  1489. 'title': video_title,
  1490. 'alt_title': video_alt_title,
  1491. 'thumbnail': video_thumbnail,
  1492. 'description': video_description,
  1493. 'categories': video_categories,
  1494. 'tags': video_tags,
  1495. 'subtitles': video_subtitles,
  1496. 'automatic_captions': automatic_captions,
  1497. 'duration': video_duration,
  1498. 'age_limit': 18 if age_gate else 0,
  1499. 'annotations': video_annotations,
  1500. 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
  1501. 'view_count': view_count,
  1502. 'like_count': like_count,
  1503. 'dislike_count': dislike_count,
  1504. 'average_rating': float_or_none(video_info.get('avg_rating', [None])[0]),
  1505. 'formats': formats,
  1506. 'is_live': is_live,
  1507. 'start_time': start_time,
  1508. 'end_time': end_time,
  1509. }
  1510. class YoutubePlaylistIE(YoutubePlaylistBaseInfoExtractor):
  1511. IE_DESC = 'YouTube.com playlists'
  1512. _VALID_URL = r"""(?x)(?:
  1513. (?:https?://)?
  1514. (?:\w+\.)?
  1515. youtube\.com/
  1516. (?:
  1517. (?:course|view_play_list|my_playlists|artist|playlist|watch|embed/videoseries)
  1518. \? (?:.*?[&;])*? (?:p|a|list)=
  1519. | p/
  1520. )
  1521. (
  1522. (?:PL|LL|EC|UU|FL|RD|UL)?[0-9A-Za-z-_]{10,}
  1523. # Top tracks, they can also include dots
  1524. |(?:MC)[\w\.]*
  1525. )
  1526. .*
  1527. |
  1528. ((?:PL|LL|EC|UU|FL|RD|UL)[0-9A-Za-z-_]{10,})
  1529. )"""
  1530. _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s'
  1531. _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&amp;[^"]*?index=(?P<index>\d+)(?:[^>]+>(?P<title>[^<]+))?'
  1532. IE_NAME = 'youtube:playlist'
  1533. _TESTS = [{
  1534. 'url': 'https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
  1535. 'info_dict': {
  1536. 'title': 'ytdl test PL',
  1537. 'id': 'PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
  1538. },
  1539. 'playlist_count': 3,
  1540. }, {
  1541. 'url': 'https://www.youtube.com/playlist?list=PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
  1542. 'info_dict': {
  1543. 'id': 'PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
  1544. 'title': 'YDL_Empty_List',
  1545. },
  1546. 'playlist_count': 0,
  1547. }, {
  1548. 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
  1549. 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  1550. 'info_dict': {
  1551. 'title': '29C3: Not my department',
  1552. 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  1553. },
  1554. 'playlist_count': 95,
  1555. }, {
  1556. 'note': 'issue #673',
  1557. 'url': 'PLBB231211A4F62143',
  1558. 'info_dict': {
  1559. 'title': '[OLD]Team Fortress 2 (Class-based LP)',
  1560. 'id': 'PLBB231211A4F62143',
  1561. },
  1562. 'playlist_mincount': 26,
  1563. }, {
  1564. 'note': 'Large playlist',
  1565. 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
  1566. 'info_dict': {
  1567. 'title': 'Uploads from Cauchemar',
  1568. 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
  1569. },
  1570. 'playlist_mincount': 799,
  1571. }, {
  1572. 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  1573. 'info_dict': {
  1574. 'title': 'YDL_safe_search',
  1575. 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  1576. },
  1577. 'playlist_count': 2,
  1578. }, {
  1579. 'note': 'embedded',
  1580. 'url': 'http://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  1581. 'playlist_count': 4,
  1582. 'info_dict': {
  1583. 'title': 'JODA15',
  1584. 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  1585. }
  1586. }, {
  1587. 'note': 'Embedded SWF player',
  1588. 'url': 'http://www.youtube.com/p/YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ?hl=en_US&fs=1&rel=0',
  1589. 'playlist_count': 4,
  1590. 'info_dict': {
  1591. 'title': 'JODA7',
  1592. 'id': 'YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ',
  1593. }
  1594. }, {
  1595. 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
  1596. 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
  1597. 'info_dict': {
  1598. 'title': 'Uploads from Interstellar Movie',
  1599. 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
  1600. },
  1601. 'playlist_mincout': 21,
  1602. }]
  1603. def _real_initialize(self):
  1604. self._login()
  1605. def _extract_mix(self, playlist_id):
  1606. # The mixes are generated from a single video
  1607. # the id of the playlist is just 'RD' + video_id
  1608. url = 'https://youtube.com/watch?v=%s&list=%s' % (playlist_id[-11:], playlist_id)
  1609. webpage = self._download_webpage(
  1610. url, playlist_id, 'Downloading Youtube mix')
  1611. search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
  1612. title_span = (
  1613. search_title('playlist-title') or
  1614. search_title('title long-title') or
  1615. search_title('title'))
  1616. title = clean_html(title_span)
  1617. ids = orderedSet(re.findall(
  1618. r'''(?xs)data-video-username=".*?".*?
  1619. href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s''' % re.escape(playlist_id),
  1620. webpage))
  1621. url_results = self._ids_to_results(ids)
  1622. return self.playlist_result(url_results, playlist_id, title)
  1623. def _extract_playlist(self, playlist_id):
  1624. url = self._TEMPLATE_URL % playlist_id
  1625. page = self._download_webpage(url, playlist_id)
  1626. for match in re.findall(r'<div class="yt-alert-message">([^<]+)</div>', page):
  1627. match = match.strip()
  1628. # Check if the playlist exists or is private
  1629. if re.match(r'[^<]*(The|This) playlist (does not exist|is private)[^<]*', match):
  1630. raise ExtractorError(
  1631. 'The playlist doesn\'t exist or is private, use --username or '
  1632. '--netrc to access it.',
  1633. expected=True)
  1634. elif re.match(r'[^<]*Invalid parameters[^<]*', match):
  1635. raise ExtractorError(
  1636. 'Invalid parameters. Maybe URL is incorrect.',
  1637. expected=True)
  1638. elif re.match(r'[^<]*Choose your language[^<]*', match):
  1639. continue
  1640. else:
  1641. self.report_warning('Youtube gives an alert message: ' + match)
  1642. playlist_title = self._html_search_regex(
  1643. r'(?s)<h1 class="pl-header-title[^"]*"[^>]*>\s*(.*?)\s*</h1>',
  1644. page, 'title')
  1645. return self.playlist_result(self._entries(page, playlist_id), playlist_id, playlist_title)
  1646. def _check_download_just_video(self, url, playlist_id):
  1647. # Check if it's a video-specific URL
  1648. query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  1649. if 'v' in query_dict:
  1650. video_id = query_dict['v'][0]
  1651. if self._downloader.params.get('noplaylist'):
  1652. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  1653. return self.url_result(video_id, 'Youtube', video_id=video_id)
  1654. else:
  1655. self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  1656. def _real_extract(self, url):
  1657. # Extract playlist id
  1658. mobj = re.match(self._VALID_URL, url)
  1659. if mobj is None:
  1660. raise ExtractorError('Invalid URL: %s' % url)
  1661. playlist_id = mobj.group(1) or mobj.group(2)
  1662. video = self._check_download_just_video(url, playlist_id)
  1663. if video:
  1664. return video
  1665. if playlist_id.startswith('RD') or playlist_id.startswith('UL'):
  1666. # Mixes require a custom extraction process
  1667. return self._extract_mix(playlist_id)
  1668. return self._extract_playlist(playlist_id)
  1669. class YoutubeChannelIE(YoutubePlaylistBaseInfoExtractor):
  1670. IE_DESC = 'YouTube.com channels'
  1671. _VALID_URL = r'https?://(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/(?P<id>[0-9A-Za-z_-]+)'
  1672. _TEMPLATE_URL = 'https://www.youtube.com/channel/%s/videos'
  1673. _VIDEO_RE = r'(?:title="(?P<title>[^"]+)"[^>]+)?href="/watch\?v=(?P<id>[0-9A-Za-z_-]+)&?'
  1674. IE_NAME = 'youtube:channel'
  1675. _TESTS = [{
  1676. 'note': 'paginated channel',
  1677. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
  1678. 'playlist_mincount': 91,
  1679. 'info_dict': {
  1680. 'id': 'UUKfVa3S1e4PHvxWcwyMMg8w',
  1681. 'title': 'Uploads from lex will',
  1682. }
  1683. }, {
  1684. 'note': 'Age restricted channel',
  1685. # from https://www.youtube.com/user/DeusExOfficial
  1686. 'url': 'https://www.youtube.com/channel/UCs0ifCMCm1icqRbqhUINa0w',
  1687. 'playlist_mincount': 64,
  1688. 'info_dict': {
  1689. 'id': 'UUs0ifCMCm1icqRbqhUINa0w',
  1690. 'title': 'Uploads from Deus Ex',
  1691. },
  1692. }]
  1693. @classmethod
  1694. def suitable(cls, url):
  1695. return False if YoutubePlaylistsIE.suitable(url) else super(YoutubeChannelIE, cls).suitable(url)
  1696. def _real_extract(self, url):
  1697. channel_id = self._match_id(url)
  1698. url = self._TEMPLATE_URL % channel_id
  1699. # Channel by page listing is restricted to 35 pages of 30 items, i.e. 1050 videos total (see #5778)
  1700. # Workaround by extracting as a playlist if managed to obtain channel playlist URL
  1701. # otherwise fallback on channel by page extraction
  1702. channel_page = self._download_webpage(
  1703. url + '?view=57', channel_id,
  1704. 'Downloading channel page', fatal=False)
  1705. if channel_page is False:
  1706. channel_playlist_id = False
  1707. else:
  1708. channel_playlist_id = self._html_search_meta(
  1709. 'channelId', channel_page, 'channel id', default=None)
  1710. if not channel_playlist_id:
  1711. channel_playlist_id = self._search_regex(
  1712. r'data-(?:channel-external-|yt)id="([^"]+)"',
  1713. channel_page, 'channel id', default=None)
  1714. if channel_playlist_id and channel_playlist_id.startswith('UC'):
  1715. playlist_id = 'UU' + channel_playlist_id[2:]
  1716. return self.url_result(
  1717. compat_urlparse.urljoin(url, '/playlist?list=%s' % playlist_id), 'YoutubePlaylist')
  1718. channel_page = self._download_webpage(url, channel_id, 'Downloading page #1')
  1719. autogenerated = re.search(r'''(?x)
  1720. class="[^"]*?(?:
  1721. channel-header-autogenerated-label|
  1722. yt-channel-title-autogenerated
  1723. )[^"]*"''', channel_page) is not None
  1724. if autogenerated:
  1725. # The videos are contained in a single page
  1726. # the ajax pages can't be used, they are empty
  1727. entries = [
  1728. self.url_result(
  1729. video_id, 'Youtube', video_id=video_id,
  1730. video_title=video_title)
  1731. for video_id, video_title in self.extract_videos_from_page(channel_page)]
  1732. return self.playlist_result(entries, channel_id)
  1733. return self.playlist_result(self._entries(channel_page, channel_id), channel_id)
  1734. class YoutubeUserIE(YoutubeChannelIE):
  1735. IE_DESC = 'YouTube.com user videos (URL or "ytuser" keyword)'
  1736. _VALID_URL = r'(?:(?:https?://(?:\w+\.)?youtube\.com/(?:user/)?(?!(?:attribution_link|watch|results)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)(?P<id>[A-Za-z0-9_-]+)'
  1737. _TEMPLATE_URL = 'https://www.youtube.com/user/%s/videos'
  1738. IE_NAME = 'youtube:user'
  1739. _TESTS = [{
  1740. 'url': 'https://www.youtube.com/user/TheLinuxFoundation',
  1741. 'playlist_mincount': 320,
  1742. 'info_dict': {
  1743. 'title': 'TheLinuxFoundation',
  1744. }
  1745. }, {
  1746. 'url': 'ytuser:phihag',
  1747. 'only_matching': True,
  1748. }]
  1749. @classmethod
  1750. def suitable(cls, url):
  1751. # Don't return True if the url can be extracted with other youtube
  1752. # extractor, the regex would is too permissive and it would match.
  1753. other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls)
  1754. if any(ie.suitable(url) for ie in other_ies):
  1755. return False
  1756. else:
  1757. return super(YoutubeUserIE, cls).suitable(url)
  1758. class YoutubePlaylistsIE(YoutubePlaylistsBaseInfoExtractor):
  1759. IE_DESC = 'YouTube.com user/channel playlists'
  1760. _VALID_URL = r'https?://(?:\w+\.)?youtube\.com/(?:user|channel)/(?P<id>[^/]+)/playlists'
  1761. IE_NAME = 'youtube:playlists'
  1762. _TESTS = [{
  1763. 'url': 'http://www.youtube.com/user/ThirstForScience/playlists',
  1764. 'playlist_mincount': 4,
  1765. 'info_dict': {
  1766. 'id': 'ThirstForScience',
  1767. 'title': 'Thirst for Science',
  1768. },
  1769. }, {
  1770. # with "Load more" button
  1771. 'url': 'http://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
  1772. 'playlist_mincount': 70,
  1773. 'info_dict': {
  1774. 'id': 'igorkle1',
  1775. 'title': 'Игорь Клейнер',
  1776. },
  1777. }, {
  1778. 'url': 'https://www.youtube.com/channel/UCiU1dHvZObB2iP6xkJ__Icw/playlists',
  1779. 'playlist_mincount': 17,
  1780. 'info_dict': {
  1781. 'id': 'UCiU1dHvZObB2iP6xkJ__Icw',
  1782. 'title': 'Chem Player',
  1783. },
  1784. }]
  1785. class YoutubeSearchIE(SearchInfoExtractor, YoutubePlaylistIE):
  1786. IE_DESC = 'YouTube.com searches'
  1787. # there doesn't appear to be a real limit, for example if you search for
  1788. # 'python' you get more than 8.000.000 results
  1789. _MAX_RESULTS = float('inf')
  1790. IE_NAME = 'youtube:search'
  1791. _SEARCH_KEY = 'ytsearch'
  1792. _EXTRA_QUERY_ARGS = {}
  1793. _TESTS = []
  1794. def _get_n_results(self, query, n):
  1795. """Get a specified number of results for a query"""
  1796. videos = []
  1797. limit = n
  1798. for pagenum in itertools.count(1):
  1799. url_query = {
  1800. 'search_query': query.encode('utf-8'),
  1801. 'page': pagenum,
  1802. 'spf': 'navigate',
  1803. }
  1804. url_query.update(self._EXTRA_QUERY_ARGS)
  1805. result_url = 'https://www.youtube.com/results?' + compat_urllib_parse.urlencode(url_query)
  1806. data = self._download_json(
  1807. result_url, video_id='query "%s"' % query,
  1808. note='Downloading page %s' % pagenum,
  1809. errnote='Unable to download API page')
  1810. html_content = data[1]['body']['content']
  1811. if 'class="search-message' in html_content:
  1812. raise ExtractorError(
  1813. '[youtube] No video results', expected=True)
  1814. new_videos = self._ids_to_results(orderedSet(re.findall(
  1815. r'href="/watch\?v=(.{11})', html_content)))
  1816. videos += new_videos
  1817. if not new_videos or len(videos) > limit:
  1818. break
  1819. if len(videos) > n:
  1820. videos = videos[:n]
  1821. return self.playlist_result(videos, query)
  1822. class YoutubeSearchDateIE(YoutubeSearchIE):
  1823. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  1824. _SEARCH_KEY = 'ytsearchdate'
  1825. IE_DESC = 'YouTube.com searches, newest videos first'
  1826. _EXTRA_QUERY_ARGS = {'search_sort': 'video_date_uploaded'}
  1827. class YoutubeSearchURLIE(InfoExtractor):
  1828. IE_DESC = 'YouTube.com search URLs'
  1829. IE_NAME = 'youtube:search_url'
  1830. _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?(?:search_query|q)=(?P<query>[^&]+)(?:[&]|$)'
  1831. _TESTS = [{
  1832. 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
  1833. 'playlist_mincount': 5,
  1834. 'info_dict': {
  1835. 'title': 'youtube-dl test video',
  1836. }
  1837. }, {
  1838. 'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
  1839. 'only_matching': True,
  1840. }]
  1841. def _real_extract(self, url):
  1842. mobj = re.match(self._VALID_URL, url)
  1843. query = compat_urllib_parse_unquote_plus(mobj.group('query'))
  1844. webpage = self._download_webpage(url, query)
  1845. result_code = self._search_regex(
  1846. r'(?s)<ol[^>]+class="item-section"(.*?)</ol>', webpage, 'result HTML')
  1847. part_codes = re.findall(
  1848. r'(?s)<h3[^>]+class="[^"]*yt-lockup-title[^"]*"[^>]*>(.*?)</h3>', result_code)
  1849. entries = []
  1850. for part_code in part_codes:
  1851. part_title = self._html_search_regex(
  1852. [r'(?s)title="([^"]+)"', r'>([^<]+)</a>'], part_code, 'item title', fatal=False)
  1853. part_url_snippet = self._html_search_regex(
  1854. r'(?s)href="([^"]+)"', part_code, 'item URL')
  1855. part_url = compat_urlparse.urljoin(
  1856. 'https://www.youtube.com/', part_url_snippet)
  1857. entries.append({
  1858. '_type': 'url',
  1859. 'url': part_url,
  1860. 'title': part_title,
  1861. })
  1862. return {
  1863. '_type': 'playlist',
  1864. 'entries': entries,
  1865. 'title': query,
  1866. }
  1867. class YoutubeShowIE(YoutubePlaylistsBaseInfoExtractor):
  1868. IE_DESC = 'YouTube.com (multi-season) shows'
  1869. _VALID_URL = r'https?://www\.youtube\.com/show/(?P<id>[^?#]*)'
  1870. IE_NAME = 'youtube:show'
  1871. _TESTS = [{
  1872. 'url': 'https://www.youtube.com/show/airdisasters',
  1873. 'playlist_mincount': 5,
  1874. 'info_dict': {
  1875. 'id': 'airdisasters',
  1876. 'title': 'Air Disasters',
  1877. }
  1878. }]
  1879. def _real_extract(self, url):
  1880. playlist_id = self._match_id(url)
  1881. return super(YoutubeShowIE, self)._real_extract(
  1882. 'https://www.youtube.com/show/%s/playlists' % playlist_id)
  1883. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  1884. """
  1885. Base class for feed extractors
  1886. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  1887. """
  1888. _LOGIN_REQUIRED = True
  1889. @property
  1890. def IE_NAME(self):
  1891. return 'youtube:%s' % self._FEED_NAME
  1892. def _real_initialize(self):
  1893. self._login()
  1894. def _real_extract(self, url):
  1895. page = self._download_webpage(
  1896. 'https://www.youtube.com/feed/%s' % self._FEED_NAME, self._PLAYLIST_TITLE)
  1897. # The extraction process is the same as for playlists, but the regex
  1898. # for the video ids doesn't contain an index
  1899. ids = []
  1900. more_widget_html = content_html = page
  1901. for page_num in itertools.count(1):
  1902. matches = re.findall(r'href="\s*/watch\?v=([0-9A-Za-z_-]{11})', content_html)
  1903. # 'recommended' feed has infinite 'load more' and each new portion spins
  1904. # the same videos in (sometimes) slightly different order, so we'll check
  1905. # for unicity and break when portion has no new videos
  1906. new_ids = filter(lambda video_id: video_id not in ids, orderedSet(matches))
  1907. if not new_ids:
  1908. break
  1909. ids.extend(new_ids)
  1910. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  1911. if not mobj:
  1912. break
  1913. more = self._download_json(
  1914. 'https://youtube.com/%s' % mobj.group('more'), self._PLAYLIST_TITLE,
  1915. 'Downloading page #%s' % page_num,
  1916. transform_source=uppercase_escape)
  1917. content_html = more['content_html']
  1918. more_widget_html = more['load_more_widget_html']
  1919. return self.playlist_result(
  1920. self._ids_to_results(ids), playlist_title=self._PLAYLIST_TITLE)
  1921. class YoutubeWatchLaterIE(YoutubePlaylistIE):
  1922. IE_NAME = 'youtube:watchlater'
  1923. IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
  1924. _VALID_URL = r'https?://www\.youtube\.com/(?:feed/watch_later|(?:playlist|watch)\?(?:.+&)?list=WL)|:ytwatchlater'
  1925. _TESTS = [{
  1926. 'url': 'https://www.youtube.com/playlist?list=WL',
  1927. 'only_matching': True,
  1928. }, {
  1929. 'url': 'https://www.youtube.com/watch?v=bCNU9TrbiRk&index=1&list=WL',
  1930. 'only_matching': True,
  1931. }]
  1932. def _real_extract(self, url):
  1933. video = self._check_download_just_video(url, 'WL')
  1934. if video:
  1935. return video
  1936. return self._extract_playlist('WL')
  1937. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  1938. IE_NAME = 'youtube:favorites'
  1939. IE_DESC = 'YouTube.com favourite videos, ":ytfav" for short (requires authentication)'
  1940. _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  1941. _LOGIN_REQUIRED = True
  1942. def _real_extract(self, url):
  1943. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  1944. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, 'favourites playlist id')
  1945. return self.url_result(playlist_id, 'YoutubePlaylist')
  1946. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  1947. IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
  1948. _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  1949. _FEED_NAME = 'recommended'
  1950. _PLAYLIST_TITLE = 'Youtube Recommended videos'
  1951. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  1952. IE_DESC = 'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
  1953. _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  1954. _FEED_NAME = 'subscriptions'
  1955. _PLAYLIST_TITLE = 'Youtube Subscriptions'
  1956. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  1957. IE_DESC = 'Youtube watch history, ":ythistory" for short (requires authentication)'
  1958. _VALID_URL = 'https?://www\.youtube\.com/feed/history|:ythistory'
  1959. _FEED_NAME = 'history'
  1960. _PLAYLIST_TITLE = 'Youtube History'
  1961. class YoutubeTruncatedURLIE(InfoExtractor):
  1962. IE_NAME = 'youtube:truncated_url'
  1963. IE_DESC = False # Do not list
  1964. _VALID_URL = r'''(?x)
  1965. (?:https?://)?
  1966. (?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/
  1967. (?:watch\?(?:
  1968. feature=[a-z_]+|
  1969. annotation_id=annotation_[^&]+|
  1970. x-yt-cl=[0-9]+|
  1971. hl=[^&]*|
  1972. t=[0-9]+
  1973. )?
  1974. |
  1975. attribution_link\?a=[^&]+
  1976. )
  1977. $
  1978. '''
  1979. _TESTS = [{
  1980. 'url': 'http://www.youtube.com/watch?annotation_id=annotation_3951667041',
  1981. 'only_matching': True,
  1982. }, {
  1983. 'url': 'http://www.youtube.com/watch?',
  1984. 'only_matching': True,
  1985. }, {
  1986. 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
  1987. 'only_matching': True,
  1988. }, {
  1989. 'url': 'https://www.youtube.com/watch?feature=foo',
  1990. 'only_matching': True,
  1991. }, {
  1992. 'url': 'https://www.youtube.com/watch?hl=en-GB',
  1993. 'only_matching': True,
  1994. }, {
  1995. 'url': 'https://www.youtube.com/watch?t=2372',
  1996. 'only_matching': True,
  1997. }]
  1998. def _real_extract(self, url):
  1999. raise ExtractorError(
  2000. 'Did you forget to quote the URL? Remember that & is a meta '
  2001. 'character in most shells, so you want to put the URL in quotes, '
  2002. 'like youtube-dl '
  2003. '"http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
  2004. ' or simply youtube-dl BaW_jenozKc .',
  2005. expected=True)
  2006. class YoutubeTruncatedIDIE(InfoExtractor):
  2007. IE_NAME = 'youtube:truncated_id'
  2008. IE_DESC = False # Do not list
  2009. _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
  2010. _TESTS = [{
  2011. 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
  2012. 'only_matching': True,
  2013. }]
  2014. def _real_extract(self, url):
  2015. video_id = self._match_id(url)
  2016. raise ExtractorError(
  2017. 'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),
  2018. expected=True)