youtube.py 84 KB

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