youtube.py 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813
  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 == 93: # findpropstrict
  736. index = u30(coder)
  737. mname = multinames[index]
  738. res = extract_function(mname)
  739. stack.append(res)
  740. elif opcode == 97: # setproperty
  741. index = u30(coder)
  742. value = stack.pop()
  743. idx = stack.pop()
  744. obj = stack.pop()
  745. assert isinstance(obj, list)
  746. assert isinstance(idx, int)
  747. obj[idx] = value
  748. elif opcode == 98: # getlocal
  749. index = u30(coder)
  750. stack.append(registers[index])
  751. elif opcode == 99: # setlocal
  752. index = u30(coder)
  753. value = stack.pop()
  754. registers[index] = value
  755. elif opcode == 102: # getproperty
  756. index = u30(coder)
  757. pname = multinames[index]
  758. if pname == u'length':
  759. obj = stack.pop()
  760. assert isinstance(obj, list)
  761. stack.append(len(obj))
  762. else: # Assume attribute access
  763. idx = stack.pop()
  764. assert isinstance(idx, int)
  765. obj = stack.pop()
  766. assert isinstance(obj, list)
  767. stack.append(obj[idx])
  768. elif opcode == 128: # coerce
  769. u30(coder)
  770. elif opcode == 133: # coerce_s
  771. assert isinstance(stack[-1], (type(None), compat_str))
  772. elif opcode == 164: # modulo
  773. value2 = stack.pop()
  774. value1 = stack.pop()
  775. res = value1 % value2
  776. stack.append(res)
  777. elif opcode == 208: # getlocal_0
  778. stack.append(registers[0])
  779. elif opcode == 209: # getlocal_1
  780. stack.append(registers[1])
  781. elif opcode == 210: # getlocal_2
  782. stack.append(registers[2])
  783. elif opcode == 211: # getlocal_3
  784. stack.append(registers[3])
  785. elif opcode == 214: # setlocal_2
  786. registers[2] = stack.pop()
  787. elif opcode == 215: # setlocal_3
  788. registers[3] = stack.pop()
  789. else:
  790. raise NotImplementedError(
  791. u'Unsupported opcode %d' % opcode)
  792. method_pyfunctions[func_name] = resfunc
  793. return resfunc
  794. initial_function = extract_function(u'decipher')
  795. return lambda s: initial_function([s])
  796. def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
  797. """Turn the encrypted s field into a working signature"""
  798. if player_url is None:
  799. raise ExtractorError(u'Cannot decrypt signature without player_url')
  800. if player_url.startswith(u'//'):
  801. player_url = u'https:' + player_url
  802. try:
  803. player_id = (player_url, len(s))
  804. if player_id not in self._player_cache:
  805. func = self._extract_signature_function(
  806. video_id, player_url, len(s)
  807. )
  808. self._player_cache[player_id] = func
  809. func = self._player_cache[player_id]
  810. if self._downloader.params.get('youtube_print_sig_code'):
  811. self._print_sig_code(func, len(s))
  812. return func(s)
  813. except Exception as e:
  814. tb = traceback.format_exc()
  815. raise ExtractorError(
  816. u'Automatic signature extraction failed: ' + tb, cause=e)
  817. def _get_available_subtitles(self, video_id, webpage):
  818. try:
  819. sub_list = self._download_webpage(
  820. 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  821. video_id, note=False)
  822. except ExtractorError as err:
  823. self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err))
  824. return {}
  825. lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
  826. sub_lang_list = {}
  827. for l in lang_list:
  828. lang = l[1]
  829. params = compat_urllib_parse.urlencode({
  830. 'lang': lang,
  831. 'v': video_id,
  832. 'fmt': self._downloader.params.get('subtitlesformat', 'srt'),
  833. 'name': unescapeHTML(l[0]).encode('utf-8'),
  834. })
  835. url = u'https://www.youtube.com/api/timedtext?' + params
  836. sub_lang_list[lang] = url
  837. if not sub_lang_list:
  838. self._downloader.report_warning(u'video doesn\'t have subtitles')
  839. return {}
  840. return sub_lang_list
  841. def _get_available_automatic_caption(self, video_id, webpage):
  842. """We need the webpage for getting the captions url, pass it as an
  843. argument to speed up the process."""
  844. sub_format = self._downloader.params.get('subtitlesformat', 'srt')
  845. self.to_screen(u'%s: Looking for automatic captions' % video_id)
  846. mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
  847. err_msg = u'Couldn\'t find automatic captions for %s' % video_id
  848. if mobj is None:
  849. self._downloader.report_warning(err_msg)
  850. return {}
  851. player_config = json.loads(mobj.group(1))
  852. try:
  853. args = player_config[u'args']
  854. caption_url = args[u'ttsurl']
  855. timestamp = args[u'timestamp']
  856. # We get the available subtitles
  857. list_params = compat_urllib_parse.urlencode({
  858. 'type': 'list',
  859. 'tlangs': 1,
  860. 'asrs': 1,
  861. })
  862. list_url = caption_url + '&' + list_params
  863. caption_list = self._download_xml(list_url, video_id)
  864. original_lang_node = caption_list.find('track')
  865. if original_lang_node is None or original_lang_node.attrib.get('kind') != 'asr' :
  866. self._downloader.report_warning(u'Video doesn\'t have automatic captions')
  867. return {}
  868. original_lang = original_lang_node.attrib['lang_code']
  869. sub_lang_list = {}
  870. for lang_node in caption_list.findall('target'):
  871. sub_lang = lang_node.attrib['lang_code']
  872. params = compat_urllib_parse.urlencode({
  873. 'lang': original_lang,
  874. 'tlang': sub_lang,
  875. 'fmt': sub_format,
  876. 'ts': timestamp,
  877. 'kind': 'asr',
  878. })
  879. sub_lang_list[sub_lang] = caption_url + '&' + params
  880. return sub_lang_list
  881. # An extractor error can be raise by the download process if there are
  882. # no automatic captions but there are subtitles
  883. except (KeyError, ExtractorError):
  884. self._downloader.report_warning(err_msg)
  885. return {}
  886. @classmethod
  887. def extract_id(cls, url):
  888. mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
  889. if mobj is None:
  890. raise ExtractorError(u'Invalid URL: %s' % url)
  891. video_id = mobj.group(2)
  892. return video_id
  893. def _extract_from_m3u8(self, manifest_url, video_id):
  894. url_map = {}
  895. def _get_urls(_manifest):
  896. lines = _manifest.split('\n')
  897. urls = filter(lambda l: l and not l.startswith('#'),
  898. lines)
  899. return urls
  900. manifest = self._download_webpage(manifest_url, video_id, u'Downloading formats manifest')
  901. formats_urls = _get_urls(manifest)
  902. for format_url in formats_urls:
  903. itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
  904. url_map[itag] = format_url
  905. return url_map
  906. def _extract_annotations(self, video_id):
  907. url = 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id
  908. return self._download_webpage(url, video_id, note=u'Searching for annotations.', errnote=u'Unable to download video annotations.')
  909. def _real_extract(self, url):
  910. proto = (
  911. u'http' if self._downloader.params.get('prefer_insecure', False)
  912. else u'https')
  913. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  914. mobj = re.search(self._NEXT_URL_RE, url)
  915. if mobj:
  916. url = proto + '://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  917. video_id = self.extract_id(url)
  918. # Get video webpage
  919. url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
  920. video_webpage = self._download_webpage(url, video_id)
  921. # Attempt to extract SWF player URL
  922. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  923. if mobj is not None:
  924. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  925. else:
  926. player_url = None
  927. # Get video info
  928. self.report_video_info_webpage_download(video_id)
  929. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  930. self.report_age_confirmation()
  931. age_gate = True
  932. # We simulate the access to the video from www.youtube.com/v/{video_id}
  933. # this can be viewed without login into Youtube
  934. data = compat_urllib_parse.urlencode({'video_id': video_id,
  935. 'el': 'player_embedded',
  936. 'gl': 'US',
  937. 'hl': 'en',
  938. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  939. 'asv': 3,
  940. 'sts':'1588',
  941. })
  942. video_info_url = proto + '://www.youtube.com/get_video_info?' + data
  943. video_info_webpage = self._download_webpage(video_info_url, video_id,
  944. note=False,
  945. errnote='unable to download video info webpage')
  946. video_info = compat_parse_qs(video_info_webpage)
  947. else:
  948. age_gate = False
  949. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  950. video_info_url = (proto + '://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  951. % (video_id, el_type))
  952. video_info_webpage = self._download_webpage(video_info_url, video_id,
  953. note=False,
  954. errnote='unable to download video info webpage')
  955. video_info = compat_parse_qs(video_info_webpage)
  956. if 'token' in video_info:
  957. break
  958. if 'token' not in video_info:
  959. if 'reason' in video_info:
  960. raise ExtractorError(
  961. u'YouTube said: %s' % video_info['reason'][0],
  962. expected=True, video_id=video_id)
  963. else:
  964. raise ExtractorError(
  965. u'"token" parameter not in video info for unknown reason',
  966. video_id=video_id)
  967. if 'view_count' in video_info:
  968. view_count = int(video_info['view_count'][0])
  969. else:
  970. view_count = None
  971. # Check for "rental" videos
  972. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  973. raise ExtractorError(u'"rental" videos not supported')
  974. # Start extracting information
  975. self.report_information_extraction(video_id)
  976. # uploader
  977. if 'author' not in video_info:
  978. raise ExtractorError(u'Unable to extract uploader name')
  979. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  980. # uploader_id
  981. video_uploader_id = None
  982. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  983. if mobj is not None:
  984. video_uploader_id = mobj.group(1)
  985. else:
  986. self._downloader.report_warning(u'unable to extract uploader nickname')
  987. # title
  988. if 'title' in video_info:
  989. video_title = video_info['title'][0]
  990. else:
  991. self._downloader.report_warning(u'Unable to extract video title')
  992. video_title = u'_'
  993. # thumbnail image
  994. # We try first to get a high quality image:
  995. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  996. video_webpage, re.DOTALL)
  997. if m_thumb is not None:
  998. video_thumbnail = m_thumb.group(1)
  999. elif 'thumbnail_url' not in video_info:
  1000. self._downloader.report_warning(u'unable to extract video thumbnail')
  1001. video_thumbnail = None
  1002. else: # don't panic if we can't find it
  1003. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  1004. # upload date
  1005. upload_date = None
  1006. mobj = re.search(r'(?s)id="eow-date.*?>(.*?)</span>', video_webpage)
  1007. if mobj is None:
  1008. mobj = re.search(
  1009. r'(?s)id="watch-uploader-info".*?>.*?(?:Published|Uploaded|Streamed live) on (.*?)</strong>',
  1010. video_webpage)
  1011. if mobj is not None:
  1012. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  1013. upload_date = unified_strdate(upload_date)
  1014. m_cat_container = get_element_by_id("eow-category", video_webpage)
  1015. if m_cat_container:
  1016. category = self._html_search_regex(
  1017. r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
  1018. default=None)
  1019. video_categories = None if category is None else [category]
  1020. else:
  1021. video_categories = None
  1022. # description
  1023. video_description = get_element_by_id("eow-description", video_webpage)
  1024. if video_description:
  1025. video_description = re.sub(r'''(?x)
  1026. <a\s+
  1027. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  1028. title="([^"]+)"\s+
  1029. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  1030. class="yt-uix-redirect-link"\s*>
  1031. [^<]+
  1032. </a>
  1033. ''', r'\1', video_description)
  1034. video_description = clean_html(video_description)
  1035. else:
  1036. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  1037. if fd_mobj:
  1038. video_description = unescapeHTML(fd_mobj.group(1))
  1039. else:
  1040. video_description = u''
  1041. def _extract_count(klass):
  1042. count = self._search_regex(
  1043. r'class="%s">([\d,]+)</span>' % re.escape(klass),
  1044. video_webpage, klass, default=None)
  1045. if count is not None:
  1046. return int(count.replace(',', ''))
  1047. return None
  1048. like_count = _extract_count(u'likes-count')
  1049. dislike_count = _extract_count(u'dislikes-count')
  1050. # subtitles
  1051. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  1052. if self._downloader.params.get('listsubtitles', False):
  1053. self._list_available_subtitles(video_id, video_webpage)
  1054. return
  1055. if 'length_seconds' not in video_info:
  1056. self._downloader.report_warning(u'unable to extract video duration')
  1057. video_duration = None
  1058. else:
  1059. video_duration = int(compat_urllib_parse.unquote_plus(video_info['length_seconds'][0]))
  1060. # annotations
  1061. video_annotations = None
  1062. if self._downloader.params.get('writeannotations', False):
  1063. video_annotations = self._extract_annotations(video_id)
  1064. # Decide which formats to download
  1065. try:
  1066. mobj = re.search(r';ytplayer\.config\s*=\s*({.*?});', video_webpage)
  1067. if not mobj:
  1068. raise ValueError('Could not find vevo ID')
  1069. json_code = uppercase_escape(mobj.group(1))
  1070. ytplayer_config = json.loads(json_code)
  1071. args = ytplayer_config['args']
  1072. # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
  1073. # this signatures are encrypted
  1074. if 'url_encoded_fmt_stream_map' not in args:
  1075. raise ValueError(u'No stream_map present') # caught below
  1076. re_signature = re.compile(r'[&,]s=')
  1077. m_s = re_signature.search(args['url_encoded_fmt_stream_map'])
  1078. if m_s is not None:
  1079. self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
  1080. video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
  1081. m_s = re_signature.search(args.get('adaptive_fmts', u''))
  1082. if m_s is not None:
  1083. if 'adaptive_fmts' in video_info:
  1084. video_info['adaptive_fmts'][0] += ',' + args['adaptive_fmts']
  1085. else:
  1086. video_info['adaptive_fmts'] = [args['adaptive_fmts']]
  1087. except ValueError:
  1088. pass
  1089. def _map_to_format_list(urlmap):
  1090. formats = []
  1091. for itag, video_real_url in urlmap.items():
  1092. dct = {
  1093. 'format_id': itag,
  1094. 'url': video_real_url,
  1095. 'player_url': player_url,
  1096. }
  1097. if itag in self._formats:
  1098. dct.update(self._formats[itag])
  1099. formats.append(dct)
  1100. return formats
  1101. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  1102. self.report_rtmp_download()
  1103. formats = [{
  1104. 'format_id': '_rtmp',
  1105. 'protocol': 'rtmp',
  1106. 'url': video_info['conn'][0],
  1107. 'player_url': player_url,
  1108. }]
  1109. elif len(video_info.get('url_encoded_fmt_stream_map', [])) >= 1 or len(video_info.get('adaptive_fmts', [])) >= 1:
  1110. encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts',[''])[0]
  1111. if 'rtmpe%3Dyes' in encoded_url_map:
  1112. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
  1113. url_map = {}
  1114. for url_data_str in encoded_url_map.split(','):
  1115. url_data = compat_parse_qs(url_data_str)
  1116. if 'itag' in url_data and 'url' in url_data:
  1117. url = url_data['url'][0]
  1118. if 'sig' in url_data:
  1119. url += '&signature=' + url_data['sig'][0]
  1120. elif 's' in url_data:
  1121. encrypted_sig = url_data['s'][0]
  1122. if not age_gate:
  1123. jsplayer_url_json = self._search_regex(
  1124. r'"assets":.+?"js":\s*("[^"]+")',
  1125. video_webpage, u'JS player URL')
  1126. player_url = json.loads(jsplayer_url_json)
  1127. if player_url is None:
  1128. player_url_json = self._search_regex(
  1129. r'ytplayer\.config.*?"url"\s*:\s*("[^"]+")',
  1130. video_webpage, u'age gate player URL')
  1131. player_url = json.loads(player_url_json)
  1132. if self._downloader.params.get('verbose'):
  1133. if player_url is None:
  1134. player_version = 'unknown'
  1135. player_desc = 'unknown'
  1136. else:
  1137. if player_url.endswith('swf'):
  1138. player_version = self._search_regex(
  1139. r'-(.+)\.swf$', player_url,
  1140. u'flash player', fatal=False)
  1141. player_desc = 'flash player %s' % player_version
  1142. else:
  1143. player_version = self._search_regex(
  1144. r'html5player-(.+?)\.js', video_webpage,
  1145. 'html5 player', fatal=False)
  1146. player_desc = u'html5 player %s' % player_version
  1147. parts_sizes = u'.'.join(compat_str(len(part)) for part in encrypted_sig.split('.'))
  1148. self.to_screen(u'encrypted signature length %d (%s), itag %s, %s' %
  1149. (len(encrypted_sig), parts_sizes, url_data['itag'][0], player_desc))
  1150. signature = self._decrypt_signature(
  1151. encrypted_sig, video_id, player_url, age_gate)
  1152. url += '&signature=' + signature
  1153. if 'ratebypass' not in url:
  1154. url += '&ratebypass=yes'
  1155. url_map[url_data['itag'][0]] = url
  1156. formats = _map_to_format_list(url_map)
  1157. elif video_info.get('hlsvp'):
  1158. manifest_url = video_info['hlsvp'][0]
  1159. url_map = self._extract_from_m3u8(manifest_url, video_id)
  1160. formats = _map_to_format_list(url_map)
  1161. else:
  1162. raise ExtractorError(u'no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
  1163. # Look for the DASH manifest
  1164. if (self._downloader.params.get('youtube_include_dash_manifest', False)):
  1165. try:
  1166. # The DASH manifest used needs to be the one from the original video_webpage.
  1167. # The one found in get_video_info seems to be using different signatures.
  1168. # However, in the case of an age restriction there won't be any embedded dashmpd in the video_webpage.
  1169. # Luckily, it seems, this case uses some kind of default signature (len == 86), so the
  1170. # combination of get_video_info and the _static_decrypt_signature() decryption fallback will work here.
  1171. if age_gate:
  1172. dash_manifest_url = video_info.get('dashmpd')[0]
  1173. else:
  1174. dash_manifest_url = ytplayer_config['args']['dashmpd']
  1175. def decrypt_sig(mobj):
  1176. s = mobj.group(1)
  1177. dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
  1178. return '/signature/%s' % dec_s
  1179. dash_manifest_url = re.sub(r'/s/([\w\.]+)', decrypt_sig, dash_manifest_url)
  1180. dash_doc = self._download_xml(
  1181. dash_manifest_url, video_id,
  1182. note=u'Downloading DASH manifest',
  1183. errnote=u'Could not download DASH manifest')
  1184. for r in dash_doc.findall(u'.//{urn:mpeg:DASH:schema:MPD:2011}Representation'):
  1185. url_el = r.find('{urn:mpeg:DASH:schema:MPD:2011}BaseURL')
  1186. if url_el is None:
  1187. continue
  1188. format_id = r.attrib['id']
  1189. video_url = url_el.text
  1190. filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength'))
  1191. f = {
  1192. 'format_id': format_id,
  1193. 'url': video_url,
  1194. 'width': int_or_none(r.attrib.get('width')),
  1195. 'tbr': int_or_none(r.attrib.get('bandwidth'), 1000),
  1196. 'asr': int_or_none(r.attrib.get('audioSamplingRate')),
  1197. 'filesize': filesize,
  1198. }
  1199. try:
  1200. existing_format = next(
  1201. fo for fo in formats
  1202. if fo['format_id'] == format_id)
  1203. except StopIteration:
  1204. f.update(self._formats.get(format_id, {}))
  1205. formats.append(f)
  1206. else:
  1207. existing_format.update(f)
  1208. except (ExtractorError, KeyError) as e:
  1209. self.report_warning(u'Skipping DASH manifest: %s' % e, video_id)
  1210. self._sort_formats(formats)
  1211. return {
  1212. 'id': video_id,
  1213. 'uploader': video_uploader,
  1214. 'uploader_id': video_uploader_id,
  1215. 'upload_date': upload_date,
  1216. 'title': video_title,
  1217. 'thumbnail': video_thumbnail,
  1218. 'description': video_description,
  1219. 'categories': video_categories,
  1220. 'subtitles': video_subtitles,
  1221. 'duration': video_duration,
  1222. 'age_limit': 18 if age_gate else 0,
  1223. 'annotations': video_annotations,
  1224. 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
  1225. 'view_count': view_count,
  1226. 'like_count': like_count,
  1227. 'dislike_count': dislike_count,
  1228. 'formats': formats,
  1229. }
  1230. class YoutubePlaylistIE(YoutubeBaseInfoExtractor):
  1231. IE_DESC = u'YouTube.com playlists'
  1232. _VALID_URL = r"""(?x)(?:
  1233. (?:https?://)?
  1234. (?:\w+\.)?
  1235. youtube\.com/
  1236. (?:
  1237. (?:course|view_play_list|my_playlists|artist|playlist|watch)
  1238. \? (?:.*?&)*? (?:p|a|list)=
  1239. | p/
  1240. )
  1241. (
  1242. (?:PL|LL|EC|UU|FL|RD)?[0-9A-Za-z-_]{10,}
  1243. # Top tracks, they can also include dots
  1244. |(?:MC)[\w\.]*
  1245. )
  1246. .*
  1247. |
  1248. ((?:PL|LL|EC|UU|FL|RD)[0-9A-Za-z-_]{10,})
  1249. )"""
  1250. _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s'
  1251. _MORE_PAGES_INDICATOR = r'data-link-type="next"'
  1252. _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&amp;[^"]*?index=(?P<index>\d+)'
  1253. IE_NAME = u'youtube:playlist'
  1254. def _real_initialize(self):
  1255. self._login()
  1256. def _ids_to_results(self, ids):
  1257. return [self.url_result(vid_id, 'Youtube', video_id=vid_id)
  1258. for vid_id in ids]
  1259. def _extract_mix(self, playlist_id):
  1260. # The mixes are generated from a a single video
  1261. # the id of the playlist is just 'RD' + video_id
  1262. url = 'https://youtube.com/watch?v=%s&list=%s' % (playlist_id[-11:], playlist_id)
  1263. webpage = self._download_webpage(url, playlist_id, u'Downloading Youtube mix')
  1264. search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
  1265. title_span = (search_title('playlist-title') or
  1266. search_title('title long-title') or search_title('title'))
  1267. title = clean_html(title_span)
  1268. video_re = r'''(?x)data-video-username=".*?".*?
  1269. href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s''' % re.escape(playlist_id)
  1270. ids = orderedSet(re.findall(video_re, webpage, flags=re.DOTALL))
  1271. url_results = self._ids_to_results(ids)
  1272. return self.playlist_result(url_results, playlist_id, title)
  1273. def _real_extract(self, url):
  1274. # Extract playlist id
  1275. mobj = re.match(self._VALID_URL, url)
  1276. if mobj is None:
  1277. raise ExtractorError(u'Invalid URL: %s' % url)
  1278. playlist_id = mobj.group(1) or mobj.group(2)
  1279. # Check if it's a video-specific URL
  1280. query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  1281. if 'v' in query_dict:
  1282. video_id = query_dict['v'][0]
  1283. if self._downloader.params.get('noplaylist'):
  1284. self.to_screen(u'Downloading just video %s because of --no-playlist' % video_id)
  1285. return self.url_result(video_id, 'Youtube', video_id=video_id)
  1286. else:
  1287. self.to_screen(u'Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  1288. if playlist_id.startswith('RD'):
  1289. # Mixes require a custom extraction process
  1290. return self._extract_mix(playlist_id)
  1291. if playlist_id.startswith('TL'):
  1292. raise ExtractorError(u'For downloading YouTube.com top lists, use '
  1293. u'the "yttoplist" keyword, for example "youtube-dl \'yttoplist:music:Top Tracks\'"', expected=True)
  1294. url = self._TEMPLATE_URL % playlist_id
  1295. page = self._download_webpage(url, playlist_id)
  1296. more_widget_html = content_html = page
  1297. # Check if the playlist exists or is private
  1298. if re.search(r'<div class="yt-alert-message">[^<]*?(The|This) playlist (does not exist|is private)[^<]*?</div>', page) is not None:
  1299. raise ExtractorError(
  1300. u'The playlist doesn\'t exist or is private, use --username or '
  1301. '--netrc to access it.',
  1302. expected=True)
  1303. # Extract the video ids from the playlist pages
  1304. ids = []
  1305. for page_num in itertools.count(1):
  1306. matches = re.finditer(self._VIDEO_RE, content_html)
  1307. # We remove the duplicates and the link with index 0
  1308. # (it's not the first video of the playlist)
  1309. new_ids = orderedSet(m.group('id') for m in matches if m.group('index') != '0')
  1310. ids.extend(new_ids)
  1311. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  1312. if not mobj:
  1313. break
  1314. more = self._download_json(
  1315. 'https://youtube.com/%s' % mobj.group('more'), playlist_id,
  1316. 'Downloading page #%s' % page_num,
  1317. transform_source=uppercase_escape)
  1318. content_html = more['content_html']
  1319. more_widget_html = more['load_more_widget_html']
  1320. playlist_title = self._html_search_regex(
  1321. r'(?s)<h1 class="pl-header-title[^"]*">\s*(.*?)\s*</h1>',
  1322. page, u'title')
  1323. url_results = self._ids_to_results(ids)
  1324. return self.playlist_result(url_results, playlist_id, playlist_title)
  1325. class YoutubeTopListIE(YoutubePlaylistIE):
  1326. IE_NAME = u'youtube:toplist'
  1327. IE_DESC = (u'YouTube.com top lists, "yttoplist:{channel}:{list title}"'
  1328. u' (Example: "yttoplist:music:Top Tracks")')
  1329. _VALID_URL = r'yttoplist:(?P<chann>.*?):(?P<title>.*?)$'
  1330. def _real_extract(self, url):
  1331. mobj = re.match(self._VALID_URL, url)
  1332. channel = mobj.group('chann')
  1333. title = mobj.group('title')
  1334. query = compat_urllib_parse.urlencode({'title': title})
  1335. playlist_re = 'href="([^"]+?%s.*?)"' % re.escape(query)
  1336. channel_page = self._download_webpage('https://www.youtube.com/%s' % channel, title)
  1337. link = self._html_search_regex(playlist_re, channel_page, u'list')
  1338. url = compat_urlparse.urljoin('https://www.youtube.com/', link)
  1339. video_re = r'data-index="\d+".*?data-video-id="([0-9A-Za-z_-]{11})"'
  1340. ids = []
  1341. # sometimes the webpage doesn't contain the videos
  1342. # retry until we get them
  1343. for i in itertools.count(0):
  1344. msg = u'Downloading Youtube mix'
  1345. if i > 0:
  1346. msg += ', retry #%d' % i
  1347. webpage = self._download_webpage(url, title, msg)
  1348. ids = orderedSet(re.findall(video_re, webpage))
  1349. if ids:
  1350. break
  1351. url_results = self._ids_to_results(ids)
  1352. return self.playlist_result(url_results, playlist_title=title)
  1353. class YoutubeChannelIE(InfoExtractor):
  1354. IE_DESC = u'YouTube.com channels'
  1355. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
  1356. _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
  1357. _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'
  1358. IE_NAME = u'youtube:channel'
  1359. def extract_videos_from_page(self, page):
  1360. ids_in_page = []
  1361. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
  1362. if mobj.group(1) not in ids_in_page:
  1363. ids_in_page.append(mobj.group(1))
  1364. return ids_in_page
  1365. def _real_extract(self, url):
  1366. # Extract channel id
  1367. mobj = re.match(self._VALID_URL, url)
  1368. if mobj is None:
  1369. raise ExtractorError(u'Invalid URL: %s' % url)
  1370. # Download channel page
  1371. channel_id = mobj.group(1)
  1372. video_ids = []
  1373. url = 'https://www.youtube.com/channel/%s/videos' % channel_id
  1374. channel_page = self._download_webpage(url, channel_id)
  1375. autogenerated = re.search(r'''(?x)
  1376. class="[^"]*?(?:
  1377. channel-header-autogenerated-label|
  1378. yt-channel-title-autogenerated
  1379. )[^"]*"''', channel_page) is not None
  1380. if autogenerated:
  1381. # The videos are contained in a single page
  1382. # the ajax pages can't be used, they are empty
  1383. video_ids = self.extract_videos_from_page(channel_page)
  1384. else:
  1385. # Download all channel pages using the json-based channel_ajax query
  1386. for pagenum in itertools.count(1):
  1387. url = self._MORE_PAGES_URL % (pagenum, channel_id)
  1388. page = self._download_json(
  1389. url, channel_id, note=u'Downloading page #%s' % pagenum,
  1390. transform_source=uppercase_escape)
  1391. ids_in_page = self.extract_videos_from_page(page['content_html'])
  1392. video_ids.extend(ids_in_page)
  1393. if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
  1394. break
  1395. self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  1396. url_entries = [self.url_result(video_id, 'Youtube', video_id=video_id)
  1397. for video_id in video_ids]
  1398. return self.playlist_result(url_entries, channel_id)
  1399. class YoutubeUserIE(InfoExtractor):
  1400. IE_DESC = u'YouTube.com user videos (URL or "ytuser" keyword)'
  1401. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?(?!(?:attribution_link|watch|results)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)([A-Za-z0-9_-]+)'
  1402. _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/users/%s'
  1403. _GDATA_PAGE_SIZE = 50
  1404. _GDATA_URL = 'https://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d&alt=json'
  1405. IE_NAME = u'youtube:user'
  1406. @classmethod
  1407. def suitable(cls, url):
  1408. # Don't return True if the url can be extracted with other youtube
  1409. # extractor, the regex would is too permissive and it would match.
  1410. other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls)
  1411. if any(ie.suitable(url) for ie in other_ies): return False
  1412. else: return super(YoutubeUserIE, cls).suitable(url)
  1413. def _real_extract(self, url):
  1414. # Extract username
  1415. mobj = re.match(self._VALID_URL, url)
  1416. if mobj is None:
  1417. raise ExtractorError(u'Invalid URL: %s' % url)
  1418. username = mobj.group(1)
  1419. # Download video ids using YouTube Data API. Result size per
  1420. # query is limited (currently to 50 videos) so we need to query
  1421. # page by page until there are no video ids - it means we got
  1422. # all of them.
  1423. def download_page(pagenum):
  1424. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1425. gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
  1426. page = self._download_webpage(
  1427. gdata_url, username,
  1428. u'Downloading video ids from %d to %d' % (
  1429. start_index, start_index + self._GDATA_PAGE_SIZE))
  1430. try:
  1431. response = json.loads(page)
  1432. except ValueError as err:
  1433. raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
  1434. if 'entry' not in response['feed']:
  1435. return
  1436. # Extract video identifiers
  1437. entries = response['feed']['entry']
  1438. for entry in entries:
  1439. title = entry['title']['$t']
  1440. video_id = entry['id']['$t'].split('/')[-1]
  1441. yield {
  1442. '_type': 'url',
  1443. 'url': video_id,
  1444. 'ie_key': 'Youtube',
  1445. 'id': video_id,
  1446. 'title': title,
  1447. }
  1448. url_results = PagedList(download_page, self._GDATA_PAGE_SIZE)
  1449. return self.playlist_result(url_results, playlist_title=username)
  1450. class YoutubeSearchIE(SearchInfoExtractor):
  1451. IE_DESC = u'YouTube.com searches'
  1452. _API_URL = u'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1453. _MAX_RESULTS = 1000
  1454. IE_NAME = u'youtube:search'
  1455. _SEARCH_KEY = 'ytsearch'
  1456. def _get_n_results(self, query, n):
  1457. """Get a specified number of results for a query"""
  1458. video_ids = []
  1459. pagenum = 0
  1460. limit = n
  1461. PAGE_SIZE = 50
  1462. while (PAGE_SIZE * pagenum) < limit:
  1463. result_url = self._API_URL % (
  1464. compat_urllib_parse.quote_plus(query.encode('utf-8')),
  1465. (PAGE_SIZE * pagenum) + 1)
  1466. data_json = self._download_webpage(
  1467. result_url, video_id=u'query "%s"' % query,
  1468. note=u'Downloading page %s' % (pagenum + 1),
  1469. errnote=u'Unable to download API page')
  1470. data = json.loads(data_json)
  1471. api_response = data['data']
  1472. if 'items' not in api_response:
  1473. raise ExtractorError(
  1474. u'[youtube] No video results', expected=True)
  1475. new_ids = list(video['id'] for video in api_response['items'])
  1476. video_ids += new_ids
  1477. limit = min(n, api_response['totalItems'])
  1478. pagenum += 1
  1479. if len(video_ids) > n:
  1480. video_ids = video_ids[:n]
  1481. videos = [self.url_result(video_id, 'Youtube', video_id=video_id)
  1482. for video_id in video_ids]
  1483. return self.playlist_result(videos, query)
  1484. class YoutubeSearchDateIE(YoutubeSearchIE):
  1485. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  1486. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc&orderby=published'
  1487. _SEARCH_KEY = 'ytsearchdate'
  1488. IE_DESC = u'YouTube.com searches, newest videos first'
  1489. class YoutubeSearchURLIE(InfoExtractor):
  1490. IE_DESC = u'YouTube.com search URLs'
  1491. IE_NAME = u'youtube:search_url'
  1492. _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?search_query=(?P<query>[^&]+)(?:[&]|$)'
  1493. def _real_extract(self, url):
  1494. mobj = re.match(self._VALID_URL, url)
  1495. query = compat_urllib_parse.unquote_plus(mobj.group('query'))
  1496. webpage = self._download_webpage(url, query)
  1497. result_code = self._search_regex(
  1498. r'(?s)<ol class="item-section"(.*?)</ol>', webpage, u'result HTML')
  1499. part_codes = re.findall(
  1500. r'(?s)<h3 class="yt-lockup-title">(.*?)</h3>', result_code)
  1501. entries = []
  1502. for part_code in part_codes:
  1503. part_title = self._html_search_regex(
  1504. [r'(?s)title="([^"]+)"', r'>([^<]+)</a>'], part_code, 'item title', fatal=False)
  1505. part_url_snippet = self._html_search_regex(
  1506. r'(?s)href="([^"]+)"', part_code, 'item URL')
  1507. part_url = compat_urlparse.urljoin(
  1508. 'https://www.youtube.com/', part_url_snippet)
  1509. entries.append({
  1510. '_type': 'url',
  1511. 'url': part_url,
  1512. 'title': part_title,
  1513. })
  1514. return {
  1515. '_type': 'playlist',
  1516. 'entries': entries,
  1517. 'title': query,
  1518. }
  1519. class YoutubeShowIE(InfoExtractor):
  1520. IE_DESC = u'YouTube.com (multi-season) shows'
  1521. _VALID_URL = r'https?://www\.youtube\.com/show/(.*)'
  1522. IE_NAME = u'youtube:show'
  1523. def _real_extract(self, url):
  1524. mobj = re.match(self._VALID_URL, url)
  1525. show_name = mobj.group(1)
  1526. webpage = self._download_webpage(url, show_name, u'Downloading show webpage')
  1527. # There's one playlist for each season of the show
  1528. m_seasons = list(re.finditer(r'href="(/playlist\?list=.*?)"', webpage))
  1529. self.to_screen(u'%s: Found %s seasons' % (show_name, len(m_seasons)))
  1530. return [self.url_result('https://www.youtube.com' + season.group(1), 'YoutubePlaylist') for season in m_seasons]
  1531. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  1532. """
  1533. Base class for extractors that fetch info from
  1534. http://www.youtube.com/feed_ajax
  1535. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  1536. """
  1537. _LOGIN_REQUIRED = True
  1538. # use action_load_personal_feed instead of action_load_system_feed
  1539. _PERSONAL_FEED = False
  1540. @property
  1541. def _FEED_TEMPLATE(self):
  1542. action = 'action_load_system_feed'
  1543. if self._PERSONAL_FEED:
  1544. action = 'action_load_personal_feed'
  1545. return 'https://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action, self._FEED_NAME)
  1546. @property
  1547. def IE_NAME(self):
  1548. return u'youtube:%s' % self._FEED_NAME
  1549. def _real_initialize(self):
  1550. self._login()
  1551. def _real_extract(self, url):
  1552. feed_entries = []
  1553. paging = 0
  1554. for i in itertools.count(1):
  1555. info = self._download_json(self._FEED_TEMPLATE % paging,
  1556. u'%s feed' % self._FEED_NAME,
  1557. u'Downloading page %s' % i)
  1558. feed_html = info.get('feed_html') or info.get('content_html')
  1559. m_ids = re.finditer(r'"/watch\?v=(.*?)["&]', feed_html)
  1560. ids = orderedSet(m.group(1) for m in m_ids)
  1561. feed_entries.extend(
  1562. self.url_result(video_id, 'Youtube', video_id=video_id)
  1563. for video_id in ids)
  1564. mobj = re.search(
  1565. r'data-uix-load-more-href="/?[^"]+paging=(?P<paging>\d+)',
  1566. feed_html)
  1567. if mobj is None:
  1568. break
  1569. paging = mobj.group('paging')
  1570. return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE)
  1571. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  1572. IE_DESC = u'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
  1573. _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  1574. _FEED_NAME = 'subscriptions'
  1575. _PLAYLIST_TITLE = u'Youtube Subscriptions'
  1576. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  1577. IE_DESC = u'YouTube.com recommended videos, "ytrec" keyword (requires authentication)'
  1578. _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  1579. _FEED_NAME = 'recommended'
  1580. _PLAYLIST_TITLE = u'Youtube Recommended videos'
  1581. class YoutubeWatchLaterIE(YoutubeFeedsInfoExtractor):
  1582. IE_DESC = u'Youtube watch later list, "ytwatchlater" keyword (requires authentication)'
  1583. _VALID_URL = r'https?://www\.youtube\.com/feed/watch_later|:ytwatchlater'
  1584. _FEED_NAME = 'watch_later'
  1585. _PLAYLIST_TITLE = u'Youtube Watch Later'
  1586. _PERSONAL_FEED = True
  1587. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  1588. IE_DESC = u'Youtube watch history, "ythistory" keyword (requires authentication)'
  1589. _VALID_URL = u'https?://www\.youtube\.com/feed/history|:ythistory'
  1590. _FEED_NAME = 'history'
  1591. _PERSONAL_FEED = True
  1592. _PLAYLIST_TITLE = u'Youtube Watch History'
  1593. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  1594. IE_NAME = u'youtube:favorites'
  1595. IE_DESC = u'YouTube.com favourite videos, "ytfav" keyword (requires authentication)'
  1596. _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  1597. _LOGIN_REQUIRED = True
  1598. def _real_extract(self, url):
  1599. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  1600. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, u'favourites playlist id')
  1601. return self.url_result(playlist_id, 'YoutubePlaylist')
  1602. class YoutubeTruncatedURLIE(InfoExtractor):
  1603. IE_NAME = 'youtube:truncated_url'
  1604. IE_DESC = False # Do not list
  1605. _VALID_URL = r'''(?x)
  1606. (?:https?://)?[^/]+/watch\?(?:
  1607. feature=[a-z_]+|
  1608. annotation_id=annotation_[^&]+
  1609. )?$|
  1610. (?:https?://)?(?:www\.)?youtube\.com/attribution_link\?a=[^&]+$
  1611. '''
  1612. _TESTS = [{
  1613. 'url': 'http://www.youtube.com/watch?annotation_id=annotation_3951667041',
  1614. 'only_matching': True,
  1615. }, {
  1616. 'url': 'http://www.youtube.com/watch?',
  1617. 'only_matching': True,
  1618. }]
  1619. def _real_extract(self, url):
  1620. raise ExtractorError(
  1621. u'Did you forget to quote the URL? Remember that & is a meta '
  1622. u'character in most shells, so you want to put the URL in quotes, '
  1623. u'like youtube-dl '
  1624. u'"http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
  1625. u' or simply youtube-dl BaW_jenozKc .',
  1626. expected=True)