generic.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. # encoding: utf-8
  2. from __future__ import unicode_literals
  3. import os
  4. import re
  5. from .common import InfoExtractor
  6. from .youtube import YoutubeIE
  7. from ..utils import (
  8. compat_urllib_error,
  9. compat_urllib_parse,
  10. compat_urllib_request,
  11. compat_urlparse,
  12. compat_xml_parse_error,
  13. ExtractorError,
  14. float_or_none,
  15. HEADRequest,
  16. orderedSet,
  17. parse_xml,
  18. smuggle_url,
  19. unescapeHTML,
  20. unified_strdate,
  21. unsmuggle_url,
  22. url_basename,
  23. )
  24. from .brightcove import BrightcoveIE
  25. from .ooyala import OoyalaIE
  26. from .rutv import RUTVIE
  27. from .smotri import SmotriIE
  28. class GenericIE(InfoExtractor):
  29. IE_DESC = 'Generic downloader that works on some sites'
  30. _VALID_URL = r'.*'
  31. IE_NAME = 'generic'
  32. _TESTS = [
  33. {
  34. 'url': 'http://www.hodiho.fr/2013/02/regis-plante-sa-jeep.html',
  35. 'md5': '85b90ccc9d73b4acd9138d3af4c27f89',
  36. 'info_dict': {
  37. 'id': '13601338388002',
  38. 'ext': 'mp4',
  39. 'uploader': 'www.hodiho.fr',
  40. 'title': 'R\u00e9gis plante sa Jeep',
  41. }
  42. },
  43. # bandcamp page with custom domain
  44. {
  45. 'add_ie': ['Bandcamp'],
  46. 'url': 'http://bronyrock.com/track/the-pony-mash',
  47. 'info_dict': {
  48. 'id': '3235767654',
  49. 'ext': 'mp3',
  50. 'title': 'The Pony Mash',
  51. 'uploader': 'M_Pallante',
  52. },
  53. 'skip': 'There is a limit of 200 free downloads / month for the test song',
  54. },
  55. # embedded brightcove video
  56. # it also tests brightcove videos that need to set the 'Referer' in the
  57. # http requests
  58. {
  59. 'add_ie': ['Brightcove'],
  60. 'url': 'http://www.bfmtv.com/video/bfmbusiness/cours-bourse/cours-bourse-l-analyse-technique-154522/',
  61. 'info_dict': {
  62. 'id': '2765128793001',
  63. 'ext': 'mp4',
  64. 'title': 'Le cours de bourse : l’analyse technique',
  65. 'description': 'md5:7e9ad046e968cb2d1114004aba466fd9',
  66. 'uploader': 'BFM BUSINESS',
  67. },
  68. 'params': {
  69. 'skip_download': True,
  70. },
  71. },
  72. {
  73. # https://github.com/rg3/youtube-dl/issues/2253
  74. 'url': 'http://bcove.me/i6nfkrc3',
  75. 'md5': '0ba9446db037002366bab3b3eb30c88c',
  76. 'info_dict': {
  77. 'id': '3101154703001',
  78. 'ext': 'mp4',
  79. 'title': 'Still no power',
  80. 'uploader': 'thestar.com',
  81. 'description': 'Mississauga resident David Farmer is still out of power as a result of the ice storm a month ago. To keep the house warm, Farmer cuts wood from his property for a wood burning stove downstairs.',
  82. },
  83. 'add_ie': ['Brightcove'],
  84. },
  85. {
  86. 'url': 'http://www.championat.com/video/football/v/87/87499.html',
  87. 'md5': 'fb973ecf6e4a78a67453647444222983',
  88. 'info_dict': {
  89. 'id': '3414141473001',
  90. 'ext': 'mp4',
  91. 'title': 'Видео. Удаление Дзагоева (ЦСКА)',
  92. 'description': 'Онлайн-трансляция матча ЦСКА - "Волга"',
  93. 'uploader': 'Championat',
  94. },
  95. },
  96. # Direct link to a video
  97. {
  98. 'url': 'http://media.w3.org/2010/05/sintel/trailer.mp4',
  99. 'md5': '67d406c2bcb6af27fa886f31aa934bbe',
  100. 'info_dict': {
  101. 'id': 'trailer',
  102. 'ext': 'mp4',
  103. 'title': 'trailer',
  104. 'upload_date': '20100513',
  105. }
  106. },
  107. # ooyala video
  108. {
  109. 'url': 'http://www.rollingstone.com/music/videos/norwegian-dj-cashmere-cat-goes-spartan-on-with-me-premiere-20131219',
  110. 'md5': '5644c6ca5d5782c1d0d350dad9bd840c',
  111. 'info_dict': {
  112. 'id': 'BwY2RxaTrTkslxOfcan0UCf0YqyvWysJ',
  113. 'ext': 'mp4',
  114. 'title': '2cc213299525360.mov', # that's what we get
  115. },
  116. },
  117. # google redirect
  118. {
  119. 'url': 'http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&ved=0CCUQtwIwAA&url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DcmQHVoWB5FY&ei=F-sNU-LLCaXk4QT52ICQBQ&usg=AFQjCNEw4hL29zgOohLXvpJ-Bdh2bils1Q&bvm=bv.61965928,d.bGE',
  120. 'info_dict': {
  121. 'id': 'cmQHVoWB5FY',
  122. 'ext': 'mp4',
  123. 'upload_date': '20130224',
  124. 'uploader_id': 'TheVerge',
  125. 'description': 'Chris Ziegler takes a look at the Alcatel OneTouch Fire and the ZTE Open; two of the first Firefox OS handsets to be officially announced.',
  126. 'uploader': 'The Verge',
  127. 'title': 'First Firefox OS phones side-by-side',
  128. },
  129. 'params': {
  130. 'skip_download': False,
  131. }
  132. },
  133. # embed.ly video
  134. {
  135. 'url': 'http://www.tested.com/science/weird/460206-tested-grinding-coffee-2000-frames-second/',
  136. 'info_dict': {
  137. 'id': '9ODmcdjQcHQ',
  138. 'ext': 'mp4',
  139. 'title': 'Tested: Grinding Coffee at 2000 Frames Per Second',
  140. 'upload_date': '20140225',
  141. 'description': 'md5:06a40fbf30b220468f1e0957c0f558ff',
  142. 'uploader': 'Tested',
  143. 'uploader_id': 'testedcom',
  144. },
  145. # No need to test YoutubeIE here
  146. 'params': {
  147. 'skip_download': True,
  148. },
  149. },
  150. # funnyordie embed
  151. {
  152. 'url': 'http://www.theguardian.com/world/2014/mar/11/obama-zach-galifianakis-between-two-ferns',
  153. 'md5': '7cf780be104d40fea7bae52eed4a470e',
  154. 'info_dict': {
  155. 'id': '18e820ec3f',
  156. 'ext': 'mp4',
  157. 'title': 'Between Two Ferns with Zach Galifianakis: President Barack Obama',
  158. 'description': 'Episode 18: President Barack Obama sits down with Zach Galifianakis for his most memorable interview yet.',
  159. },
  160. },
  161. # RUTV embed
  162. {
  163. 'url': 'http://www.rg.ru/2014/03/15/reg-dfo/anklav-anons.html',
  164. 'info_dict': {
  165. 'id': '776940',
  166. 'ext': 'mp4',
  167. 'title': 'Охотское море стало целиком российским',
  168. 'description': 'md5:5ed62483b14663e2a95ebbe115eb8f43',
  169. },
  170. 'params': {
  171. # m3u8 download
  172. 'skip_download': True,
  173. },
  174. },
  175. # Embedded TED video
  176. {
  177. 'url': 'http://en.support.wordpress.com/videos/ted-talks/',
  178. 'md5': 'deeeabcc1085eb2ba205474e7235a3d5',
  179. 'info_dict': {
  180. 'id': '981',
  181. 'ext': 'mp4',
  182. 'title': 'My web playroom',
  183. 'uploader': 'Ze Frank',
  184. 'description': 'md5:ddb2a40ecd6b6a147e400e535874947b',
  185. }
  186. },
  187. # Embeded Ustream video
  188. {
  189. 'url': 'http://www.american.edu/spa/pti/nsa-privacy-janus-2014.cfm',
  190. 'md5': '27b99cdb639c9b12a79bca876a073417',
  191. 'info_dict': {
  192. 'id': '45734260',
  193. 'ext': 'flv',
  194. 'uploader': 'AU SPA: The NSA and Privacy',
  195. 'title': 'NSA and Privacy Forum Debate featuring General Hayden and Barton Gellman'
  196. }
  197. },
  198. # nowvideo embed hidden behind percent encoding
  199. {
  200. 'url': 'http://www.waoanime.tv/the-super-dimension-fortress-macross-episode-1/',
  201. 'md5': '2baf4ddd70f697d94b1c18cf796d5107',
  202. 'info_dict': {
  203. 'id': '06e53103ca9aa',
  204. 'ext': 'flv',
  205. 'title': 'Macross Episode 001 Watch Macross Episode 001 onl',
  206. 'description': 'No description',
  207. },
  208. },
  209. # arte embed
  210. {
  211. 'url': 'http://www.tv-replay.fr/redirection/20-03-14/x-enius-arte-10753389.html',
  212. 'md5': '7653032cbb25bf6c80d80f217055fa43',
  213. 'info_dict': {
  214. 'id': '048195-004_PLUS7-F',
  215. 'ext': 'flv',
  216. 'title': 'X:enius',
  217. 'description': 'md5:d5fdf32ef6613cdbfd516ae658abf168',
  218. 'upload_date': '20140320',
  219. },
  220. 'params': {
  221. 'skip_download': 'Requires rtmpdump'
  222. }
  223. },
  224. # smotri embed
  225. {
  226. 'url': 'http://rbctv.rbc.ru/archive/news/562949990879132.shtml',
  227. 'md5': 'ec40048448e9284c9a1de77bb188108b',
  228. 'info_dict': {
  229. 'id': 'v27008541fad',
  230. 'ext': 'mp4',
  231. 'title': 'Крым и Севастополь вошли в состав России',
  232. 'description': 'md5:fae01b61f68984c7bd2fa741e11c3175',
  233. 'duration': 900,
  234. 'upload_date': '20140318',
  235. 'uploader': 'rbctv_2012_4',
  236. 'uploader_id': 'rbctv_2012_4',
  237. },
  238. },
  239. # Condé Nast embed
  240. {
  241. 'url': 'http://www.wired.com/2014/04/honda-asimo/',
  242. 'md5': 'ba0dfe966fa007657bd1443ee672db0f',
  243. 'info_dict': {
  244. 'id': '53501be369702d3275860000',
  245. 'ext': 'mp4',
  246. 'title': 'Honda’s New Asimo Robot Is More Human Than Ever',
  247. }
  248. },
  249. # Dailymotion embed
  250. {
  251. 'url': 'http://www.spi0n.com/zap-spi0n-com-n216/',
  252. 'md5': '441aeeb82eb72c422c7f14ec533999cd',
  253. 'info_dict': {
  254. 'id': 'k2mm4bCdJ6CQ2i7c8o2',
  255. 'ext': 'mp4',
  256. 'title': 'Le Zap de Spi0n n°216 - Zapping du Web',
  257. 'uploader': 'Spi0n',
  258. },
  259. 'add_ie': ['Dailymotion'],
  260. },
  261. # YouTube embed
  262. {
  263. 'url': 'http://www.badzine.de/ansicht/datum/2014/06/09/so-funktioniert-die-neue-englische-badminton-liga.html',
  264. 'info_dict': {
  265. 'id': 'FXRb4ykk4S0',
  266. 'ext': 'mp4',
  267. 'title': 'The NBL Auction 2014',
  268. 'uploader': 'BADMINTON England',
  269. 'uploader_id': 'BADMINTONEvents',
  270. 'upload_date': '20140603',
  271. 'description': 'md5:9ef128a69f1e262a700ed83edb163a73',
  272. },
  273. 'add_ie': ['Youtube'],
  274. 'params': {
  275. 'skip_download': True,
  276. }
  277. },
  278. # MTVSercices embed
  279. {
  280. 'url': 'http://www.gametrailers.com/news-post/76093/north-america-europe-is-getting-that-mario-kart-8-mercedes-dlc-too',
  281. 'md5': '35727f82f58c76d996fc188f9755b0d5',
  282. 'info_dict': {
  283. 'id': '0306a69b-8adf-4fb5-aace-75f8e8cbfca9',
  284. 'ext': 'mp4',
  285. 'title': 'Review',
  286. 'description': 'Mario\'s life in the fast lane has never looked so good.',
  287. },
  288. },
  289. # YouTube embed via <data-embed-url="">
  290. {
  291. 'url': 'https://play.google.com/store/apps/details?id=com.gameloft.android.ANMP.GloftA8HM',
  292. 'info_dict': {
  293. 'id': 'jpSGZsgga_I',
  294. 'ext': 'mp4',
  295. 'title': 'Asphalt 8: Airborne - Launch Trailer',
  296. 'uploader': 'Gameloft',
  297. 'uploader_id': 'gameloft',
  298. 'upload_date': '20130821',
  299. 'description': 'md5:87bd95f13d8be3e7da87a5f2c443106a',
  300. },
  301. 'params': {
  302. 'skip_download': True,
  303. }
  304. },
  305. # Camtasia studio
  306. {
  307. 'url': 'http://www.ll.mit.edu/workshops/education/videocourses/antennas/lecture1/video/',
  308. 'playlist': [{
  309. 'md5': '0c5e352edabf715d762b0ad4e6d9ee67',
  310. 'info_dict': {
  311. 'id': 'Fenn-AA_PA_Radar_Course_Lecture_1c_Final',
  312. 'title': 'Fenn-AA_PA_Radar_Course_Lecture_1c_Final - video1',
  313. 'ext': 'flv',
  314. 'duration': 2235.90,
  315. }
  316. }, {
  317. 'md5': '10e4bb3aaca9fd630e273ff92d9f3c63',
  318. 'info_dict': {
  319. 'id': 'Fenn-AA_PA_Radar_Course_Lecture_1c_Final_PIP',
  320. 'title': 'Fenn-AA_PA_Radar_Course_Lecture_1c_Final - pip',
  321. 'ext': 'flv',
  322. 'duration': 2235.93,
  323. }
  324. }],
  325. 'info_dict': {
  326. 'title': 'Fenn-AA_PA_Radar_Course_Lecture_1c_Final',
  327. }
  328. },
  329. # Flowplayer
  330. {
  331. 'url': 'http://www.handjobhub.com/video/busty-blonde-siri-tit-fuck-while-wank-6313.html',
  332. 'md5': '9d65602bf31c6e20014319c7d07fba27',
  333. 'info_dict': {
  334. 'id': '5123ea6d5e5a7',
  335. 'ext': 'mp4',
  336. 'age_limit': 18,
  337. 'uploader': 'www.handjobhub.com',
  338. 'title': 'Busty Blonde Siri Tit Fuck While Wank at Handjob Hub',
  339. }
  340. }
  341. ]
  342. def report_download_webpage(self, video_id):
  343. """Report webpage download."""
  344. if not self._downloader.params.get('test', False):
  345. self._downloader.report_warning('Falling back on generic information extractor.')
  346. super(GenericIE, self).report_download_webpage(video_id)
  347. def report_following_redirect(self, new_url):
  348. """Report information extraction."""
  349. self._downloader.to_screen('[redirect] Following redirect to %s' % new_url)
  350. def _send_head(self, url):
  351. """Check if it is a redirect, like url shorteners, in case return the new url."""
  352. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  353. """
  354. Subclass the HTTPRedirectHandler to make it use our
  355. HEADRequest also on the redirected URL
  356. """
  357. def redirect_request(self, req, fp, code, msg, headers, newurl):
  358. if code in (301, 302, 303, 307):
  359. newurl = newurl.replace(' ', '%20')
  360. newheaders = dict((k,v) for k,v in req.headers.items()
  361. if k.lower() not in ("content-length", "content-type"))
  362. try:
  363. # This function was deprecated in python 3.3 and removed in 3.4
  364. origin_req_host = req.get_origin_req_host()
  365. except AttributeError:
  366. origin_req_host = req.origin_req_host
  367. return HEADRequest(newurl,
  368. headers=newheaders,
  369. origin_req_host=origin_req_host,
  370. unverifiable=True)
  371. else:
  372. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  373. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  374. """
  375. Fallback to GET if HEAD is not allowed (405 HTTP error)
  376. """
  377. def http_error_405(self, req, fp, code, msg, headers):
  378. fp.read()
  379. fp.close()
  380. newheaders = dict((k,v) for k,v in req.headers.items()
  381. if k.lower() not in ("content-length", "content-type"))
  382. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  383. headers=newheaders,
  384. origin_req_host=req.get_origin_req_host(),
  385. unverifiable=True))
  386. # Build our opener
  387. opener = compat_urllib_request.OpenerDirector()
  388. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  389. HTTPMethodFallback, HEADRedirectHandler,
  390. compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  391. opener.add_handler(handler())
  392. response = opener.open(HEADRequest(url))
  393. if response is None:
  394. raise ExtractorError('Invalid URL protocol')
  395. return response
  396. def _extract_rss(self, url, video_id, doc):
  397. playlist_title = doc.find('./channel/title').text
  398. playlist_desc_el = doc.find('./channel/description')
  399. playlist_desc = None if playlist_desc_el is None else playlist_desc_el.text
  400. entries = [{
  401. '_type': 'url',
  402. 'url': e.find('link').text,
  403. 'title': e.find('title').text,
  404. } for e in doc.findall('./channel/item')]
  405. return {
  406. '_type': 'playlist',
  407. 'id': url,
  408. 'title': playlist_title,
  409. 'description': playlist_desc,
  410. 'entries': entries,
  411. }
  412. def _extract_camtasia(self, url, video_id, webpage):
  413. """ Returns None if no camtasia video can be found. """
  414. camtasia_cfg = self._search_regex(
  415. r'fo\.addVariable\(\s*"csConfigFile",\s*"([^"]+)"\s*\);',
  416. webpage, 'camtasia configuration file', default=None)
  417. if camtasia_cfg is None:
  418. return None
  419. title = self._html_search_meta('DC.title', webpage, fatal=True)
  420. camtasia_url = compat_urlparse.urljoin(url, camtasia_cfg)
  421. camtasia_cfg = self._download_xml(
  422. camtasia_url, video_id,
  423. note='Downloading camtasia configuration',
  424. errnote='Failed to download camtasia configuration')
  425. fileset_node = camtasia_cfg.find('./playlist/array/fileset')
  426. entries = []
  427. for n in fileset_node.getchildren():
  428. url_n = n.find('./uri')
  429. if url_n is None:
  430. continue
  431. entries.append({
  432. 'id': os.path.splitext(url_n.text.rpartition('/')[2])[0],
  433. 'title': '%s - %s' % (title, n.tag),
  434. 'url': compat_urlparse.urljoin(url, url_n.text),
  435. 'duration': float_or_none(n.find('./duration').text),
  436. })
  437. return {
  438. '_type': 'playlist',
  439. 'entries': entries,
  440. 'title': title,
  441. }
  442. def _real_extract(self, url):
  443. if url.startswith('//'):
  444. return {
  445. '_type': 'url',
  446. 'url': self.http_scheme() + url,
  447. }
  448. parsed_url = compat_urlparse.urlparse(url)
  449. if not parsed_url.scheme:
  450. default_search = self._downloader.params.get('default_search')
  451. if default_search is None:
  452. default_search = 'fixup_error'
  453. if default_search in ('auto', 'auto_warning', 'fixup_error'):
  454. if '/' in url:
  455. self._downloader.report_warning('The url doesn\'t specify the protocol, trying with http')
  456. return self.url_result('http://' + url)
  457. elif default_search != 'fixup_error':
  458. if default_search == 'auto_warning':
  459. if re.match(r'^(?:url|URL)$', url):
  460. raise ExtractorError(
  461. 'Invalid URL: %r . Call youtube-dl like this: youtube-dl -v "https://www.youtube.com/watch?v=BaW_jenozKc" ' % url,
  462. expected=True)
  463. else:
  464. self._downloader.report_warning(
  465. 'Falling back to youtube search for %s . Set --default-search "auto" to suppress this warning.' % url)
  466. return self.url_result('ytsearch:' + url)
  467. if default_search in ('error', 'fixup_error'):
  468. raise ExtractorError(
  469. ('%r is not a valid URL. '
  470. 'Set --default-search "ytsearch" (or run youtube-dl "ytsearch:%s" ) to search YouTube'
  471. ) % (url, url), expected=True)
  472. else:
  473. assert ':' in default_search
  474. return self.url_result(default_search + url)
  475. url, smuggled_data = unsmuggle_url(url)
  476. force_videoid = None
  477. if smuggled_data and 'force_videoid' in smuggled_data:
  478. force_videoid = smuggled_data['force_videoid']
  479. video_id = force_videoid
  480. else:
  481. video_id = os.path.splitext(url.rstrip('/').split('/')[-1])[0]
  482. self.to_screen('%s: Requesting header' % video_id)
  483. try:
  484. response = self._send_head(url)
  485. # Check for redirect
  486. new_url = response.geturl()
  487. if url != new_url:
  488. self.report_following_redirect(new_url)
  489. if force_videoid:
  490. new_url = smuggle_url(
  491. new_url, {'force_videoid': force_videoid})
  492. return self.url_result(new_url)
  493. # Check for direct link to a video
  494. content_type = response.headers.get('Content-Type', '')
  495. m = re.match(r'^(?P<type>audio|video|application(?=/ogg$))/(?P<format_id>.+)$', content_type)
  496. if m:
  497. upload_date = response.headers.get('Last-Modified')
  498. if upload_date:
  499. upload_date = unified_strdate(upload_date)
  500. return {
  501. 'id': video_id,
  502. 'title': os.path.splitext(url_basename(url))[0],
  503. 'formats': [{
  504. 'format_id': m.group('format_id'),
  505. 'url': url,
  506. 'vcodec': 'none' if m.group('type') == 'audio' else None
  507. }],
  508. 'upload_date': upload_date,
  509. }
  510. except compat_urllib_error.HTTPError:
  511. # This may be a stupid server that doesn't like HEAD, our UA, or so
  512. pass
  513. try:
  514. webpage = self._download_webpage(url, video_id)
  515. except ValueError:
  516. # since this is the last-resort InfoExtractor, if
  517. # this error is thrown, it'll be thrown here
  518. raise ExtractorError('Failed to download URL: %s' % url)
  519. self.report_extraction(video_id)
  520. # Is it an RSS feed?
  521. try:
  522. doc = parse_xml(webpage)
  523. if doc.tag == 'rss':
  524. return self._extract_rss(url, video_id, doc)
  525. except compat_xml_parse_error:
  526. pass
  527. # Is it a Camtasia project?
  528. camtasia_res = self._extract_camtasia(url, video_id, webpage)
  529. if camtasia_res is not None:
  530. return camtasia_res
  531. # Sometimes embedded video player is hidden behind percent encoding
  532. # (e.g. https://github.com/rg3/youtube-dl/issues/2448)
  533. # Unescaping the whole page allows to handle those cases in a generic way
  534. webpage = compat_urllib_parse.unquote(webpage)
  535. # it's tempting to parse this further, but you would
  536. # have to take into account all the variations like
  537. # Video Title - Site Name
  538. # Site Name | Video Title
  539. # Video Title - Tagline | Site Name
  540. # and so on and so forth; it's just not practical
  541. video_title = self._html_search_regex(
  542. r'(?s)<title>(.*?)</title>', webpage, 'video title',
  543. default='video')
  544. # Try to detect age limit automatically
  545. age_limit = self._rta_search(webpage)
  546. # And then there are the jokers who advertise that they use RTA,
  547. # but actually don't.
  548. AGE_LIMIT_MARKERS = [
  549. r'Proudly Labeled <a href="http://www.rtalabel.org/" title="Restricted to Adults">RTA</a>',
  550. ]
  551. if any(re.search(marker, webpage) for marker in AGE_LIMIT_MARKERS):
  552. age_limit = 18
  553. # video uploader is domain name
  554. video_uploader = self._search_regex(
  555. r'^(?:https?://)?([^/]*)/.*', url, 'video uploader')
  556. # Helper method
  557. def _playlist_from_matches(matches, getter, ie=None):
  558. urlrs = orderedSet(self.url_result(getter(m), ie) for m in matches)
  559. return self.playlist_result(
  560. urlrs, playlist_id=video_id, playlist_title=video_title)
  561. # Look for BrightCove:
  562. bc_urls = BrightcoveIE._extract_brightcove_urls(webpage)
  563. if bc_urls:
  564. self.to_screen('Brightcove video detected.')
  565. entries = [{
  566. '_type': 'url',
  567. 'url': smuggle_url(bc_url, {'Referer': url}),
  568. 'ie_key': 'Brightcove'
  569. } for bc_url in bc_urls]
  570. return {
  571. '_type': 'playlist',
  572. 'title': video_title,
  573. 'id': video_id,
  574. 'entries': entries,
  575. }
  576. # Look for embedded (iframe) Vimeo player
  577. mobj = re.search(
  578. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//player\.vimeo\.com/video/.+?)\1', webpage)
  579. if mobj:
  580. player_url = unescapeHTML(mobj.group('url'))
  581. surl = smuggle_url(player_url, {'Referer': url})
  582. return self.url_result(surl, 'Vimeo')
  583. # Look for embedded (swf embed) Vimeo player
  584. mobj = re.search(
  585. r'<embed[^>]+?src="(https?://(?:www\.)?vimeo\.com/moogaloop\.swf.+?)"', webpage)
  586. if mobj:
  587. return self.url_result(mobj.group(1), 'Vimeo')
  588. # Look for embedded YouTube player
  589. matches = re.findall(r'''(?x)
  590. (?:
  591. <iframe[^>]+?src=|
  592. data-video-url=|
  593. <embed[^>]+?src=|
  594. embedSWF\(?:\s*
  595. )
  596. (["\'])
  597. (?P<url>(?:https?:)?//(?:www\.)?youtube\.com/
  598. (?:embed|v)/.+?)
  599. \1''', webpage)
  600. if matches:
  601. return _playlist_from_matches(
  602. matches, lambda m: unescapeHTML(m[1]), ie='Youtube')
  603. # Look for embedded Dailymotion player
  604. matches = re.findall(
  605. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/embed/video/.+?)\1', webpage)
  606. if matches:
  607. return _playlist_from_matches(
  608. matches, lambda m: unescapeHTML(m[1]))
  609. # Look for embedded Wistia player
  610. match = re.search(
  611. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:fast\.)?wistia\.net/embed/iframe/.+?)\1', webpage)
  612. if match:
  613. return {
  614. '_type': 'url_transparent',
  615. 'url': unescapeHTML(match.group('url')),
  616. 'ie_key': 'Wistia',
  617. 'uploader': video_uploader,
  618. 'title': video_title,
  619. 'id': video_id,
  620. }
  621. # Look for embedded blip.tv player
  622. mobj = re.search(r'<meta\s[^>]*https?://api\.blip\.tv/\w+/redirect/\w+/(\d+)', webpage)
  623. if mobj:
  624. return self.url_result('http://blip.tv/a/a-'+mobj.group(1), 'BlipTV')
  625. mobj = re.search(r'<(?:iframe|embed|object)\s[^>]*(https?://(?:\w+\.)?blip\.tv/(?:play/|api\.swf#)[a-zA-Z0-9_]+)', webpage)
  626. if mobj:
  627. return self.url_result(mobj.group(1), 'BlipTV')
  628. # Look for embedded condenast player
  629. matches = re.findall(
  630. r'<iframe\s+(?:[a-zA-Z-]+="[^"]+"\s+)*?src="(https?://player\.cnevids\.com/embed/[^"]+")',
  631. webpage)
  632. if matches:
  633. return {
  634. '_type': 'playlist',
  635. 'entries': [{
  636. '_type': 'url',
  637. 'ie_key': 'CondeNast',
  638. 'url': ma,
  639. } for ma in matches],
  640. 'title': video_title,
  641. 'id': video_id,
  642. }
  643. # Look for Bandcamp pages with custom domain
  644. mobj = re.search(r'<meta property="og:url"[^>]*?content="(.*?bandcamp\.com.*?)"', webpage)
  645. if mobj is not None:
  646. burl = unescapeHTML(mobj.group(1))
  647. # Don't set the extractor because it can be a track url or an album
  648. return self.url_result(burl)
  649. # Look for embedded Vevo player
  650. mobj = re.search(
  651. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:cache\.)?vevo\.com/.+?)\1', webpage)
  652. if mobj is not None:
  653. return self.url_result(mobj.group('url'))
  654. # Look for Ooyala videos
  655. mobj = (re.search(r'player.ooyala.com/[^"?]+\?[^"]*?(?:embedCode|ec)=(?P<ec>[^"&]+)', webpage) or
  656. re.search(r'OO.Player.create\([\'"].*?[\'"],\s*[\'"](?P<ec>.{32})[\'"]', webpage))
  657. if mobj is not None:
  658. return OoyalaIE._build_url_result(mobj.group('ec'))
  659. # Look for Aparat videos
  660. mobj = re.search(r'<iframe .*?src="(http://www\.aparat\.com/video/[^"]+)"', webpage)
  661. if mobj is not None:
  662. return self.url_result(mobj.group(1), 'Aparat')
  663. # Look for MPORA videos
  664. mobj = re.search(r'<iframe .*?src="(http://mpora\.(?:com|de)/videos/[^"]+)"', webpage)
  665. if mobj is not None:
  666. return self.url_result(mobj.group(1), 'Mpora')
  667. # Look for embedded NovaMov-based player
  668. mobj = re.search(
  669. r'''(?x)<(?:pagespeed_)?iframe[^>]+?src=(["\'])
  670. (?P<url>http://(?:(?:embed|www)\.)?
  671. (?:novamov\.com|
  672. nowvideo\.(?:ch|sx|eu|at|ag|co)|
  673. videoweed\.(?:es|com)|
  674. movshare\.(?:net|sx|ag)|
  675. divxstage\.(?:eu|net|ch|co|at|ag))
  676. /embed\.php.+?)\1''', webpage)
  677. if mobj is not None:
  678. return self.url_result(mobj.group('url'))
  679. # Look for embedded Facebook player
  680. mobj = re.search(
  681. r'<iframe[^>]+?src=(["\'])(?P<url>https://www\.facebook\.com/video/embed.+?)\1', webpage)
  682. if mobj is not None:
  683. return self.url_result(mobj.group('url'), 'Facebook')
  684. # Look for embedded VK player
  685. mobj = re.search(r'<iframe[^>]+?src=(["\'])(?P<url>https?://vk\.com/video_ext\.php.+?)\1', webpage)
  686. if mobj is not None:
  687. return self.url_result(mobj.group('url'), 'VK')
  688. # Look for embedded ivi player
  689. mobj = re.search(r'<embed[^>]+?src=(["\'])(?P<url>https?://(?:www\.)?ivi\.ru/video/player.+?)\1', webpage)
  690. if mobj is not None:
  691. return self.url_result(mobj.group('url'), 'Ivi')
  692. # Look for embedded Huffington Post player
  693. mobj = re.search(
  694. r'<iframe[^>]+?src=(["\'])(?P<url>https?://embed\.live\.huffingtonpost\.com/.+?)\1', webpage)
  695. if mobj is not None:
  696. return self.url_result(mobj.group('url'), 'HuffPost')
  697. # Look for embed.ly
  698. mobj = re.search(r'class=["\']embedly-card["\'][^>]href=["\'](?P<url>[^"\']+)', webpage)
  699. if mobj is not None:
  700. return self.url_result(mobj.group('url'))
  701. mobj = re.search(r'class=["\']embedly-embed["\'][^>]src=["\'][^"\']*url=(?P<url>[^&]+)', webpage)
  702. if mobj is not None:
  703. return self.url_result(compat_urllib_parse.unquote(mobj.group('url')))
  704. # Look for funnyordie embed
  705. matches = re.findall(r'<iframe[^>]+?src="(https?://(?:www\.)?funnyordie\.com/embed/[^"]+)"', webpage)
  706. if matches:
  707. return _playlist_from_matches(
  708. matches, getter=unescapeHTML, ie='FunnyOrDie')
  709. # Look for embedded RUTV player
  710. rutv_url = RUTVIE._extract_url(webpage)
  711. if rutv_url:
  712. return self.url_result(rutv_url, 'RUTV')
  713. # Look for embedded TED player
  714. mobj = re.search(
  715. r'<iframe[^>]+?src=(["\'])(?P<url>http://embed\.ted\.com/.+?)\1', webpage)
  716. if mobj is not None:
  717. return self.url_result(mobj.group('url'), 'TED')
  718. # Look for embedded Ustream videos
  719. mobj = re.search(
  720. r'<iframe[^>]+?src=(["\'])(?P<url>http://www\.ustream\.tv/embed/.+?)\1', webpage)
  721. if mobj is not None:
  722. return self.url_result(mobj.group('url'), 'Ustream')
  723. # Look for embedded arte.tv player
  724. mobj = re.search(
  725. r'<script [^>]*?src="(?P<url>http://www\.arte\.tv/playerv2/embed[^"]+)"',
  726. webpage)
  727. if mobj is not None:
  728. return self.url_result(mobj.group('url'), 'ArteTVEmbed')
  729. # Look for embedded smotri.com player
  730. smotri_url = SmotriIE._extract_url(webpage)
  731. if smotri_url:
  732. return self.url_result(smotri_url, 'Smotri')
  733. # Look for embeded soundcloud player
  734. mobj = re.search(
  735. r'<iframe src="(?P<url>https?://(?:w\.)?soundcloud\.com/player[^"]+)"',
  736. webpage)
  737. if mobj is not None:
  738. url = unescapeHTML(mobj.group('url'))
  739. return self.url_result(url)
  740. # Look for embedded vulture.com player
  741. mobj = re.search(
  742. r'<iframe src="(?P<url>https?://video\.vulture\.com/[^"]+)"',
  743. webpage)
  744. if mobj is not None:
  745. url = unescapeHTML(mobj.group('url'))
  746. return self.url_result(url, ie='Vulture')
  747. # Look for embedded mtvservices player
  748. mobj = re.search(
  749. r'<iframe src="(?P<url>https?://media\.mtvnservices\.com/embed/[^"]+)"',
  750. webpage)
  751. if mobj is not None:
  752. url = unescapeHTML(mobj.group('url'))
  753. return self.url_result(url, ie='MTVServicesEmbedded')
  754. # Look for embedded yahoo player
  755. mobj = re.search(
  756. r'<iframe[^>]+?src=(["\'])(?P<url>https?://(?:screen|movies)\.yahoo\.com/.+?\.html\?format=embed)\1',
  757. webpage)
  758. if mobj is not None:
  759. return self.url_result(mobj.group('url'), 'Yahoo')
  760. # Look for embedded sbs.com.au player
  761. mobj = re.search(
  762. r'<iframe[^>]+?src=(["\'])(?P<url>https?://(?:www\.)sbs\.com\.au/ondemand/video/single/.+?)\1',
  763. webpage)
  764. if mobj is not None:
  765. return self.url_result(mobj.group('url'), 'SBS')
  766. # Start with something easy: JW Player in SWFObject
  767. found = re.findall(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  768. if not found:
  769. # Look for gorilla-vid style embedding
  770. found = re.findall(r'''(?sx)
  771. (?:
  772. jw_plugins|
  773. JWPlayerOptions|
  774. jwplayer\s*\(\s*["'][^'"]+["']\s*\)\s*\.setup
  775. )
  776. .*?file\s*:\s*["\'](.*?)["\']''', webpage)
  777. if not found:
  778. # Broaden the search a little bit
  779. found = re.findall(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  780. if not found:
  781. # Broaden the findall a little bit: JWPlayer JS loader
  782. found = re.findall(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http(?![^\'"]+\.[0-9]+[\'"])[^\'"]+)["\']', webpage)
  783. if not found:
  784. # Flow player
  785. found = re.findall(r'''(?xs)
  786. flowplayer\("[^"]+",\s*
  787. \{[^}]+?\}\s*,
  788. \s*{[^}]+? ["']?clip["']?\s*:\s*\{\s*
  789. ["']?url["']?\s*:\s*["']([^"']+)["']
  790. ''', webpage)
  791. assert found
  792. if not found:
  793. # Try to find twitter cards info
  794. found = re.findall(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
  795. if not found:
  796. # We look for Open Graph info:
  797. # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
  798. m_video_type = re.findall(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
  799. # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
  800. if m_video_type is not None:
  801. def check_video(vurl):
  802. vpath = compat_urlparse.urlparse(vurl).path
  803. return '.' in vpath and not vpath.endswith('.swf')
  804. found = list(filter(
  805. check_video,
  806. re.findall(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)))
  807. if not found:
  808. # HTML5 video
  809. found = re.findall(r'(?s)<video[^<]*(?:>.*?<source.*?)? src="([^"]+)"', webpage)
  810. if not found:
  811. found = re.search(
  812. r'(?i)<meta\s+(?=(?:[a-z-]+="[^"]+"\s+)*http-equiv="refresh")'
  813. r'(?:[a-z-]+="[^"]+"\s+)*?content="[0-9]{,2};url=\'([^\']+)\'"',
  814. webpage)
  815. if found:
  816. new_url = found.group(1)
  817. self.report_following_redirect(new_url)
  818. return {
  819. '_type': 'url',
  820. 'url': new_url,
  821. }
  822. if not found:
  823. raise ExtractorError('Unsupported URL: %s' % url)
  824. entries = []
  825. for video_url in found:
  826. video_url = compat_urlparse.urljoin(url, video_url)
  827. video_id = compat_urllib_parse.unquote(os.path.basename(video_url))
  828. # Sometimes, jwplayer extraction will result in a YouTube URL
  829. if YoutubeIE.suitable(video_url):
  830. entries.append(self.url_result(video_url, 'Youtube'))
  831. continue
  832. # here's a fun little line of code for you:
  833. video_id = os.path.splitext(video_id)[0]
  834. entries.append({
  835. 'id': video_id,
  836. 'url': video_url,
  837. 'uploader': video_uploader,
  838. 'title': video_title,
  839. 'age_limit': age_limit,
  840. })
  841. if len(entries) == 1:
  842. return entries[0]
  843. else:
  844. for num, e in enumerate(entries, start=1):
  845. e['title'] = '%s (%d)' % (e['title'], num)
  846. return {
  847. '_type': 'playlist',
  848. 'entries': entries,
  849. }