generic.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  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. ]
  330. def report_download_webpage(self, video_id):
  331. """Report webpage download."""
  332. if not self._downloader.params.get('test', False):
  333. self._downloader.report_warning('Falling back on generic information extractor.')
  334. super(GenericIE, self).report_download_webpage(video_id)
  335. def report_following_redirect(self, new_url):
  336. """Report information extraction."""
  337. self._downloader.to_screen('[redirect] Following redirect to %s' % new_url)
  338. def _send_head(self, url):
  339. """Check if it is a redirect, like url shorteners, in case return the new url."""
  340. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  341. """
  342. Subclass the HTTPRedirectHandler to make it use our
  343. HEADRequest also on the redirected URL
  344. """
  345. def redirect_request(self, req, fp, code, msg, headers, newurl):
  346. if code in (301, 302, 303, 307):
  347. newurl = newurl.replace(' ', '%20')
  348. newheaders = dict((k,v) for k,v in req.headers.items()
  349. if k.lower() not in ("content-length", "content-type"))
  350. try:
  351. # This function was deprecated in python 3.3 and removed in 3.4
  352. origin_req_host = req.get_origin_req_host()
  353. except AttributeError:
  354. origin_req_host = req.origin_req_host
  355. return HEADRequest(newurl,
  356. headers=newheaders,
  357. origin_req_host=origin_req_host,
  358. unverifiable=True)
  359. else:
  360. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  361. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  362. """
  363. Fallback to GET if HEAD is not allowed (405 HTTP error)
  364. """
  365. def http_error_405(self, req, fp, code, msg, headers):
  366. fp.read()
  367. fp.close()
  368. newheaders = dict((k,v) for k,v in req.headers.items()
  369. if k.lower() not in ("content-length", "content-type"))
  370. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  371. headers=newheaders,
  372. origin_req_host=req.get_origin_req_host(),
  373. unverifiable=True))
  374. # Build our opener
  375. opener = compat_urllib_request.OpenerDirector()
  376. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  377. HTTPMethodFallback, HEADRedirectHandler,
  378. compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  379. opener.add_handler(handler())
  380. response = opener.open(HEADRequest(url))
  381. if response is None:
  382. raise ExtractorError('Invalid URL protocol')
  383. return response
  384. def _extract_rss(self, url, video_id, doc):
  385. playlist_title = doc.find('./channel/title').text
  386. playlist_desc_el = doc.find('./channel/description')
  387. playlist_desc = None if playlist_desc_el is None else playlist_desc_el.text
  388. entries = [{
  389. '_type': 'url',
  390. 'url': e.find('link').text,
  391. 'title': e.find('title').text,
  392. } for e in doc.findall('./channel/item')]
  393. return {
  394. '_type': 'playlist',
  395. 'id': url,
  396. 'title': playlist_title,
  397. 'description': playlist_desc,
  398. 'entries': entries,
  399. }
  400. def _extract_camtasia(self, url, video_id, webpage):
  401. """ Returns None if no camtasia video can be found. """
  402. camtasia_cfg = self._search_regex(
  403. r'fo\.addVariable\(\s*"csConfigFile",\s*"([^"]+)"\s*\);',
  404. webpage, 'camtasia configuration file', default=None)
  405. if camtasia_cfg is None:
  406. return None
  407. title = self._html_search_meta('DC.title', webpage, fatal=True)
  408. camtasia_url = compat_urlparse.urljoin(url, camtasia_cfg)
  409. camtasia_cfg = self._download_xml(
  410. camtasia_url, video_id,
  411. note='Downloading camtasia configuration',
  412. errnote='Failed to download camtasia configuration')
  413. fileset_node = camtasia_cfg.find('./playlist/array/fileset')
  414. entries = []
  415. for n in fileset_node.getchildren():
  416. url_n = n.find('./uri')
  417. if url_n is None:
  418. continue
  419. entries.append({
  420. 'id': os.path.splitext(url_n.text.rpartition('/')[2])[0],
  421. 'title': '%s - %s' % (title, n.tag),
  422. 'url': compat_urlparse.urljoin(url, url_n.text),
  423. 'duration': float_or_none(n.find('./duration').text),
  424. })
  425. return {
  426. '_type': 'playlist',
  427. 'entries': entries,
  428. 'title': title,
  429. }
  430. def _real_extract(self, url):
  431. if url.startswith('//'):
  432. return {
  433. '_type': 'url',
  434. 'url': self.http_scheme() + url,
  435. }
  436. parsed_url = compat_urlparse.urlparse(url)
  437. if not parsed_url.scheme:
  438. default_search = self._downloader.params.get('default_search')
  439. if default_search is None:
  440. default_search = 'fixup_error'
  441. if default_search in ('auto', 'auto_warning', 'fixup_error'):
  442. if '/' in url:
  443. self._downloader.report_warning('The url doesn\'t specify the protocol, trying with http')
  444. return self.url_result('http://' + url)
  445. elif default_search != 'fixup_error':
  446. if default_search == 'auto_warning':
  447. if re.match(r'^(?:url|URL)$', url):
  448. raise ExtractorError(
  449. 'Invalid URL: %r . Call youtube-dl like this: youtube-dl -v "https://www.youtube.com/watch?v=BaW_jenozKc" ' % url,
  450. expected=True)
  451. else:
  452. self._downloader.report_warning(
  453. 'Falling back to youtube search for %s . Set --default-search "auto" to suppress this warning.' % url)
  454. return self.url_result('ytsearch:' + url)
  455. if default_search in ('error', 'fixup_error'):
  456. raise ExtractorError(
  457. ('%r is not a valid URL. '
  458. 'Set --default-search "ytsearch" (or run youtube-dl "ytsearch:%s" ) to search YouTube'
  459. ) % (url, url), expected=True)
  460. else:
  461. assert ':' in default_search
  462. return self.url_result(default_search + url)
  463. url, smuggled_data = unsmuggle_url(url)
  464. force_videoid = None
  465. if smuggled_data and 'force_videoid' in smuggled_data:
  466. force_videoid = smuggled_data['force_videoid']
  467. video_id = force_videoid
  468. else:
  469. video_id = os.path.splitext(url.rstrip('/').split('/')[-1])[0]
  470. self.to_screen('%s: Requesting header' % video_id)
  471. try:
  472. response = self._send_head(url)
  473. # Check for redirect
  474. new_url = response.geturl()
  475. if url != new_url:
  476. self.report_following_redirect(new_url)
  477. if force_videoid:
  478. new_url = smuggle_url(
  479. new_url, {'force_videoid': force_videoid})
  480. return self.url_result(new_url)
  481. # Check for direct link to a video
  482. content_type = response.headers.get('Content-Type', '')
  483. m = re.match(r'^(?P<type>audio|video|application(?=/ogg$))/(?P<format_id>.+)$', content_type)
  484. if m:
  485. upload_date = response.headers.get('Last-Modified')
  486. if upload_date:
  487. upload_date = unified_strdate(upload_date)
  488. return {
  489. 'id': video_id,
  490. 'title': os.path.splitext(url_basename(url))[0],
  491. 'formats': [{
  492. 'format_id': m.group('format_id'),
  493. 'url': url,
  494. 'vcodec': 'none' if m.group('type') == 'audio' else None
  495. }],
  496. 'upload_date': upload_date,
  497. }
  498. except compat_urllib_error.HTTPError:
  499. # This may be a stupid server that doesn't like HEAD, our UA, or so
  500. pass
  501. try:
  502. webpage = self._download_webpage(url, video_id)
  503. except ValueError:
  504. # since this is the last-resort InfoExtractor, if
  505. # this error is thrown, it'll be thrown here
  506. raise ExtractorError('Failed to download URL: %s' % url)
  507. self.report_extraction(video_id)
  508. # Is it an RSS feed?
  509. try:
  510. doc = parse_xml(webpage)
  511. if doc.tag == 'rss':
  512. return self._extract_rss(url, video_id, doc)
  513. except compat_xml_parse_error:
  514. pass
  515. # Is it a Camtasia project?
  516. camtasia_res = self._extract_camtasia(url, video_id, webpage)
  517. if camtasia_res is not None:
  518. return camtasia_res
  519. # Sometimes embedded video player is hidden behind percent encoding
  520. # (e.g. https://github.com/rg3/youtube-dl/issues/2448)
  521. # Unescaping the whole page allows to handle those cases in a generic way
  522. webpage = compat_urllib_parse.unquote(webpage)
  523. # it's tempting to parse this further, but you would
  524. # have to take into account all the variations like
  525. # Video Title - Site Name
  526. # Site Name | Video Title
  527. # Video Title - Tagline | Site Name
  528. # and so on and so forth; it's just not practical
  529. video_title = self._html_search_regex(
  530. r'(?s)<title>(.*?)</title>', webpage, 'video title',
  531. default='video')
  532. # video uploader is domain name
  533. video_uploader = self._search_regex(
  534. r'^(?:https?://)?([^/]*)/.*', url, 'video uploader')
  535. # Helper method
  536. def _playlist_from_matches(matches, getter, ie=None):
  537. urlrs = orderedSet(self.url_result(getter(m), ie) for m in matches)
  538. return self.playlist_result(
  539. urlrs, playlist_id=video_id, playlist_title=video_title)
  540. # Look for BrightCove:
  541. bc_urls = BrightcoveIE._extract_brightcove_urls(webpage)
  542. if bc_urls:
  543. self.to_screen('Brightcove video detected.')
  544. entries = [{
  545. '_type': 'url',
  546. 'url': smuggle_url(bc_url, {'Referer': url}),
  547. 'ie_key': 'Brightcove'
  548. } for bc_url in bc_urls]
  549. return {
  550. '_type': 'playlist',
  551. 'title': video_title,
  552. 'id': video_id,
  553. 'entries': entries,
  554. }
  555. # Look for embedded (iframe) Vimeo player
  556. mobj = re.search(
  557. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//player\.vimeo\.com/video/.+?)\1', webpage)
  558. if mobj:
  559. player_url = unescapeHTML(mobj.group('url'))
  560. surl = smuggle_url(player_url, {'Referer': url})
  561. return self.url_result(surl, 'Vimeo')
  562. # Look for embedded (swf embed) Vimeo player
  563. mobj = re.search(
  564. r'<embed[^>]+?src="(https?://(?:www\.)?vimeo\.com/moogaloop\.swf.+?)"', webpage)
  565. if mobj:
  566. return self.url_result(mobj.group(1), 'Vimeo')
  567. # Look for embedded YouTube player
  568. matches = re.findall(r'''(?x)
  569. (?:
  570. <iframe[^>]+?src=|
  571. data-video-url=|
  572. <embed[^>]+?src=|
  573. embedSWF\(?:\s*
  574. )
  575. (["\'])
  576. (?P<url>(?:https?:)?//(?:www\.)?youtube\.com/
  577. (?:embed|v)/.+?)
  578. \1''', webpage)
  579. if matches:
  580. return _playlist_from_matches(
  581. matches, lambda m: unescapeHTML(m[1]), ie='Youtube')
  582. # Look for embedded Dailymotion player
  583. matches = re.findall(
  584. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/embed/video/.+?)\1', webpage)
  585. if matches:
  586. return _playlist_from_matches(
  587. matches, lambda m: unescapeHTML(m[1]))
  588. # Look for embedded Wistia player
  589. match = re.search(
  590. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:fast\.)?wistia\.net/embed/iframe/.+?)\1', webpage)
  591. if match:
  592. return {
  593. '_type': 'url_transparent',
  594. 'url': unescapeHTML(match.group('url')),
  595. 'ie_key': 'Wistia',
  596. 'uploader': video_uploader,
  597. 'title': video_title,
  598. 'id': video_id,
  599. }
  600. # Look for embedded blip.tv player
  601. mobj = re.search(r'<meta\s[^>]*https?://api\.blip\.tv/\w+/redirect/\w+/(\d+)', webpage)
  602. if mobj:
  603. return self.url_result('http://blip.tv/a/a-'+mobj.group(1), 'BlipTV')
  604. mobj = re.search(r'<(?:iframe|embed|object)\s[^>]*(https?://(?:\w+\.)?blip\.tv/(?:play/|api\.swf#)[a-zA-Z0-9_]+)', webpage)
  605. if mobj:
  606. return self.url_result(mobj.group(1), 'BlipTV')
  607. # Look for embedded condenast player
  608. matches = re.findall(
  609. r'<iframe\s+(?:[a-zA-Z-]+="[^"]+"\s+)*?src="(https?://player\.cnevids\.com/embed/[^"]+")',
  610. webpage)
  611. if matches:
  612. return {
  613. '_type': 'playlist',
  614. 'entries': [{
  615. '_type': 'url',
  616. 'ie_key': 'CondeNast',
  617. 'url': ma,
  618. } for ma in matches],
  619. 'title': video_title,
  620. 'id': video_id,
  621. }
  622. # Look for Bandcamp pages with custom domain
  623. mobj = re.search(r'<meta property="og:url"[^>]*?content="(.*?bandcamp\.com.*?)"', webpage)
  624. if mobj is not None:
  625. burl = unescapeHTML(mobj.group(1))
  626. # Don't set the extractor because it can be a track url or an album
  627. return self.url_result(burl)
  628. # Look for embedded Vevo player
  629. mobj = re.search(
  630. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:cache\.)?vevo\.com/.+?)\1', webpage)
  631. if mobj is not None:
  632. return self.url_result(mobj.group('url'))
  633. # Look for Ooyala videos
  634. mobj = (re.search(r'player.ooyala.com/[^"?]+\?[^"]*?(?:embedCode|ec)=(?P<ec>[^"&]+)', webpage) or
  635. re.search(r'OO.Player.create\([\'"].*?[\'"],\s*[\'"](?P<ec>.{32})[\'"]', webpage))
  636. if mobj is not None:
  637. return OoyalaIE._build_url_result(mobj.group('ec'))
  638. # Look for Aparat videos
  639. mobj = re.search(r'<iframe .*?src="(http://www\.aparat\.com/video/[^"]+)"', webpage)
  640. if mobj is not None:
  641. return self.url_result(mobj.group(1), 'Aparat')
  642. # Look for MPORA videos
  643. mobj = re.search(r'<iframe .*?src="(http://mpora\.(?:com|de)/videos/[^"]+)"', webpage)
  644. if mobj is not None:
  645. return self.url_result(mobj.group(1), 'Mpora')
  646. # Look for embedded NovaMov-based player
  647. mobj = re.search(
  648. r'''(?x)<(?:pagespeed_)?iframe[^>]+?src=(["\'])
  649. (?P<url>http://(?:(?:embed|www)\.)?
  650. (?:novamov\.com|
  651. nowvideo\.(?:ch|sx|eu|at|ag|co)|
  652. videoweed\.(?:es|com)|
  653. movshare\.(?:net|sx|ag)|
  654. divxstage\.(?:eu|net|ch|co|at|ag))
  655. /embed\.php.+?)\1''', webpage)
  656. if mobj is not None:
  657. return self.url_result(mobj.group('url'))
  658. # Look for embedded Facebook player
  659. mobj = re.search(
  660. r'<iframe[^>]+?src=(["\'])(?P<url>https://www\.facebook\.com/video/embed.+?)\1', webpage)
  661. if mobj is not None:
  662. return self.url_result(mobj.group('url'), 'Facebook')
  663. # Look for embedded VK player
  664. mobj = re.search(r'<iframe[^>]+?src=(["\'])(?P<url>https?://vk\.com/video_ext\.php.+?)\1', webpage)
  665. if mobj is not None:
  666. return self.url_result(mobj.group('url'), 'VK')
  667. # Look for embedded ivi player
  668. mobj = re.search(r'<embed[^>]+?src=(["\'])(?P<url>https?://(?:www\.)?ivi\.ru/video/player.+?)\1', webpage)
  669. if mobj is not None:
  670. return self.url_result(mobj.group('url'), 'Ivi')
  671. # Look for embedded Huffington Post player
  672. mobj = re.search(
  673. r'<iframe[^>]+?src=(["\'])(?P<url>https?://embed\.live\.huffingtonpost\.com/.+?)\1', webpage)
  674. if mobj is not None:
  675. return self.url_result(mobj.group('url'), 'HuffPost')
  676. # Look for embed.ly
  677. mobj = re.search(r'class=["\']embedly-card["\'][^>]href=["\'](?P<url>[^"\']+)', webpage)
  678. if mobj is not None:
  679. return self.url_result(mobj.group('url'))
  680. mobj = re.search(r'class=["\']embedly-embed["\'][^>]src=["\'][^"\']*url=(?P<url>[^&]+)', webpage)
  681. if mobj is not None:
  682. return self.url_result(compat_urllib_parse.unquote(mobj.group('url')))
  683. # Look for funnyordie embed
  684. matches = re.findall(r'<iframe[^>]+?src="(https?://(?:www\.)?funnyordie\.com/embed/[^"]+)"', webpage)
  685. if matches:
  686. return _playlist_from_matches(
  687. matches, getter=unescapeHTML, ie='FunnyOrDie')
  688. # Look for embedded RUTV player
  689. rutv_url = RUTVIE._extract_url(webpage)
  690. if rutv_url:
  691. return self.url_result(rutv_url, 'RUTV')
  692. # Look for embedded TED player
  693. mobj = re.search(
  694. r'<iframe[^>]+?src=(["\'])(?P<url>http://embed\.ted\.com/.+?)\1', webpage)
  695. if mobj is not None:
  696. return self.url_result(mobj.group('url'), 'TED')
  697. # Look for embedded Ustream videos
  698. mobj = re.search(
  699. r'<iframe[^>]+?src=(["\'])(?P<url>http://www\.ustream\.tv/embed/.+?)\1', webpage)
  700. if mobj is not None:
  701. return self.url_result(mobj.group('url'), 'Ustream')
  702. # Look for embedded arte.tv player
  703. mobj = re.search(
  704. r'<script [^>]*?src="(?P<url>http://www\.arte\.tv/playerv2/embed[^"]+)"',
  705. webpage)
  706. if mobj is not None:
  707. return self.url_result(mobj.group('url'), 'ArteTVEmbed')
  708. # Look for embedded smotri.com player
  709. smotri_url = SmotriIE._extract_url(webpage)
  710. if smotri_url:
  711. return self.url_result(smotri_url, 'Smotri')
  712. # Look for embeded soundcloud player
  713. mobj = re.search(
  714. r'<iframe src="(?P<url>https?://(?:w\.)?soundcloud\.com/player[^"]+)"',
  715. webpage)
  716. if mobj is not None:
  717. url = unescapeHTML(mobj.group('url'))
  718. return self.url_result(url)
  719. # Look for embedded vulture.com player
  720. mobj = re.search(
  721. r'<iframe src="(?P<url>https?://video\.vulture\.com/[^"]+)"',
  722. webpage)
  723. if mobj is not None:
  724. url = unescapeHTML(mobj.group('url'))
  725. return self.url_result(url, ie='Vulture')
  726. # Look for embedded mtvservices player
  727. mobj = re.search(
  728. r'<iframe src="(?P<url>https?://media\.mtvnservices\.com/embed/[^"]+)"',
  729. webpage)
  730. if mobj is not None:
  731. url = unescapeHTML(mobj.group('url'))
  732. return self.url_result(url, ie='MTVServicesEmbedded')
  733. # Look for embedded yahoo player
  734. mobj = re.search(
  735. r'<iframe[^>]+?src=(["\'])(?P<url>https?://(?:screen|movies)\.yahoo\.com/.+?\.html\?format=embed)\1',
  736. webpage)
  737. if mobj is not None:
  738. return self.url_result(mobj.group('url'), 'Yahoo')
  739. # Look for embedded sbs.com.au player
  740. mobj = re.search(
  741. r'<iframe[^>]+?src=(["\'])(?P<url>https?://(?:www\.)sbs\.com\.au/ondemand/video/single/.+?)\1',
  742. webpage)
  743. if mobj is not None:
  744. return self.url_result(mobj.group('url'), 'SBS')
  745. # Start with something easy: JW Player in SWFObject
  746. found = re.findall(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  747. if not found:
  748. # Look for gorilla-vid style embedding
  749. found = re.findall(r'''(?sx)
  750. (?:
  751. jw_plugins|
  752. JWPlayerOptions|
  753. jwplayer\s*\(\s*["'][^'"]+["']\s*\)\s*\.setup
  754. )
  755. .*?file\s*:\s*["\'](.*?)["\']''', webpage)
  756. if not found:
  757. # Broaden the search a little bit
  758. found = re.findall(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  759. if not found:
  760. # Broaden the findall a little bit: JWPlayer JS loader
  761. found = re.findall(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http(?![^\'"]+\.[0-9]+[\'"])[^\'"]+)["\']', webpage)
  762. if not found:
  763. # Try to find twitter cards info
  764. found = re.findall(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
  765. if not found:
  766. # We look for Open Graph info:
  767. # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
  768. m_video_type = re.findall(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
  769. # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
  770. if m_video_type is not None:
  771. def check_video(vurl):
  772. vpath = compat_urlparse.urlparse(vurl).path
  773. return '.' in vpath and not vpath.endswith('.swf')
  774. found = list(filter(
  775. check_video,
  776. re.findall(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)))
  777. if not found:
  778. # HTML5 video
  779. found = re.findall(r'(?s)<video[^<]*(?:>.*?<source.*?)? src="([^"]+)"', webpage)
  780. if not found:
  781. found = re.search(
  782. r'(?i)<meta\s+(?=(?:[a-z-]+="[^"]+"\s+)*http-equiv="refresh")'
  783. r'(?:[a-z-]+="[^"]+"\s+)*?content="[0-9]{,2};url=\'([^\']+)\'"',
  784. webpage)
  785. if found:
  786. new_url = found.group(1)
  787. self.report_following_redirect(new_url)
  788. return {
  789. '_type': 'url',
  790. 'url': new_url,
  791. }
  792. if not found:
  793. raise ExtractorError('Unsupported URL: %s' % url)
  794. entries = []
  795. for video_url in found:
  796. video_url = compat_urlparse.urljoin(url, video_url)
  797. video_id = compat_urllib_parse.unquote(os.path.basename(video_url))
  798. # Sometimes, jwplayer extraction will result in a YouTube URL
  799. if YoutubeIE.suitable(video_url):
  800. entries.append(self.url_result(video_url, 'Youtube'))
  801. continue
  802. # here's a fun little line of code for you:
  803. video_id = os.path.splitext(video_id)[0]
  804. entries.append({
  805. 'id': video_id,
  806. 'url': video_url,
  807. 'uploader': video_uploader,
  808. 'title': video_title,
  809. })
  810. if len(entries) == 1:
  811. return entries[0]
  812. else:
  813. for num, e in enumerate(entries, start=1):
  814. e['title'] = '%s (%d)' % (e['title'], num)
  815. return {
  816. '_type': 'playlist',
  817. 'entries': entries,
  818. }