youtube.py 79 KB

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