youtube.py 81 KB

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