youtube.py 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826
  1. # coding: utf-8
  2. import collections
  3. import errno
  4. import io
  5. import itertools
  6. import json
  7. import os.path
  8. import re
  9. import string
  10. import struct
  11. import traceback
  12. import zlib
  13. from .common import InfoExtractor, SearchInfoExtractor
  14. from .subtitles import SubtitlesInfoExtractor
  15. from ..utils import (
  16. compat_chr,
  17. compat_parse_qs,
  18. compat_urllib_parse,
  19. compat_urllib_request,
  20. compat_urlparse,
  21. compat_str,
  22. clean_html,
  23. get_cachedir,
  24. get_element_by_id,
  25. get_element_by_attribute,
  26. ExtractorError,
  27. int_or_none,
  28. PagedList,
  29. RegexNotFoundError,
  30. unescapeHTML,
  31. unified_strdate,
  32. orderedSet,
  33. write_json_file,
  34. )
  35. class YoutubeBaseInfoExtractor(InfoExtractor):
  36. """Provide base functions for Youtube extractors"""
  37. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  38. _LANG_URL = r'https://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  39. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  40. _NETRC_MACHINE = 'youtube'
  41. # If True it will raise an error if no login info is provided
  42. _LOGIN_REQUIRED = False
  43. def _set_language(self):
  44. return bool(self._download_webpage(
  45. self._LANG_URL, None,
  46. note=u'Setting language', errnote='unable to set language',
  47. fatal=False))
  48. def _login(self):
  49. (username, password) = self._get_login_info()
  50. # No authentication to be performed
  51. if username is None:
  52. if self._LOGIN_REQUIRED:
  53. raise ExtractorError(u'No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  54. return False
  55. login_page = self._download_webpage(
  56. self._LOGIN_URL, None,
  57. note=u'Downloading login page',
  58. errnote=u'unable to fetch login page', fatal=False)
  59. if login_page is False:
  60. return
  61. galx = self._search_regex(r'(?s)<input.+?name="GALX".+?value="(.+?)"',
  62. login_page, u'Login GALX parameter')
  63. # Log in
  64. login_form_strs = {
  65. u'continue': u'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
  66. u'Email': username,
  67. u'GALX': galx,
  68. u'Passwd': password,
  69. u'PersistentCookie': u'yes',
  70. u'_utf8': u'霱',
  71. u'bgresponse': u'js_disabled',
  72. u'checkConnection': u'',
  73. u'checkedDomains': u'youtube',
  74. u'dnConn': u'',
  75. u'pstMsg': u'0',
  76. u'rmShown': u'1',
  77. u'secTok': u'',
  78. u'signIn': u'Sign in',
  79. u'timeStmp': u'',
  80. u'service': u'youtube',
  81. u'uilel': u'3',
  82. u'hl': u'en_US',
  83. }
  84. # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
  85. # chokes on unicode
  86. login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
  87. login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
  88. req = compat_urllib_request.Request(self._LOGIN_URL, login_data)
  89. login_results = self._download_webpage(
  90. req, None,
  91. note=u'Logging in', errnote=u'unable to log in', fatal=False)
  92. if login_results is False:
  93. return False
  94. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
  95. self._downloader.report_warning(u'unable to log in: bad username or password')
  96. return False
  97. return True
  98. def _confirm_age(self):
  99. age_form = {
  100. 'next_url': '/',
  101. 'action_confirm': 'Confirm',
  102. }
  103. req = compat_urllib_request.Request(self._AGE_URL, compat_urllib_parse.urlencode(age_form))
  104. self._download_webpage(
  105. req, None,
  106. note=u'Confirming age', errnote=u'Unable to confirm age')
  107. return True
  108. def _real_initialize(self):
  109. if self._downloader is None:
  110. return
  111. if not self._set_language():
  112. return
  113. if not self._login():
  114. return
  115. self._confirm_age()
  116. class YoutubeIE(YoutubeBaseInfoExtractor, SubtitlesInfoExtractor):
  117. IE_DESC = u'YouTube.com'
  118. _VALID_URL = r"""(?x)^
  119. (
  120. (?:https?://|//)? # http(s):// or protocol-independent URL (optional)
  121. (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/|
  122. (?:www\.)?deturl\.com/www\.youtube\.com/|
  123. (?:www\.)?pwnyoutube\.com|
  124. tube\.majestyc\.net/|
  125. youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
  126. (?:.*?\#/)? # handle anchor (#/) redirect urls
  127. (?: # the various things that can precede the ID:
  128. (?:(?:v|embed|e)/) # v/ or embed/ or e/
  129. |(?: # or the v= param in all its forms
  130. (?:(?:watch|movie)(?:_popup)?(?:\.php)?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  131. (?:\?|\#!?) # the params delimiter ? or # or #!
  132. (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
  133. v=
  134. )
  135. ))
  136. |youtu\.be/ # just youtu.be/xxxx
  137. )
  138. )? # all until now is optional -> you can pass the naked ID
  139. ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
  140. (?(1).+)? # if we found the ID, everything can follow
  141. $"""
  142. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  143. _formats = {
  144. '5': {'ext': 'flv', 'width': 400, 'height': 240},
  145. '6': {'ext': 'flv', 'width': 450, 'height': 270},
  146. '13': {'ext': '3gp'},
  147. '17': {'ext': '3gp', 'width': 176, 'height': 144},
  148. '18': {'ext': 'mp4', 'width': 640, 'height': 360},
  149. '22': {'ext': 'mp4', 'width': 1280, 'height': 720},
  150. '34': {'ext': 'flv', 'width': 640, 'height': 360},
  151. '35': {'ext': 'flv', 'width': 854, 'height': 480},
  152. '36': {'ext': '3gp', 'width': 320, 'height': 240},
  153. '37': {'ext': 'mp4', 'width': 1920, 'height': 1080},
  154. '38': {'ext': 'mp4', 'width': 4096, 'height': 3072},
  155. '43': {'ext': 'webm', 'width': 640, 'height': 360},
  156. '44': {'ext': 'webm', 'width': 854, 'height': 480},
  157. '45': {'ext': 'webm', 'width': 1280, 'height': 720},
  158. '46': {'ext': 'webm', 'width': 1920, 'height': 1080},
  159. # 3d videos
  160. '82': {'ext': 'mp4', 'height': 360, 'resolution': '360p', 'format_note': '3D', 'preference': -20},
  161. '83': {'ext': 'mp4', 'height': 480, 'resolution': '480p', 'format_note': '3D', 'preference': -20},
  162. '84': {'ext': 'mp4', 'height': 720, 'resolution': '720p', 'format_note': '3D', 'preference': -20},
  163. '85': {'ext': 'mp4', 'height': 1080, 'resolution': '1080p', 'format_note': '3D', 'preference': -20},
  164. '100': {'ext': 'webm', 'height': 360, 'resolution': '360p', 'format_note': '3D', 'preference': -20},
  165. '101': {'ext': 'webm', 'height': 480, 'resolution': '480p', 'format_note': '3D', 'preference': -20},
  166. '102': {'ext': 'webm', 'height': 720, 'resolution': '720p', 'format_note': '3D', 'preference': -20},
  167. # Apple HTTP Live Streaming
  168. '92': {'ext': 'mp4', 'height': 240, 'resolution': '240p', 'format_note': 'HLS', 'preference': -10},
  169. '93': {'ext': 'mp4', 'height': 360, 'resolution': '360p', 'format_note': 'HLS', 'preference': -10},
  170. '94': {'ext': 'mp4', 'height': 480, 'resolution': '480p', 'format_note': 'HLS', 'preference': -10},
  171. '95': {'ext': 'mp4', 'height': 720, 'resolution': '720p', 'format_note': 'HLS', 'preference': -10},
  172. '96': {'ext': 'mp4', 'height': 1080, 'resolution': '1080p', 'format_note': 'HLS', 'preference': -10},
  173. '132': {'ext': 'mp4', 'height': 240, 'resolution': '240p', 'format_note': 'HLS', 'preference': -10},
  174. '151': {'ext': 'mp4', 'height': 72, 'resolution': '72p', 'format_note': 'HLS', 'preference': -10},
  175. # DASH mp4 video
  176. '133': {'ext': 'mp4', 'height': 240, 'resolution': '240p', 'format_note': 'DASH video', 'preference': -40},
  177. '134': {'ext': 'mp4', 'height': 360, 'resolution': '360p', 'format_note': 'DASH video', 'preference': -40},
  178. '135': {'ext': 'mp4', 'height': 480, 'resolution': '480p', 'format_note': 'DASH video', 'preference': -40},
  179. '136': {'ext': 'mp4', 'height': 720, 'resolution': '720p', 'format_note': 'DASH video', 'preference': -40},
  180. '137': {'ext': 'mp4', 'height': 1080, 'resolution': '1080p', 'format_note': 'DASH video', 'preference': -40},
  181. '138': {'ext': 'mp4', 'height': 1081, 'resolution': '>1080p', 'format_note': 'DASH video', 'preference': -40},
  182. '160': {'ext': 'mp4', 'height': 192, 'resolution': '192p', 'format_note': 'DASH video', 'preference': -40},
  183. '264': {'ext': 'mp4', 'height': 1080, 'resolution': '1080p', 'format_note': 'DASH video', 'preference': -40},
  184. # Dash mp4 audio
  185. '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 48, 'preference': -50},
  186. '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 128, 'preference': -50},
  187. '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 256, 'preference': -50},
  188. # Dash webm
  189. '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'VP8', 'acodec': 'none', 'preference': -40},
  190. '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'VP8', 'acodec': 'none', 'preference': -40},
  191. '168': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'VP8', 'acodec': 'none', 'preference': -40},
  192. '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'VP8', 'acodec': 'none', 'preference': -40},
  193. '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'VP8', 'acodec': 'none', 'preference': -40},
  194. '242': {'ext': 'webm', 'height': 240, 'resolution': '240p', 'format_note': 'DASH webm', 'preference': -40},
  195. '243': {'ext': 'webm', 'height': 360, 'resolution': '360p', 'format_note': 'DASH webm', 'preference': -40},
  196. '244': {'ext': 'webm', 'height': 480, 'resolution': '480p', 'format_note': 'DASH webm', 'preference': -40},
  197. '245': {'ext': 'webm', 'height': 480, 'resolution': '480p', 'format_note': 'DASH webm', 'preference': -40},
  198. '246': {'ext': 'webm', 'height': 480, 'resolution': '480p', 'format_note': 'DASH webm', 'preference': -40},
  199. '247': {'ext': 'webm', 'height': 720, 'resolution': '720p', 'format_note': 'DASH webm', 'preference': -40},
  200. '248': {'ext': 'webm', 'height': 1080, 'resolution': '1080p', 'format_note': 'DASH webm', 'preference': -40},
  201. # Dash webm audio
  202. '171': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH webm audio', 'abr': 48, 'preference': -50},
  203. '172': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH webm audio', 'abr': 256, 'preference': -50},
  204. # RTMP (unnamed)
  205. '_rtmp': {'protocol': 'rtmp'},
  206. }
  207. IE_NAME = u'youtube'
  208. _TESTS = [
  209. {
  210. u"url": u"http://www.youtube.com/watch?v=BaW_jenozKc",
  211. u"file": u"BaW_jenozKc.mp4",
  212. u"info_dict": {
  213. u"title": u"youtube-dl test video \"'/\\ä↭𝕐",
  214. u"uploader": u"Philipp Hagemeister",
  215. u"uploader_id": u"phihag",
  216. u"upload_date": u"20121002",
  217. u"description": u"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 ."
  218. }
  219. },
  220. {
  221. u"url": u"http://www.youtube.com/watch?v=UxxajLWwzqY",
  222. u"file": u"UxxajLWwzqY.mp4",
  223. u"note": u"Test generic use_cipher_signature video (#897)",
  224. u"info_dict": {
  225. u"upload_date": u"20120506",
  226. u"title": u"Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]",
  227. u"description": u"md5:5b292926389560516e384ac437c0ec07",
  228. u"uploader": u"Icona Pop",
  229. u"uploader_id": u"IconaPop"
  230. }
  231. },
  232. {
  233. u"url": u"https://www.youtube.com/watch?v=07FYdnEawAQ",
  234. u"file": u"07FYdnEawAQ.mp4",
  235. u"note": u"Test VEVO video with age protection (#956)",
  236. u"info_dict": {
  237. u"upload_date": u"20130703",
  238. u"title": u"Justin Timberlake - Tunnel Vision (Explicit)",
  239. u"description": u"md5:64249768eec3bc4276236606ea996373",
  240. u"uploader": u"justintimberlakeVEVO",
  241. u"uploader_id": u"justintimberlakeVEVO"
  242. }
  243. },
  244. {
  245. u"url": u"//www.YouTube.com/watch?v=yZIXLfi8CZQ",
  246. u"file": u"yZIXLfi8CZQ.mp4",
  247. u"note": u"Embed-only video (#1746)",
  248. u"info_dict": {
  249. u"upload_date": u"20120608",
  250. u"title": u"Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012",
  251. u"description": u"md5:09b78bd971f1e3e289601dfba15ca4f7",
  252. u"uploader": u"SET India",
  253. u"uploader_id": u"setindia"
  254. }
  255. },
  256. {
  257. u"url": u"http://www.youtube.com/watch?v=a9LDPn-MO4I",
  258. u"file": u"a9LDPn-MO4I.m4a",
  259. u"note": u"256k DASH audio (format 141) via DASH manifest",
  260. u"info_dict": {
  261. u"upload_date": "20121002",
  262. u"uploader_id": "8KVIDEO",
  263. u"description": "No description available.",
  264. u"uploader": "8KVIDEO",
  265. u"title": "UHDTV TEST 8K VIDEO.mp4"
  266. },
  267. u"params": {
  268. u"youtube_include_dash_manifest": True,
  269. u"format": "141",
  270. },
  271. },
  272. ]
  273. @classmethod
  274. def suitable(cls, url):
  275. """Receives a URL and returns True if suitable for this IE."""
  276. if YoutubePlaylistIE.suitable(url): return False
  277. return re.match(cls._VALID_URL, url) is not None
  278. def __init__(self, *args, **kwargs):
  279. super(YoutubeIE, self).__init__(*args, **kwargs)
  280. self._player_cache = {}
  281. def report_video_info_webpage_download(self, video_id):
  282. """Report attempt to download video info webpage."""
  283. self.to_screen(u'%s: Downloading video info webpage' % video_id)
  284. def report_information_extraction(self, video_id):
  285. """Report attempt to extract video information."""
  286. self.to_screen(u'%s: Extracting video information' % video_id)
  287. def report_unavailable_format(self, video_id, format):
  288. """Report extracted video URL."""
  289. self.to_screen(u'%s: Format %s not available' % (video_id, format))
  290. def report_rtmp_download(self):
  291. """Indicate the download will use the RTMP protocol."""
  292. self.to_screen(u'RTMP download detected')
  293. def _extract_signature_function(self, video_id, player_url, slen):
  294. id_m = re.match(r'.*-(?P<id>[a-zA-Z0-9_-]+)\.(?P<ext>[a-z]+)$',
  295. player_url)
  296. player_type = id_m.group('ext')
  297. player_id = id_m.group('id')
  298. # Read from filesystem cache
  299. func_id = '%s_%s_%d' % (player_type, player_id, slen)
  300. assert os.path.basename(func_id) == func_id
  301. cache_dir = get_cachedir(self._downloader.params)
  302. cache_enabled = cache_dir is not None
  303. if cache_enabled:
  304. cache_fn = os.path.join(os.path.expanduser(cache_dir),
  305. u'youtube-sigfuncs',
  306. func_id + '.json')
  307. try:
  308. with io.open(cache_fn, 'r', encoding='utf-8') as cachef:
  309. cache_spec = json.load(cachef)
  310. return lambda s: u''.join(s[i] for i in cache_spec)
  311. except IOError:
  312. pass # No cache available
  313. if player_type == 'js':
  314. code = self._download_webpage(
  315. player_url, video_id,
  316. note=u'Downloading %s player %s' % (player_type, player_id),
  317. errnote=u'Download of %s failed' % player_url)
  318. res = self._parse_sig_js(code)
  319. elif player_type == 'swf':
  320. urlh = self._request_webpage(
  321. player_url, video_id,
  322. note=u'Downloading %s player %s' % (player_type, player_id),
  323. errnote=u'Download of %s failed' % player_url)
  324. code = urlh.read()
  325. res = self._parse_sig_swf(code)
  326. else:
  327. assert False, 'Invalid player type %r' % player_type
  328. if cache_enabled:
  329. try:
  330. test_string = u''.join(map(compat_chr, range(slen)))
  331. cache_res = res(test_string)
  332. cache_spec = [ord(c) for c in cache_res]
  333. try:
  334. os.makedirs(os.path.dirname(cache_fn))
  335. except OSError as ose:
  336. if ose.errno != errno.EEXIST:
  337. raise
  338. write_json_file(cache_spec, cache_fn)
  339. except Exception:
  340. tb = traceback.format_exc()
  341. self._downloader.report_warning(
  342. u'Writing cache to %r failed: %s' % (cache_fn, tb))
  343. return res
  344. def _print_sig_code(self, func, slen):
  345. def gen_sig_code(idxs):
  346. def _genslice(start, end, step):
  347. starts = u'' if start == 0 else str(start)
  348. ends = (u':%d' % (end+step)) if end + step >= 0 else u':'
  349. steps = u'' if step == 1 else (u':%d' % step)
  350. return u's[%s%s%s]' % (starts, ends, steps)
  351. step = None
  352. start = '(Never used)' # Quelch pyflakes warnings - start will be
  353. # set as soon as step is set
  354. for i, prev in zip(idxs[1:], idxs[:-1]):
  355. if step is not None:
  356. if i - prev == step:
  357. continue
  358. yield _genslice(start, prev, step)
  359. step = None
  360. continue
  361. if i - prev in [-1, 1]:
  362. step = i - prev
  363. start = prev
  364. continue
  365. else:
  366. yield u's[%d]' % prev
  367. if step is None:
  368. yield u's[%d]' % i
  369. else:
  370. yield _genslice(start, i, step)
  371. test_string = u''.join(map(compat_chr, range(slen)))
  372. cache_res = func(test_string)
  373. cache_spec = [ord(c) for c in cache_res]
  374. expr_code = u' + '.join(gen_sig_code(cache_spec))
  375. code = u'if len(s) == %d:\n return %s\n' % (slen, expr_code)
  376. self.to_screen(u'Extracted signature function:\n' + code)
  377. def _parse_sig_js(self, jscode):
  378. funcname = self._search_regex(
  379. r'signature=([a-zA-Z]+)', jscode,
  380. u'Initial JS player signature function name')
  381. functions = {}
  382. def argidx(varname):
  383. return string.lowercase.index(varname)
  384. def interpret_statement(stmt, local_vars, allow_recursion=20):
  385. if allow_recursion < 0:
  386. raise ExtractorError(u'Recursion limit reached')
  387. if stmt.startswith(u'var '):
  388. stmt = stmt[len(u'var '):]
  389. ass_m = re.match(r'^(?P<out>[a-z]+)(?:\[(?P<index>[^\]]+)\])?' +
  390. r'=(?P<expr>.*)$', stmt)
  391. if ass_m:
  392. if ass_m.groupdict().get('index'):
  393. def assign(val):
  394. lvar = local_vars[ass_m.group('out')]
  395. idx = interpret_expression(ass_m.group('index'),
  396. local_vars, allow_recursion)
  397. assert isinstance(idx, int)
  398. lvar[idx] = val
  399. return val
  400. expr = ass_m.group('expr')
  401. else:
  402. def assign(val):
  403. local_vars[ass_m.group('out')] = val
  404. return val
  405. expr = ass_m.group('expr')
  406. elif stmt.startswith(u'return '):
  407. assign = lambda v: v
  408. expr = stmt[len(u'return '):]
  409. else:
  410. raise ExtractorError(
  411. u'Cannot determine left side of statement in %r' % stmt)
  412. v = interpret_expression(expr, local_vars, allow_recursion)
  413. return assign(v)
  414. def interpret_expression(expr, local_vars, allow_recursion):
  415. if expr.isdigit():
  416. return int(expr)
  417. if expr.isalpha():
  418. return local_vars[expr]
  419. m = re.match(r'^(?P<in>[a-z]+)\.(?P<member>.*)$', expr)
  420. if m:
  421. member = m.group('member')
  422. val = local_vars[m.group('in')]
  423. if member == 'split("")':
  424. return list(val)
  425. if member == 'join("")':
  426. return u''.join(val)
  427. if member == 'length':
  428. return len(val)
  429. if member == 'reverse()':
  430. return val[::-1]
  431. slice_m = re.match(r'slice\((?P<idx>.*)\)', member)
  432. if slice_m:
  433. idx = interpret_expression(
  434. slice_m.group('idx'), local_vars, allow_recursion-1)
  435. return val[idx:]
  436. m = re.match(
  437. r'^(?P<in>[a-z]+)\[(?P<idx>.+)\]$', expr)
  438. if m:
  439. val = local_vars[m.group('in')]
  440. idx = interpret_expression(m.group('idx'), local_vars,
  441. allow_recursion-1)
  442. return val[idx]
  443. m = re.match(r'^(?P<a>.+?)(?P<op>[%])(?P<b>.+?)$', expr)
  444. if m:
  445. a = interpret_expression(m.group('a'),
  446. local_vars, allow_recursion)
  447. b = interpret_expression(m.group('b'),
  448. local_vars, allow_recursion)
  449. return a % b
  450. m = re.match(
  451. r'^(?P<func>[a-zA-Z]+)\((?P<args>[a-z0-9,]+)\)$', expr)
  452. if m:
  453. fname = m.group('func')
  454. if fname not in functions:
  455. functions[fname] = extract_function(fname)
  456. argvals = [int(v) if v.isdigit() else local_vars[v]
  457. for v in m.group('args').split(',')]
  458. return functions[fname](argvals)
  459. raise ExtractorError(u'Unsupported JS expression %r' % expr)
  460. def extract_function(funcname):
  461. func_m = re.search(
  462. r'function ' + re.escape(funcname) +
  463. r'\((?P<args>[a-z,]+)\){(?P<code>[^}]+)}',
  464. jscode)
  465. argnames = func_m.group('args').split(',')
  466. def resf(args):
  467. local_vars = dict(zip(argnames, args))
  468. for stmt in func_m.group('code').split(';'):
  469. res = interpret_statement(stmt, local_vars)
  470. return res
  471. return resf
  472. initial_function = extract_function(funcname)
  473. return lambda s: initial_function([s])
  474. def _parse_sig_swf(self, file_contents):
  475. if file_contents[1:3] != b'WS':
  476. raise ExtractorError(
  477. u'Not an SWF file; header is %r' % file_contents[:3])
  478. if file_contents[:1] == b'C':
  479. content = zlib.decompress(file_contents[8:])
  480. else:
  481. raise NotImplementedError(u'Unsupported compression format %r' %
  482. file_contents[:1])
  483. def extract_tags(content):
  484. pos = 0
  485. while pos < len(content):
  486. header16 = struct.unpack('<H', content[pos:pos+2])[0]
  487. pos += 2
  488. tag_code = header16 >> 6
  489. tag_len = header16 & 0x3f
  490. if tag_len == 0x3f:
  491. tag_len = struct.unpack('<I', content[pos:pos+4])[0]
  492. pos += 4
  493. assert pos+tag_len <= len(content)
  494. yield (tag_code, content[pos:pos+tag_len])
  495. pos += tag_len
  496. code_tag = next(tag
  497. for tag_code, tag in extract_tags(content)
  498. if tag_code == 82)
  499. p = code_tag.index(b'\0', 4) + 1
  500. code_reader = io.BytesIO(code_tag[p:])
  501. # Parse ABC (AVM2 ByteCode)
  502. def read_int(reader=None):
  503. if reader is None:
  504. reader = code_reader
  505. res = 0
  506. shift = 0
  507. for _ in range(5):
  508. buf = reader.read(1)
  509. assert len(buf) == 1
  510. b = struct.unpack('<B', buf)[0]
  511. res = res | ((b & 0x7f) << shift)
  512. if b & 0x80 == 0:
  513. break
  514. shift += 7
  515. return res
  516. def u30(reader=None):
  517. res = read_int(reader)
  518. assert res & 0xf0000000 == 0
  519. return res
  520. u32 = read_int
  521. def s32(reader=None):
  522. v = read_int(reader)
  523. if v & 0x80000000 != 0:
  524. v = - ((v ^ 0xffffffff) + 1)
  525. return v
  526. def read_string(reader=None):
  527. if reader is None:
  528. reader = code_reader
  529. slen = u30(reader)
  530. resb = reader.read(slen)
  531. assert len(resb) == slen
  532. return resb.decode('utf-8')
  533. def read_bytes(count, reader=None):
  534. if reader is None:
  535. reader = code_reader
  536. resb = reader.read(count)
  537. assert len(resb) == count
  538. return resb
  539. def read_byte(reader=None):
  540. resb = read_bytes(1, reader=reader)
  541. res = struct.unpack('<B', resb)[0]
  542. return res
  543. # minor_version + major_version
  544. read_bytes(2 + 2)
  545. # Constant pool
  546. int_count = u30()
  547. for _c in range(1, int_count):
  548. s32()
  549. uint_count = u30()
  550. for _c in range(1, uint_count):
  551. u32()
  552. double_count = u30()
  553. read_bytes((double_count-1) * 8)
  554. string_count = u30()
  555. constant_strings = [u'']
  556. for _c in range(1, string_count):
  557. s = read_string()
  558. constant_strings.append(s)
  559. namespace_count = u30()
  560. for _c in range(1, namespace_count):
  561. read_bytes(1) # kind
  562. u30() # name
  563. ns_set_count = u30()
  564. for _c in range(1, ns_set_count):
  565. count = u30()
  566. for _c2 in range(count):
  567. u30()
  568. multiname_count = u30()
  569. MULTINAME_SIZES = {
  570. 0x07: 2, # QName
  571. 0x0d: 2, # QNameA
  572. 0x0f: 1, # RTQName
  573. 0x10: 1, # RTQNameA
  574. 0x11: 0, # RTQNameL
  575. 0x12: 0, # RTQNameLA
  576. 0x09: 2, # Multiname
  577. 0x0e: 2, # MultinameA
  578. 0x1b: 1, # MultinameL
  579. 0x1c: 1, # MultinameLA
  580. }
  581. multinames = [u'']
  582. for _c in range(1, multiname_count):
  583. kind = u30()
  584. assert kind in MULTINAME_SIZES, u'Invalid multiname kind %r' % kind
  585. if kind == 0x07:
  586. u30() # namespace_idx
  587. name_idx = u30()
  588. multinames.append(constant_strings[name_idx])
  589. else:
  590. multinames.append('[MULTINAME kind: %d]' % kind)
  591. for _c2 in range(MULTINAME_SIZES[kind]):
  592. u30()
  593. # Methods
  594. method_count = u30()
  595. MethodInfo = collections.namedtuple(
  596. 'MethodInfo',
  597. ['NEED_ARGUMENTS', 'NEED_REST'])
  598. method_infos = []
  599. for method_id in range(method_count):
  600. param_count = u30()
  601. u30() # return type
  602. for _ in range(param_count):
  603. u30() # param type
  604. u30() # name index (always 0 for youtube)
  605. flags = read_byte()
  606. if flags & 0x08 != 0:
  607. # Options present
  608. option_count = u30()
  609. for c in range(option_count):
  610. u30() # val
  611. read_bytes(1) # kind
  612. if flags & 0x80 != 0:
  613. # Param names present
  614. for _ in range(param_count):
  615. u30() # param name
  616. mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)
  617. method_infos.append(mi)
  618. # Metadata
  619. metadata_count = u30()
  620. for _c in range(metadata_count):
  621. u30() # name
  622. item_count = u30()
  623. for _c2 in range(item_count):
  624. u30() # key
  625. u30() # value
  626. def parse_traits_info():
  627. trait_name_idx = u30()
  628. kind_full = read_byte()
  629. kind = kind_full & 0x0f
  630. attrs = kind_full >> 4
  631. methods = {}
  632. if kind in [0x00, 0x06]: # Slot or Const
  633. u30() # Slot id
  634. u30() # type_name_idx
  635. vindex = u30()
  636. if vindex != 0:
  637. read_byte() # vkind
  638. elif kind in [0x01, 0x02, 0x03]: # Method / Getter / Setter
  639. u30() # disp_id
  640. method_idx = u30()
  641. methods[multinames[trait_name_idx]] = method_idx
  642. elif kind == 0x04: # Class
  643. u30() # slot_id
  644. u30() # classi
  645. elif kind == 0x05: # Function
  646. u30() # slot_id
  647. function_idx = u30()
  648. methods[function_idx] = multinames[trait_name_idx]
  649. else:
  650. raise ExtractorError(u'Unsupported trait kind %d' % kind)
  651. if attrs & 0x4 != 0: # Metadata present
  652. metadata_count = u30()
  653. for _c3 in range(metadata_count):
  654. u30() # metadata index
  655. return methods
  656. # Classes
  657. TARGET_CLASSNAME = u'SignatureDecipher'
  658. searched_idx = multinames.index(TARGET_CLASSNAME)
  659. searched_class_id = None
  660. class_count = u30()
  661. for class_id in range(class_count):
  662. name_idx = u30()
  663. if name_idx == searched_idx:
  664. # We found the class we're looking for!
  665. searched_class_id = class_id
  666. u30() # super_name idx
  667. flags = read_byte()
  668. if flags & 0x08 != 0: # Protected namespace is present
  669. u30() # protected_ns_idx
  670. intrf_count = u30()
  671. for _c2 in range(intrf_count):
  672. u30()
  673. u30() # iinit
  674. trait_count = u30()
  675. for _c2 in range(trait_count):
  676. parse_traits_info()
  677. if searched_class_id is None:
  678. raise ExtractorError(u'Target class %r not found' %
  679. TARGET_CLASSNAME)
  680. method_names = {}
  681. method_idxs = {}
  682. for class_id in range(class_count):
  683. u30() # cinit
  684. trait_count = u30()
  685. for _c2 in range(trait_count):
  686. trait_methods = parse_traits_info()
  687. if class_id == searched_class_id:
  688. method_names.update(trait_methods.items())
  689. method_idxs.update(dict(
  690. (idx, name)
  691. for name, idx in trait_methods.items()))
  692. # Scripts
  693. script_count = u30()
  694. for _c in range(script_count):
  695. u30() # init
  696. trait_count = u30()
  697. for _c2 in range(trait_count):
  698. parse_traits_info()
  699. # Method bodies
  700. method_body_count = u30()
  701. Method = collections.namedtuple('Method', ['code', 'local_count'])
  702. methods = {}
  703. for _c in range(method_body_count):
  704. method_idx = u30()
  705. u30() # max_stack
  706. local_count = u30()
  707. u30() # init_scope_depth
  708. u30() # max_scope_depth
  709. code_length = u30()
  710. code = read_bytes(code_length)
  711. if method_idx in method_idxs:
  712. m = Method(code, local_count)
  713. methods[method_idxs[method_idx]] = m
  714. exception_count = u30()
  715. for _c2 in range(exception_count):
  716. u30() # from
  717. u30() # to
  718. u30() # target
  719. u30() # exc_type
  720. u30() # var_name
  721. trait_count = u30()
  722. for _c2 in range(trait_count):
  723. parse_traits_info()
  724. assert p + code_reader.tell() == len(code_tag)
  725. assert len(methods) == len(method_idxs)
  726. method_pyfunctions = {}
  727. def extract_function(func_name):
  728. if func_name in method_pyfunctions:
  729. return method_pyfunctions[func_name]
  730. if func_name not in methods:
  731. raise ExtractorError(u'Cannot find function %r' % func_name)
  732. m = methods[func_name]
  733. def resfunc(args):
  734. registers = ['(this)'] + list(args) + [None] * m.local_count
  735. stack = []
  736. coder = io.BytesIO(m.code)
  737. while True:
  738. opcode = struct.unpack('!B', coder.read(1))[0]
  739. if opcode == 36: # pushbyte
  740. v = struct.unpack('!B', coder.read(1))[0]
  741. stack.append(v)
  742. elif opcode == 44: # pushstring
  743. idx = u30(coder)
  744. stack.append(constant_strings[idx])
  745. elif opcode == 48: # pushscope
  746. # We don't implement the scope register, so we'll just
  747. # ignore the popped value
  748. stack.pop()
  749. elif opcode == 70: # callproperty
  750. index = u30(coder)
  751. mname = multinames[index]
  752. arg_count = u30(coder)
  753. args = list(reversed(
  754. [stack.pop() for _ in range(arg_count)]))
  755. obj = stack.pop()
  756. if mname == u'split':
  757. assert len(args) == 1
  758. assert isinstance(args[0], compat_str)
  759. assert isinstance(obj, compat_str)
  760. if args[0] == u'':
  761. res = list(obj)
  762. else:
  763. res = obj.split(args[0])
  764. stack.append(res)
  765. elif mname == u'slice':
  766. assert len(args) == 1
  767. assert isinstance(args[0], int)
  768. assert isinstance(obj, list)
  769. res = obj[args[0]:]
  770. stack.append(res)
  771. elif mname == u'join':
  772. assert len(args) == 1
  773. assert isinstance(args[0], compat_str)
  774. assert isinstance(obj, list)
  775. res = args[0].join(obj)
  776. stack.append(res)
  777. elif mname in method_pyfunctions:
  778. stack.append(method_pyfunctions[mname](args))
  779. else:
  780. raise NotImplementedError(
  781. u'Unsupported property %r on %r'
  782. % (mname, obj))
  783. elif opcode == 72: # returnvalue
  784. res = stack.pop()
  785. return res
  786. elif opcode == 79: # callpropvoid
  787. index = u30(coder)
  788. mname = multinames[index]
  789. arg_count = u30(coder)
  790. args = list(reversed(
  791. [stack.pop() for _ in range(arg_count)]))
  792. obj = stack.pop()
  793. if mname == u'reverse':
  794. assert isinstance(obj, list)
  795. obj.reverse()
  796. else:
  797. raise NotImplementedError(
  798. u'Unsupported (void) property %r on %r'
  799. % (mname, obj))
  800. elif opcode == 93: # findpropstrict
  801. index = u30(coder)
  802. mname = multinames[index]
  803. res = extract_function(mname)
  804. stack.append(res)
  805. elif opcode == 97: # setproperty
  806. index = u30(coder)
  807. value = stack.pop()
  808. idx = stack.pop()
  809. obj = stack.pop()
  810. assert isinstance(obj, list)
  811. assert isinstance(idx, int)
  812. obj[idx] = value
  813. elif opcode == 98: # getlocal
  814. index = u30(coder)
  815. stack.append(registers[index])
  816. elif opcode == 99: # setlocal
  817. index = u30(coder)
  818. value = stack.pop()
  819. registers[index] = value
  820. elif opcode == 102: # getproperty
  821. index = u30(coder)
  822. pname = multinames[index]
  823. if pname == u'length':
  824. obj = stack.pop()
  825. assert isinstance(obj, list)
  826. stack.append(len(obj))
  827. else: # Assume attribute access
  828. idx = stack.pop()
  829. assert isinstance(idx, int)
  830. obj = stack.pop()
  831. assert isinstance(obj, list)
  832. stack.append(obj[idx])
  833. elif opcode == 128: # coerce
  834. u30(coder)
  835. elif opcode == 133: # coerce_s
  836. assert isinstance(stack[-1], (type(None), compat_str))
  837. elif opcode == 164: # modulo
  838. value2 = stack.pop()
  839. value1 = stack.pop()
  840. res = value1 % value2
  841. stack.append(res)
  842. elif opcode == 208: # getlocal_0
  843. stack.append(registers[0])
  844. elif opcode == 209: # getlocal_1
  845. stack.append(registers[1])
  846. elif opcode == 210: # getlocal_2
  847. stack.append(registers[2])
  848. elif opcode == 211: # getlocal_3
  849. stack.append(registers[3])
  850. elif opcode == 214: # setlocal_2
  851. registers[2] = stack.pop()
  852. elif opcode == 215: # setlocal_3
  853. registers[3] = stack.pop()
  854. else:
  855. raise NotImplementedError(
  856. u'Unsupported opcode %d' % opcode)
  857. method_pyfunctions[func_name] = resfunc
  858. return resfunc
  859. initial_function = extract_function(u'decipher')
  860. return lambda s: initial_function([s])
  861. def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
  862. """Turn the encrypted s field into a working signature"""
  863. if player_url is not None:
  864. if player_url.startswith(u'//'):
  865. player_url = u'https:' + player_url
  866. try:
  867. player_id = (player_url, len(s))
  868. if player_id not in self._player_cache:
  869. func = self._extract_signature_function(
  870. video_id, player_url, len(s)
  871. )
  872. self._player_cache[player_id] = func
  873. func = self._player_cache[player_id]
  874. if self._downloader.params.get('youtube_print_sig_code'):
  875. self._print_sig_code(func, len(s))
  876. return func(s)
  877. except Exception:
  878. tb = traceback.format_exc()
  879. self._downloader.report_warning(
  880. u'Automatic signature extraction failed: ' + tb)
  881. self._downloader.report_warning(
  882. u'Warning: Falling back to static signature algorithm')
  883. return self._static_decrypt_signature(
  884. s, video_id, player_url, age_gate)
  885. def _static_decrypt_signature(self, s, video_id, player_url, age_gate):
  886. if age_gate:
  887. # The videos with age protection use another player, so the
  888. # algorithms can be different.
  889. if len(s) == 86:
  890. return s[2:63] + s[82] + s[64:82] + s[63]
  891. if len(s) == 93:
  892. return s[86:29:-1] + s[88] + s[28:5:-1]
  893. elif len(s) == 92:
  894. return s[25] + s[3:25] + s[0] + s[26:42] + s[79] + s[43:79] + s[91] + s[80:83]
  895. elif len(s) == 91:
  896. return s[84:27:-1] + s[86] + s[26:5:-1]
  897. elif len(s) == 90:
  898. return s[25] + s[3:25] + s[2] + s[26:40] + s[77] + s[41:77] + s[89] + s[78:81]
  899. elif len(s) == 89:
  900. return s[84:78:-1] + s[87] + s[77:60:-1] + s[0] + s[59:3:-1]
  901. elif len(s) == 88:
  902. return s[7:28] + s[87] + s[29:45] + s[55] + s[46:55] + s[2] + s[56:87] + s[28]
  903. elif len(s) == 87:
  904. return s[6:27] + s[4] + s[28:39] + s[27] + s[40:59] + s[2] + s[60:]
  905. elif len(s) == 86:
  906. return s[80:72:-1] + s[16] + s[71:39:-1] + s[72] + s[38:16:-1] + s[82] + s[15::-1]
  907. elif len(s) == 85:
  908. return s[3:11] + s[0] + s[12:55] + s[84] + s[56:84]
  909. elif len(s) == 84:
  910. return s[78:70:-1] + s[14] + s[69:37:-1] + s[70] + s[36:14:-1] + s[80] + s[:14][::-1]
  911. elif len(s) == 83:
  912. return s[80:63:-1] + s[0] + s[62:0:-1] + s[63]
  913. elif len(s) == 82:
  914. return s[80:37:-1] + s[7] + s[36:7:-1] + s[0] + s[6:0:-1] + s[37]
  915. elif len(s) == 81:
  916. return s[56] + s[79:56:-1] + s[41] + s[55:41:-1] + s[80] + s[40:34:-1] + s[0] + s[33:29:-1] + s[34] + s[28:9:-1] + s[29] + s[8:0:-1] + s[9]
  917. elif len(s) == 80:
  918. return s[1:19] + s[0] + s[20:68] + s[19] + s[69:80]
  919. elif len(s) == 79:
  920. return s[54] + s[77:54:-1] + s[39] + s[53:39:-1] + s[78] + s[38:34:-1] + s[0] + s[33:29:-1] + s[34] + s[28:9:-1] + s[29] + s[8:0:-1] + s[9]
  921. else:
  922. raise ExtractorError(u'Unable to decrypt signature, key length %d not supported; retrying might work' % (len(s)))
  923. def _get_available_subtitles(self, video_id, webpage):
  924. try:
  925. sub_list = self._download_webpage(
  926. 'http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  927. video_id, note=False)
  928. except ExtractorError as err:
  929. self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err))
  930. return {}
  931. lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
  932. sub_lang_list = {}
  933. for l in lang_list:
  934. lang = l[1]
  935. params = compat_urllib_parse.urlencode({
  936. 'lang': lang,
  937. 'v': video_id,
  938. 'fmt': self._downloader.params.get('subtitlesformat', 'srt'),
  939. 'name': unescapeHTML(l[0]).encode('utf-8'),
  940. })
  941. url = u'http://www.youtube.com/api/timedtext?' + params
  942. sub_lang_list[lang] = url
  943. if not sub_lang_list:
  944. self._downloader.report_warning(u'video doesn\'t have subtitles')
  945. return {}
  946. return sub_lang_list
  947. def _get_available_automatic_caption(self, video_id, webpage):
  948. """We need the webpage for getting the captions url, pass it as an
  949. argument to speed up the process."""
  950. sub_format = self._downloader.params.get('subtitlesformat', 'srt')
  951. self.to_screen(u'%s: Looking for automatic captions' % video_id)
  952. mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
  953. err_msg = u'Couldn\'t find automatic captions for %s' % video_id
  954. if mobj is None:
  955. self._downloader.report_warning(err_msg)
  956. return {}
  957. player_config = json.loads(mobj.group(1))
  958. try:
  959. args = player_config[u'args']
  960. caption_url = args[u'ttsurl']
  961. timestamp = args[u'timestamp']
  962. # We get the available subtitles
  963. list_params = compat_urllib_parse.urlencode({
  964. 'type': 'list',
  965. 'tlangs': 1,
  966. 'asrs': 1,
  967. })
  968. list_url = caption_url + '&' + list_params
  969. caption_list = self._download_xml(list_url, video_id)
  970. original_lang_node = caption_list.find('track')
  971. if original_lang_node is None or original_lang_node.attrib.get('kind') != 'asr' :
  972. self._downloader.report_warning(u'Video doesn\'t have automatic captions')
  973. return {}
  974. original_lang = original_lang_node.attrib['lang_code']
  975. sub_lang_list = {}
  976. for lang_node in caption_list.findall('target'):
  977. sub_lang = lang_node.attrib['lang_code']
  978. params = compat_urllib_parse.urlencode({
  979. 'lang': original_lang,
  980. 'tlang': sub_lang,
  981. 'fmt': sub_format,
  982. 'ts': timestamp,
  983. 'kind': 'asr',
  984. })
  985. sub_lang_list[sub_lang] = caption_url + '&' + params
  986. return sub_lang_list
  987. # An extractor error can be raise by the download process if there are
  988. # no automatic captions but there are subtitles
  989. except (KeyError, ExtractorError):
  990. self._downloader.report_warning(err_msg)
  991. return {}
  992. def _extract_id(self, url):
  993. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  994. if mobj is None:
  995. raise ExtractorError(u'Invalid URL: %s' % url)
  996. video_id = mobj.group(2)
  997. return video_id
  998. def _extract_from_m3u8(self, manifest_url, video_id):
  999. url_map = {}
  1000. def _get_urls(_manifest):
  1001. lines = _manifest.split('\n')
  1002. urls = filter(lambda l: l and not l.startswith('#'),
  1003. lines)
  1004. return urls
  1005. manifest = self._download_webpage(manifest_url, video_id, u'Downloading formats manifest')
  1006. formats_urls = _get_urls(manifest)
  1007. for format_url in formats_urls:
  1008. itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
  1009. url_map[itag] = format_url
  1010. return url_map
  1011. def _extract_annotations(self, video_id):
  1012. url = 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id
  1013. return self._download_webpage(url, video_id, note=u'Searching for annotations.', errnote=u'Unable to download video annotations.')
  1014. def _real_extract(self, url):
  1015. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  1016. mobj = re.search(self._NEXT_URL_RE, url)
  1017. if mobj:
  1018. url = 'https://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  1019. video_id = self._extract_id(url)
  1020. # Get video webpage
  1021. url = 'https://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
  1022. video_webpage = self._download_webpage(url, video_id)
  1023. # Attempt to extract SWF player URL
  1024. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  1025. if mobj is not None:
  1026. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  1027. else:
  1028. player_url = None
  1029. # Get video info
  1030. self.report_video_info_webpage_download(video_id)
  1031. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  1032. self.report_age_confirmation()
  1033. age_gate = True
  1034. # We simulate the access to the video from www.youtube.com/v/{video_id}
  1035. # this can be viewed without login into Youtube
  1036. data = compat_urllib_parse.urlencode({'video_id': video_id,
  1037. 'el': 'player_embedded',
  1038. 'gl': 'US',
  1039. 'hl': 'en',
  1040. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  1041. 'asv': 3,
  1042. 'sts':'1588',
  1043. })
  1044. video_info_url = 'https://www.youtube.com/get_video_info?' + data
  1045. video_info_webpage = self._download_webpage(video_info_url, video_id,
  1046. note=False,
  1047. errnote='unable to download video info webpage')
  1048. video_info = compat_parse_qs(video_info_webpage)
  1049. else:
  1050. age_gate = False
  1051. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  1052. video_info_url = ('https://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  1053. % (video_id, el_type))
  1054. video_info_webpage = self._download_webpage(video_info_url, video_id,
  1055. note=False,
  1056. errnote='unable to download video info webpage')
  1057. video_info = compat_parse_qs(video_info_webpage)
  1058. if 'token' in video_info:
  1059. break
  1060. if 'token' not in video_info:
  1061. if 'reason' in video_info:
  1062. raise ExtractorError(u'YouTube said: %s' % video_info['reason'][0], expected=True)
  1063. else:
  1064. raise ExtractorError(u'"token" parameter not in video info for unknown reason')
  1065. if 'view_count' in video_info:
  1066. view_count = int(video_info['view_count'][0])
  1067. else:
  1068. view_count = None
  1069. # Check for "rental" videos
  1070. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  1071. raise ExtractorError(u'"rental" videos not supported')
  1072. # Start extracting information
  1073. self.report_information_extraction(video_id)
  1074. # uploader
  1075. if 'author' not in video_info:
  1076. raise ExtractorError(u'Unable to extract uploader name')
  1077. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  1078. # uploader_id
  1079. video_uploader_id = None
  1080. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  1081. if mobj is not None:
  1082. video_uploader_id = mobj.group(1)
  1083. else:
  1084. self._downloader.report_warning(u'unable to extract uploader nickname')
  1085. # title
  1086. if 'title' in video_info:
  1087. video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
  1088. else:
  1089. self._downloader.report_warning(u'Unable to extract video title')
  1090. video_title = u'_'
  1091. # thumbnail image
  1092. # We try first to get a high quality image:
  1093. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  1094. video_webpage, re.DOTALL)
  1095. if m_thumb is not None:
  1096. video_thumbnail = m_thumb.group(1)
  1097. elif 'thumbnail_url' not in video_info:
  1098. self._downloader.report_warning(u'unable to extract video thumbnail')
  1099. video_thumbnail = None
  1100. else: # don't panic if we can't find it
  1101. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  1102. # upload date
  1103. upload_date = None
  1104. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  1105. if mobj is not None:
  1106. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  1107. upload_date = unified_strdate(upload_date)
  1108. # description
  1109. video_description = get_element_by_id("eow-description", video_webpage)
  1110. if video_description:
  1111. video_description = re.sub(r'''(?x)
  1112. <a\s+
  1113. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  1114. title="([^"]+)"\s+
  1115. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  1116. class="yt-uix-redirect-link"\s*>
  1117. [^<]+
  1118. </a>
  1119. ''', r'\1', video_description)
  1120. video_description = clean_html(video_description)
  1121. else:
  1122. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  1123. if fd_mobj:
  1124. video_description = unescapeHTML(fd_mobj.group(1))
  1125. else:
  1126. video_description = u''
  1127. def _extract_count(klass):
  1128. count = self._search_regex(
  1129. r'class="%s">([\d,]+)</span>' % re.escape(klass),
  1130. video_webpage, klass, default=None)
  1131. if count is not None:
  1132. return int(count.replace(',', ''))
  1133. return None
  1134. like_count = _extract_count(u'likes-count')
  1135. dislike_count = _extract_count(u'dislikes-count')
  1136. # subtitles
  1137. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  1138. if self._downloader.params.get('listsubtitles', False):
  1139. self._list_available_subtitles(video_id, video_webpage)
  1140. return
  1141. if 'length_seconds' not in video_info:
  1142. self._downloader.report_warning(u'unable to extract video duration')
  1143. video_duration = None
  1144. else:
  1145. video_duration = int(compat_urllib_parse.unquote_plus(video_info['length_seconds'][0]))
  1146. # annotations
  1147. video_annotations = None
  1148. if self._downloader.params.get('writeannotations', False):
  1149. video_annotations = self._extract_annotations(video_id)
  1150. # Decide which formats to download
  1151. try:
  1152. mobj = re.search(r';ytplayer.config = ({.*?});', video_webpage)
  1153. if not mobj:
  1154. raise ValueError('Could not find vevo ID')
  1155. info = json.loads(mobj.group(1))
  1156. args = info['args']
  1157. # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
  1158. # this signatures are encrypted
  1159. if 'url_encoded_fmt_stream_map' not in args:
  1160. raise ValueError(u'No stream_map present') # caught below
  1161. re_signature = re.compile(r'[&,]s=')
  1162. m_s = re_signature.search(args['url_encoded_fmt_stream_map'])
  1163. if m_s is not None:
  1164. self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
  1165. video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
  1166. m_s = re_signature.search(args.get('adaptive_fmts', u''))
  1167. if m_s is not None:
  1168. if 'adaptive_fmts' in video_info:
  1169. video_info['adaptive_fmts'][0] += ',' + args['adaptive_fmts']
  1170. else:
  1171. video_info['adaptive_fmts'] = [args['adaptive_fmts']]
  1172. except ValueError:
  1173. pass
  1174. def _map_to_format_list(urlmap):
  1175. formats = []
  1176. for itag, video_real_url in urlmap.items():
  1177. dct = {
  1178. 'format_id': itag,
  1179. 'url': video_real_url,
  1180. 'player_url': player_url,
  1181. }
  1182. if itag in self._formats:
  1183. dct.update(self._formats[itag])
  1184. formats.append(dct)
  1185. return formats
  1186. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  1187. self.report_rtmp_download()
  1188. formats = [{
  1189. 'format_id': '_rtmp',
  1190. 'protocol': 'rtmp',
  1191. 'url': video_info['conn'][0],
  1192. 'player_url': player_url,
  1193. }]
  1194. elif len(video_info.get('url_encoded_fmt_stream_map', [])) >= 1 or len(video_info.get('adaptive_fmts', [])) >= 1:
  1195. encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts',[''])[0]
  1196. if 'rtmpe%3Dyes' in encoded_url_map:
  1197. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
  1198. url_map = {}
  1199. for url_data_str in encoded_url_map.split(','):
  1200. url_data = compat_parse_qs(url_data_str)
  1201. if 'itag' in url_data and 'url' in url_data:
  1202. url = url_data['url'][0]
  1203. if 'sig' in url_data:
  1204. url += '&signature=' + url_data['sig'][0]
  1205. elif 's' in url_data:
  1206. encrypted_sig = url_data['s'][0]
  1207. if self._downloader.params.get('verbose'):
  1208. if age_gate:
  1209. if player_url is None:
  1210. player_version = 'unknown'
  1211. else:
  1212. player_version = self._search_regex(
  1213. r'-(.+)\.swf$', player_url,
  1214. u'flash player', fatal=False)
  1215. player_desc = 'flash player %s' % player_version
  1216. else:
  1217. player_version = self._search_regex(
  1218. r'html5player-(.+?)\.js', video_webpage,
  1219. 'html5 player', fatal=False)
  1220. player_desc = u'html5 player %s' % player_version
  1221. parts_sizes = u'.'.join(compat_str(len(part)) for part in encrypted_sig.split('.'))
  1222. self.to_screen(u'encrypted signature length %d (%s), itag %s, %s' %
  1223. (len(encrypted_sig), parts_sizes, url_data['itag'][0], player_desc))
  1224. if not age_gate:
  1225. jsplayer_url_json = self._search_regex(
  1226. r'"assets":.+?"js":\s*("[^"]+")',
  1227. video_webpage, u'JS player URL')
  1228. player_url = json.loads(jsplayer_url_json)
  1229. signature = self._decrypt_signature(
  1230. encrypted_sig, video_id, player_url, age_gate)
  1231. url += '&signature=' + signature
  1232. if 'ratebypass' not in url:
  1233. url += '&ratebypass=yes'
  1234. url_map[url_data['itag'][0]] = url
  1235. formats = _map_to_format_list(url_map)
  1236. elif video_info.get('hlsvp'):
  1237. manifest_url = video_info['hlsvp'][0]
  1238. url_map = self._extract_from_m3u8(manifest_url, video_id)
  1239. formats = _map_to_format_list(url_map)
  1240. else:
  1241. raise ExtractorError(u'no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
  1242. # Look for the DASH manifest
  1243. dash_manifest_url_lst = video_info.get('dashmpd')
  1244. if (dash_manifest_url_lst and dash_manifest_url_lst[0] and
  1245. self._downloader.params.get('youtube_include_dash_manifest', False)):
  1246. try:
  1247. dash_doc = self._download_xml(
  1248. dash_manifest_url_lst[0], video_id,
  1249. note=u'Downloading DASH manifest',
  1250. errnote=u'Could not download DASH manifest')
  1251. for r in dash_doc.findall(u'.//{urn:mpeg:DASH:schema:MPD:2011}Representation'):
  1252. url_el = r.find('{urn:mpeg:DASH:schema:MPD:2011}BaseURL')
  1253. if url_el is None:
  1254. continue
  1255. format_id = r.attrib['id']
  1256. video_url = url_el.text
  1257. filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength'))
  1258. f = {
  1259. 'format_id': format_id,
  1260. 'url': video_url,
  1261. 'width': int_or_none(r.attrib.get('width')),
  1262. 'tbr': int_or_none(r.attrib.get('bandwidth'), 1000),
  1263. 'asr': int_or_none(r.attrib.get('audioSamplingRate')),
  1264. 'filesize': filesize,
  1265. }
  1266. try:
  1267. existing_format = next(
  1268. fo for fo in formats
  1269. if fo['format_id'] == format_id)
  1270. except StopIteration:
  1271. f.update(self._formats.get(format_id, {}))
  1272. formats.append(f)
  1273. else:
  1274. existing_format.update(f)
  1275. except (ExtractorError, KeyError) as e:
  1276. self.report_warning(u'Skipping DASH manifest: %s' % e, video_id)
  1277. self._sort_formats(formats)
  1278. return {
  1279. 'id': video_id,
  1280. 'uploader': video_uploader,
  1281. 'uploader_id': video_uploader_id,
  1282. 'upload_date': upload_date,
  1283. 'title': video_title,
  1284. 'thumbnail': video_thumbnail,
  1285. 'description': video_description,
  1286. 'subtitles': video_subtitles,
  1287. 'duration': video_duration,
  1288. 'age_limit': 18 if age_gate else 0,
  1289. 'annotations': video_annotations,
  1290. 'webpage_url': 'https://www.youtube.com/watch?v=%s' % video_id,
  1291. 'view_count': view_count,
  1292. 'like_count': like_count,
  1293. 'dislike_count': dislike_count,
  1294. 'formats': formats,
  1295. }
  1296. class YoutubePlaylistIE(YoutubeBaseInfoExtractor):
  1297. IE_DESC = u'YouTube.com playlists'
  1298. _VALID_URL = r"""(?:
  1299. (?:https?://)?
  1300. (?:\w+\.)?
  1301. youtube\.com/
  1302. (?:
  1303. (?:course|view_play_list|my_playlists|artist|playlist|watch)
  1304. \? (?:.*?&)*? (?:p|a|list)=
  1305. | p/
  1306. )
  1307. ((?:PL|EC|UU|FL|RD)?[0-9A-Za-z-_]{10,})
  1308. .*
  1309. |
  1310. ((?:PL|EC|UU|FL|RD)[0-9A-Za-z-_]{10,})
  1311. )"""
  1312. _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s&page=%s'
  1313. _MORE_PAGES_INDICATOR = r'data-link-type="next"'
  1314. _VIDEO_RE = r'href="/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&amp;[^"]*?index=(?P<index>\d+)'
  1315. IE_NAME = u'youtube:playlist'
  1316. @classmethod
  1317. def suitable(cls, url):
  1318. """Receives a URL and returns True if suitable for this IE."""
  1319. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1320. def _real_initialize(self):
  1321. self._login()
  1322. def _ids_to_results(self, ids):
  1323. return [self.url_result(vid_id, 'Youtube', video_id=vid_id)
  1324. for vid_id in ids]
  1325. def _extract_mix(self, playlist_id):
  1326. # The mixes are generated from a a single video
  1327. # the id of the playlist is just 'RD' + video_id
  1328. url = 'https://youtube.com/watch?v=%s&list=%s' % (playlist_id[-11:], playlist_id)
  1329. webpage = self._download_webpage(url, playlist_id, u'Downloading Youtube mix')
  1330. title_span = (get_element_by_attribute('class', 'title long-title', webpage) or
  1331. get_element_by_attribute('class', 'title ', webpage))
  1332. title = clean_html(title_span)
  1333. video_re = r'data-index="\d+".*?href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s' % re.escape(playlist_id)
  1334. ids = orderedSet(re.findall(video_re, webpage))
  1335. url_results = self._ids_to_results(ids)
  1336. return self.playlist_result(url_results, playlist_id, title)
  1337. def _real_extract(self, url):
  1338. # Extract playlist id
  1339. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1340. if mobj is None:
  1341. raise ExtractorError(u'Invalid URL: %s' % url)
  1342. playlist_id = mobj.group(1) or mobj.group(2)
  1343. # Check if it's a video-specific URL
  1344. query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  1345. if 'v' in query_dict:
  1346. video_id = query_dict['v'][0]
  1347. if self._downloader.params.get('noplaylist'):
  1348. self.to_screen(u'Downloading just video %s because of --no-playlist' % video_id)
  1349. return self.url_result(video_id, 'Youtube', video_id=video_id)
  1350. else:
  1351. self.to_screen(u'Downloading playlist PL%s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  1352. if playlist_id.startswith('RD'):
  1353. # Mixes require a custom extraction process
  1354. return self._extract_mix(playlist_id)
  1355. if playlist_id.startswith('TL'):
  1356. raise ExtractorError(u'For downloading YouTube.com top lists, use '
  1357. u'the "yttoplist" keyword, for example "youtube-dl \'yttoplist:music:Top Tracks\'"', expected=True)
  1358. # Extract the video ids from the playlist pages
  1359. ids = []
  1360. for page_num in itertools.count(1):
  1361. url = self._TEMPLATE_URL % (playlist_id, page_num)
  1362. page = self._download_webpage(url, playlist_id, u'Downloading page #%s' % page_num)
  1363. matches = re.finditer(self._VIDEO_RE, page)
  1364. # We remove the duplicates and the link with index 0
  1365. # (it's not the first video of the playlist)
  1366. new_ids = orderedSet(m.group('id') for m in matches if m.group('index') != '0')
  1367. ids.extend(new_ids)
  1368. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1369. break
  1370. try:
  1371. playlist_title = self._og_search_title(page)
  1372. except RegexNotFoundError:
  1373. self.report_warning(
  1374. u'Playlist page is missing OpenGraph title, falling back ...',
  1375. playlist_id)
  1376. playlist_title = self._html_search_regex(
  1377. r'<h1 class="pl-header-title">(.*?)</h1>', page, u'title')
  1378. url_results = self._ids_to_results(ids)
  1379. return self.playlist_result(url_results, playlist_id, playlist_title)
  1380. class YoutubeTopListIE(YoutubePlaylistIE):
  1381. IE_NAME = u'youtube:toplist'
  1382. IE_DESC = (u'YouTube.com top lists, "yttoplist:{channel}:{list title}"'
  1383. u' (Example: "yttoplist:music:Top Tracks")')
  1384. _VALID_URL = r'yttoplist:(?P<chann>.*?):(?P<title>.*?)$'
  1385. def _real_extract(self, url):
  1386. mobj = re.match(self._VALID_URL, url)
  1387. channel = mobj.group('chann')
  1388. title = mobj.group('title')
  1389. query = compat_urllib_parse.urlencode({'title': title})
  1390. playlist_re = 'href="([^"]+?%s[^"]+?)"' % re.escape(query)
  1391. channel_page = self._download_webpage('https://www.youtube.com/%s' % channel, title)
  1392. link = self._html_search_regex(playlist_re, channel_page, u'list')
  1393. url = compat_urlparse.urljoin('https://www.youtube.com/', link)
  1394. video_re = r'data-index="\d+".*?data-video-id="([0-9A-Za-z_-]{11})"'
  1395. ids = []
  1396. # sometimes the webpage doesn't contain the videos
  1397. # retry until we get them
  1398. for i in itertools.count(0):
  1399. msg = u'Downloading Youtube mix'
  1400. if i > 0:
  1401. msg += ', retry #%d' % i
  1402. webpage = self._download_webpage(url, title, msg)
  1403. ids = orderedSet(re.findall(video_re, webpage))
  1404. if ids:
  1405. break
  1406. url_results = self._ids_to_results(ids)
  1407. return self.playlist_result(url_results, playlist_title=title)
  1408. class YoutubeChannelIE(InfoExtractor):
  1409. IE_DESC = u'YouTube.com channels'
  1410. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
  1411. _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
  1412. _MORE_PAGES_URL = 'http://www.youtube.com/c4_browse_ajax?action_load_more_videos=1&flow=list&paging=%s&view=0&sort=da&channel_id=%s'
  1413. IE_NAME = u'youtube:channel'
  1414. def extract_videos_from_page(self, page):
  1415. ids_in_page = []
  1416. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
  1417. if mobj.group(1) not in ids_in_page:
  1418. ids_in_page.append(mobj.group(1))
  1419. return ids_in_page
  1420. def _real_extract(self, url):
  1421. # Extract channel id
  1422. mobj = re.match(self._VALID_URL, url)
  1423. if mobj is None:
  1424. raise ExtractorError(u'Invalid URL: %s' % url)
  1425. # Download channel page
  1426. channel_id = mobj.group(1)
  1427. video_ids = []
  1428. url = 'https://www.youtube.com/channel/%s/videos' % channel_id
  1429. channel_page = self._download_webpage(url, channel_id)
  1430. autogenerated = re.search(r'''(?x)
  1431. class="[^"]*?(?:
  1432. channel-header-autogenerated-label|
  1433. yt-channel-title-autogenerated
  1434. )[^"]*"''', channel_page) is not None
  1435. if autogenerated:
  1436. # The videos are contained in a single page
  1437. # the ajax pages can't be used, they are empty
  1438. video_ids = self.extract_videos_from_page(channel_page)
  1439. else:
  1440. # Download all channel pages using the json-based channel_ajax query
  1441. for pagenum in itertools.count(1):
  1442. url = self._MORE_PAGES_URL % (pagenum, channel_id)
  1443. page = self._download_webpage(url, channel_id,
  1444. u'Downloading page #%s' % pagenum)
  1445. page = json.loads(page)
  1446. ids_in_page = self.extract_videos_from_page(page['content_html'])
  1447. video_ids.extend(ids_in_page)
  1448. if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
  1449. break
  1450. self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  1451. url_entries = [self.url_result(video_id, 'Youtube', video_id=video_id)
  1452. for video_id in video_ids]
  1453. return self.playlist_result(url_entries, channel_id)
  1454. class YoutubeUserIE(InfoExtractor):
  1455. IE_DESC = u'YouTube.com user videos (URL or "ytuser" keyword)'
  1456. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?(?!(?:attribution_link|watch)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)([A-Za-z0-9_-]+)'
  1457. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  1458. _GDATA_PAGE_SIZE = 50
  1459. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d&alt=json'
  1460. IE_NAME = u'youtube:user'
  1461. @classmethod
  1462. def suitable(cls, url):
  1463. # Don't return True if the url can be extracted with other youtube
  1464. # extractor, the regex would is too permissive and it would match.
  1465. other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls)
  1466. if any(ie.suitable(url) for ie in other_ies): return False
  1467. else: return super(YoutubeUserIE, cls).suitable(url)
  1468. def _real_extract(self, url):
  1469. # Extract username
  1470. mobj = re.match(self._VALID_URL, url)
  1471. if mobj is None:
  1472. raise ExtractorError(u'Invalid URL: %s' % url)
  1473. username = mobj.group(1)
  1474. # Download video ids using YouTube Data API. Result size per
  1475. # query is limited (currently to 50 videos) so we need to query
  1476. # page by page until there are no video ids - it means we got
  1477. # all of them.
  1478. def download_page(pagenum):
  1479. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1480. gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
  1481. page = self._download_webpage(
  1482. gdata_url, username,
  1483. u'Downloading video ids from %d to %d' % (
  1484. start_index, start_index + self._GDATA_PAGE_SIZE))
  1485. try:
  1486. response = json.loads(page)
  1487. except ValueError as err:
  1488. raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
  1489. if 'entry' not in response['feed']:
  1490. return
  1491. # Extract video identifiers
  1492. entries = response['feed']['entry']
  1493. for entry in entries:
  1494. title = entry['title']['$t']
  1495. video_id = entry['id']['$t'].split('/')[-1]
  1496. yield {
  1497. '_type': 'url',
  1498. 'url': video_id,
  1499. 'ie_key': 'Youtube',
  1500. 'id': 'video_id',
  1501. 'title': title,
  1502. }
  1503. url_results = PagedList(download_page, self._GDATA_PAGE_SIZE)
  1504. return self.playlist_result(url_results, playlist_title=username)
  1505. class YoutubeSearchIE(SearchInfoExtractor):
  1506. IE_DESC = u'YouTube.com searches'
  1507. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1508. _MAX_RESULTS = 1000
  1509. IE_NAME = u'youtube:search'
  1510. _SEARCH_KEY = 'ytsearch'
  1511. def _get_n_results(self, query, n):
  1512. """Get a specified number of results for a query"""
  1513. video_ids = []
  1514. pagenum = 0
  1515. limit = n
  1516. while (50 * pagenum) < limit:
  1517. result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
  1518. data_json = self._download_webpage(
  1519. result_url, video_id=u'query "%s"' % query,
  1520. note=u'Downloading page %s' % (pagenum + 1),
  1521. errnote=u'Unable to download API page')
  1522. data = json.loads(data_json)
  1523. api_response = data['data']
  1524. if 'items' not in api_response:
  1525. raise ExtractorError(u'[youtube] No video results')
  1526. new_ids = list(video['id'] for video in api_response['items'])
  1527. video_ids += new_ids
  1528. limit = min(n, api_response['totalItems'])
  1529. pagenum += 1
  1530. if len(video_ids) > n:
  1531. video_ids = video_ids[:n]
  1532. videos = [self.url_result(video_id, 'Youtube', video_id=video_id)
  1533. for video_id in video_ids]
  1534. return self.playlist_result(videos, query)
  1535. class YoutubeSearchDateIE(YoutubeSearchIE):
  1536. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  1537. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc&orderby=published'
  1538. _SEARCH_KEY = 'ytsearchdate'
  1539. IE_DESC = u'YouTube.com searches, newest videos first'
  1540. class YoutubeShowIE(InfoExtractor):
  1541. IE_DESC = u'YouTube.com (multi-season) shows'
  1542. _VALID_URL = r'https?://www\.youtube\.com/show/(.*)'
  1543. IE_NAME = u'youtube:show'
  1544. def _real_extract(self, url):
  1545. mobj = re.match(self._VALID_URL, url)
  1546. show_name = mobj.group(1)
  1547. webpage = self._download_webpage(url, show_name, u'Downloading show webpage')
  1548. # There's one playlist for each season of the show
  1549. m_seasons = list(re.finditer(r'href="(/playlist\?list=.*?)"', webpage))
  1550. self.to_screen(u'%s: Found %s seasons' % (show_name, len(m_seasons)))
  1551. return [self.url_result('https://www.youtube.com' + season.group(1), 'YoutubePlaylist') for season in m_seasons]
  1552. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  1553. """
  1554. Base class for extractors that fetch info from
  1555. http://www.youtube.com/feed_ajax
  1556. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  1557. """
  1558. _LOGIN_REQUIRED = True
  1559. # use action_load_personal_feed instead of action_load_system_feed
  1560. _PERSONAL_FEED = False
  1561. @property
  1562. def _FEED_TEMPLATE(self):
  1563. action = 'action_load_system_feed'
  1564. if self._PERSONAL_FEED:
  1565. action = 'action_load_personal_feed'
  1566. return 'http://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action, self._FEED_NAME)
  1567. @property
  1568. def IE_NAME(self):
  1569. return u'youtube:%s' % self._FEED_NAME
  1570. def _real_initialize(self):
  1571. self._login()
  1572. def _real_extract(self, url):
  1573. feed_entries = []
  1574. paging = 0
  1575. for i in itertools.count(1):
  1576. info = self._download_webpage(self._FEED_TEMPLATE % paging,
  1577. u'%s feed' % self._FEED_NAME,
  1578. u'Downloading page %s' % i)
  1579. info = json.loads(info)
  1580. feed_html = info['feed_html']
  1581. m_ids = re.finditer(r'"/watch\?v=(.*?)["&]', feed_html)
  1582. ids = orderedSet(m.group(1) for m in m_ids)
  1583. feed_entries.extend(
  1584. self.url_result(video_id, 'Youtube', video_id=video_id)
  1585. for video_id in ids)
  1586. if info['paging'] is None:
  1587. break
  1588. paging = info['paging']
  1589. return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE)
  1590. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  1591. IE_DESC = u'YouTube.com subscriptions feed, "ytsubs" keyword(requires authentication)'
  1592. _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  1593. _FEED_NAME = 'subscriptions'
  1594. _PLAYLIST_TITLE = u'Youtube Subscriptions'
  1595. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  1596. IE_DESC = u'YouTube.com recommended videos, "ytrec" keyword (requires authentication)'
  1597. _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  1598. _FEED_NAME = 'recommended'
  1599. _PLAYLIST_TITLE = u'Youtube Recommended videos'
  1600. class YoutubeWatchLaterIE(YoutubeFeedsInfoExtractor):
  1601. IE_DESC = u'Youtube watch later list, "ytwatchlater" keyword (requires authentication)'
  1602. _VALID_URL = r'https?://www\.youtube\.com/feed/watch_later|:ytwatchlater'
  1603. _FEED_NAME = 'watch_later'
  1604. _PLAYLIST_TITLE = u'Youtube Watch Later'
  1605. _PERSONAL_FEED = True
  1606. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  1607. IE_DESC = u'Youtube watch history, "ythistory" keyword (requires authentication)'
  1608. _VALID_URL = u'https?://www\.youtube\.com/feed/history|:ythistory'
  1609. _FEED_NAME = 'history'
  1610. _PERSONAL_FEED = True
  1611. _PLAYLIST_TITLE = u'Youtube Watch History'
  1612. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  1613. IE_NAME = u'youtube:favorites'
  1614. IE_DESC = u'YouTube.com favourite videos, "ytfav" keyword (requires authentication)'
  1615. _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  1616. _LOGIN_REQUIRED = True
  1617. def _real_extract(self, url):
  1618. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  1619. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, u'favourites playlist id')
  1620. return self.url_result(playlist_id, 'YoutubePlaylist')
  1621. class YoutubeTruncatedURLIE(InfoExtractor):
  1622. IE_NAME = 'youtube:truncated_url'
  1623. IE_DESC = False # Do not list
  1624. _VALID_URL = r'''(?x)
  1625. (?:https?://)?[^/]+/watch\?feature=[a-z_]+$|
  1626. (?:https?://)?(?:www\.)?youtube\.com/attribution_link\?a=[^&]+$
  1627. '''
  1628. def _real_extract(self, url):
  1629. raise ExtractorError(
  1630. u'Did you forget to quote the URL? Remember that & is a meta '
  1631. u'character in most shells, so you want to put the URL in quotes, '
  1632. u'like youtube-dl '
  1633. u'"http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
  1634. u' or simply youtube-dl BaW_jenozKc .',
  1635. expected=True)