InfoExtractors.py 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032
  1. import base64
  2. import datetime
  3. import itertools
  4. import netrc
  5. import os
  6. import re
  7. import socket
  8. import time
  9. import email.utils
  10. import xml.etree.ElementTree
  11. import random
  12. import math
  13. import operator
  14. import hashlib
  15. import binascii
  16. import urllib
  17. from .utils import *
  18. from .extractor.common import InfoExtractor, SearchInfoExtractor
  19. from .extractor.ard import ARDIE
  20. from .extractor.arte import ArteTvIE
  21. from .extractor.bliptv import BlipTVIE, BlipTVUserIE
  22. from .extractor.comedycentral import ComedyCentralIE
  23. from .extractor.dailymotion import DailymotionIE
  24. from .extractor.facebook import FacebookIE
  25. from .extractor.gametrailers import GametrailersIE
  26. from .extractor.generic import GenericIE
  27. from .extractor.googleplus import GooglePlusIE
  28. from .extractor.googlesearch import GoogleSearchIE
  29. from .extractor.metacafe import MetacafeIE
  30. from .extractor.myvideo import MyVideoIE
  31. from .extractor.statigram import StatigramIE
  32. from .extractor.photobucket import PhotobucketIE
  33. from .extractor.soundcloud import SoundcloudIE, SoundcloudSetIE
  34. from .extractor.vimeo import VimeoIE
  35. from .extractor.yahoo import YahooIE, YahooSearchIE
  36. from .extractor.youtube import YoutubeIE, YoutubePlaylistIE, YoutubeSearchIE, YoutubeUserIE, YoutubeChannelIE
  37. from .extractor.zdf import ZDFIE
  38. class DepositFilesIE(InfoExtractor):
  39. """Information extractor for depositfiles.com"""
  40. _VALID_URL = r'(?:http://)?(?:\w+\.)?depositfiles\.com/(?:../(?#locale))?files/(.+)'
  41. def _real_extract(self, url):
  42. file_id = url.split('/')[-1]
  43. # Rebuild url in english locale
  44. url = 'http://depositfiles.com/en/files/' + file_id
  45. # Retrieve file webpage with 'Free download' button pressed
  46. free_download_indication = { 'gateway_result' : '1' }
  47. request = compat_urllib_request.Request(url, compat_urllib_parse.urlencode(free_download_indication))
  48. try:
  49. self.report_download_webpage(file_id)
  50. webpage = compat_urllib_request.urlopen(request).read()
  51. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  52. raise ExtractorError(u'Unable to retrieve file webpage: %s' % compat_str(err))
  53. # Search for the real file URL
  54. mobj = re.search(r'<form action="(http://fileshare.+?)"', webpage)
  55. if (mobj is None) or (mobj.group(1) is None):
  56. # Try to figure out reason of the error.
  57. mobj = re.search(r'<strong>(Attention.*?)</strong>', webpage, re.DOTALL)
  58. if (mobj is not None) and (mobj.group(1) is not None):
  59. restriction_message = re.sub('\s+', ' ', mobj.group(1)).strip()
  60. raise ExtractorError(u'%s' % restriction_message)
  61. else:
  62. raise ExtractorError(u'Unable to extract download URL from: %s' % url)
  63. file_url = mobj.group(1)
  64. file_extension = os.path.splitext(file_url)[1][1:]
  65. # Search for file title
  66. file_title = self._search_regex(r'<b title="(.*?)">', webpage, u'title')
  67. return [{
  68. 'id': file_id.decode('utf-8'),
  69. 'url': file_url.decode('utf-8'),
  70. 'uploader': None,
  71. 'upload_date': None,
  72. 'title': file_title,
  73. 'ext': file_extension.decode('utf-8'),
  74. }]
  75. class EscapistIE(InfoExtractor):
  76. """Information extractor for The Escapist """
  77. _VALID_URL = r'^(https?://)?(www\.)?escapistmagazine\.com/videos/view/(?P<showname>[^/]+)/(?P<episode>[^/?]+)[/?]?.*$'
  78. IE_NAME = u'escapist'
  79. def _real_extract(self, url):
  80. mobj = re.match(self._VALID_URL, url)
  81. if mobj is None:
  82. raise ExtractorError(u'Invalid URL: %s' % url)
  83. showName = mobj.group('showname')
  84. videoId = mobj.group('episode')
  85. self.report_extraction(videoId)
  86. webpage = self._download_webpage(url, videoId)
  87. videoDesc = self._html_search_regex('<meta name="description" content="([^"]*)"',
  88. webpage, u'description', fatal=False)
  89. imgUrl = self._html_search_regex('<meta property="og:image" content="([^"]*)"',
  90. webpage, u'thumbnail', fatal=False)
  91. playerUrl = self._html_search_regex('<meta property="og:video" content="([^"]*)"',
  92. webpage, u'player url')
  93. title = self._html_search_regex('<meta name="title" content="([^"]*)"',
  94. webpage, u'player url').split(' : ')[-1]
  95. configUrl = self._search_regex('config=(.*)$', playerUrl, u'config url')
  96. configUrl = compat_urllib_parse.unquote(configUrl)
  97. configJSON = self._download_webpage(configUrl, videoId,
  98. u'Downloading configuration',
  99. u'unable to download configuration')
  100. # Technically, it's JavaScript, not JSON
  101. configJSON = configJSON.replace("'", '"')
  102. try:
  103. config = json.loads(configJSON)
  104. except (ValueError,) as err:
  105. raise ExtractorError(u'Invalid JSON in configuration file: ' + compat_str(err))
  106. playlist = config['playlist']
  107. videoUrl = playlist[1]['url']
  108. info = {
  109. 'id': videoId,
  110. 'url': videoUrl,
  111. 'uploader': showName,
  112. 'upload_date': None,
  113. 'title': title,
  114. 'ext': 'mp4',
  115. 'thumbnail': imgUrl,
  116. 'description': videoDesc,
  117. 'player_url': playerUrl,
  118. }
  119. return [info]
  120. class CollegeHumorIE(InfoExtractor):
  121. """Information extractor for collegehumor.com"""
  122. _WORKING = False
  123. _VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/video/(?P<videoid>[0-9]+)/(?P<shorttitle>.*)$'
  124. IE_NAME = u'collegehumor'
  125. def report_manifest(self, video_id):
  126. """Report information extraction."""
  127. self.to_screen(u'%s: Downloading XML manifest' % video_id)
  128. def _real_extract(self, url):
  129. mobj = re.match(self._VALID_URL, url)
  130. if mobj is None:
  131. raise ExtractorError(u'Invalid URL: %s' % url)
  132. video_id = mobj.group('videoid')
  133. info = {
  134. 'id': video_id,
  135. 'uploader': None,
  136. 'upload_date': None,
  137. }
  138. self.report_extraction(video_id)
  139. xmlUrl = 'http://www.collegehumor.com/moogaloop/video/' + video_id
  140. try:
  141. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  142. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  143. raise ExtractorError(u'Unable to download video info XML: %s' % compat_str(err))
  144. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  145. try:
  146. videoNode = mdoc.findall('./video')[0]
  147. info['description'] = videoNode.findall('./description')[0].text
  148. info['title'] = videoNode.findall('./caption')[0].text
  149. info['thumbnail'] = videoNode.findall('./thumbnail')[0].text
  150. manifest_url = videoNode.findall('./file')[0].text
  151. except IndexError:
  152. raise ExtractorError(u'Invalid metadata XML file')
  153. manifest_url += '?hdcore=2.10.3'
  154. self.report_manifest(video_id)
  155. try:
  156. manifestXml = compat_urllib_request.urlopen(manifest_url).read()
  157. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  158. raise ExtractorError(u'Unable to download video info XML: %s' % compat_str(err))
  159. adoc = xml.etree.ElementTree.fromstring(manifestXml)
  160. try:
  161. media_node = adoc.findall('./{http://ns.adobe.com/f4m/1.0}media')[0]
  162. node_id = media_node.attrib['url']
  163. video_id = adoc.findall('./{http://ns.adobe.com/f4m/1.0}id')[0].text
  164. except IndexError as err:
  165. raise ExtractorError(u'Invalid manifest file')
  166. url_pr = compat_urllib_parse_urlparse(manifest_url)
  167. url = url_pr.scheme + '://' + url_pr.netloc + '/z' + video_id[:-2] + '/' + node_id + 'Seg1-Frag1'
  168. info['url'] = url
  169. info['ext'] = 'f4f'
  170. return [info]
  171. class XVideosIE(InfoExtractor):
  172. """Information extractor for xvideos.com"""
  173. _VALID_URL = r'^(?:https?://)?(?:www\.)?xvideos\.com/video([0-9]+)(?:.*)'
  174. IE_NAME = u'xvideos'
  175. def _real_extract(self, url):
  176. mobj = re.match(self._VALID_URL, url)
  177. if mobj is None:
  178. raise ExtractorError(u'Invalid URL: %s' % url)
  179. video_id = mobj.group(1)
  180. webpage = self._download_webpage(url, video_id)
  181. self.report_extraction(video_id)
  182. # Extract video URL
  183. video_url = compat_urllib_parse.unquote(self._search_regex(r'flv_url=(.+?)&',
  184. webpage, u'video URL'))
  185. # Extract title
  186. video_title = self._html_search_regex(r'<title>(.*?)\s+-\s+XVID',
  187. webpage, u'title')
  188. # Extract video thumbnail
  189. video_thumbnail = self._search_regex(r'http://(?:img.*?\.)xvideos.com/videos/thumbs/[a-fA-F0-9]+/[a-fA-F0-9]+/[a-fA-F0-9]+/[a-fA-F0-9]+/([a-fA-F0-9.]+jpg)',
  190. webpage, u'thumbnail', fatal=False)
  191. info = {
  192. 'id': video_id,
  193. 'url': video_url,
  194. 'uploader': None,
  195. 'upload_date': None,
  196. 'title': video_title,
  197. 'ext': 'flv',
  198. 'thumbnail': video_thumbnail,
  199. 'description': None,
  200. }
  201. return [info]
  202. class InfoQIE(InfoExtractor):
  203. """Information extractor for infoq.com"""
  204. _VALID_URL = r'^(?:https?://)?(?:www\.)?infoq\.com/[^/]+/[^/]+$'
  205. def _real_extract(self, url):
  206. mobj = re.match(self._VALID_URL, url)
  207. if mobj is None:
  208. raise ExtractorError(u'Invalid URL: %s' % url)
  209. webpage = self._download_webpage(url, video_id=url)
  210. self.report_extraction(url)
  211. # Extract video URL
  212. mobj = re.search(r"jsclassref ?= ?'([^']*)'", webpage)
  213. if mobj is None:
  214. raise ExtractorError(u'Unable to extract video url')
  215. real_id = compat_urllib_parse.unquote(base64.b64decode(mobj.group(1).encode('ascii')).decode('utf-8'))
  216. video_url = 'rtmpe://video.infoq.com/cfx/st/' + real_id
  217. # Extract title
  218. video_title = self._search_regex(r'contentTitle = "(.*?)";',
  219. webpage, u'title')
  220. # Extract description
  221. video_description = self._html_search_regex(r'<meta name="description" content="(.*)"(?:\s*/)?>',
  222. webpage, u'description', fatal=False)
  223. video_filename = video_url.split('/')[-1]
  224. video_id, extension = video_filename.split('.')
  225. info = {
  226. 'id': video_id,
  227. 'url': video_url,
  228. 'uploader': None,
  229. 'upload_date': None,
  230. 'title': video_title,
  231. 'ext': extension, # Extension is always(?) mp4, but seems to be flv
  232. 'thumbnail': None,
  233. 'description': video_description,
  234. }
  235. return [info]
  236. class MixcloudIE(InfoExtractor):
  237. """Information extractor for www.mixcloud.com"""
  238. _WORKING = False # New API, but it seems good http://www.mixcloud.com/developers/documentation/
  239. _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/([\w\d-]+)/([\w\d-]+)'
  240. IE_NAME = u'mixcloud'
  241. def report_download_json(self, file_id):
  242. """Report JSON download."""
  243. self.to_screen(u'Downloading json')
  244. def get_urls(self, jsonData, fmt, bitrate='best'):
  245. """Get urls from 'audio_formats' section in json"""
  246. file_url = None
  247. try:
  248. bitrate_list = jsonData[fmt]
  249. if bitrate is None or bitrate == 'best' or bitrate not in bitrate_list:
  250. bitrate = max(bitrate_list) # select highest
  251. url_list = jsonData[fmt][bitrate]
  252. except TypeError: # we have no bitrate info.
  253. url_list = jsonData[fmt]
  254. return url_list
  255. def check_urls(self, url_list):
  256. """Returns 1st active url from list"""
  257. for url in url_list:
  258. try:
  259. compat_urllib_request.urlopen(url)
  260. return url
  261. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  262. url = None
  263. return None
  264. def _print_formats(self, formats):
  265. print('Available formats:')
  266. for fmt in formats.keys():
  267. for b in formats[fmt]:
  268. try:
  269. ext = formats[fmt][b][0]
  270. print('%s\t%s\t[%s]' % (fmt, b, ext.split('.')[-1]))
  271. except TypeError: # we have no bitrate info
  272. ext = formats[fmt][0]
  273. print('%s\t%s\t[%s]' % (fmt, '??', ext.split('.')[-1]))
  274. break
  275. def _real_extract(self, url):
  276. mobj = re.match(self._VALID_URL, url)
  277. if mobj is None:
  278. raise ExtractorError(u'Invalid URL: %s' % url)
  279. # extract uploader & filename from url
  280. uploader = mobj.group(1).decode('utf-8')
  281. file_id = uploader + "-" + mobj.group(2).decode('utf-8')
  282. # construct API request
  283. file_url = 'http://www.mixcloud.com/api/1/cloudcast/' + '/'.join(url.split('/')[-3:-1]) + '.json'
  284. # retrieve .json file with links to files
  285. request = compat_urllib_request.Request(file_url)
  286. try:
  287. self.report_download_json(file_url)
  288. jsonData = compat_urllib_request.urlopen(request).read()
  289. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  290. raise ExtractorError(u'Unable to retrieve file: %s' % compat_str(err))
  291. # parse JSON
  292. json_data = json.loads(jsonData)
  293. player_url = json_data['player_swf_url']
  294. formats = dict(json_data['audio_formats'])
  295. req_format = self._downloader.params.get('format', None)
  296. bitrate = None
  297. if self._downloader.params.get('listformats', None):
  298. self._print_formats(formats)
  299. return
  300. if req_format is None or req_format == 'best':
  301. for format_param in formats.keys():
  302. url_list = self.get_urls(formats, format_param)
  303. # check urls
  304. file_url = self.check_urls(url_list)
  305. if file_url is not None:
  306. break # got it!
  307. else:
  308. if req_format not in formats:
  309. raise ExtractorError(u'Format is not available')
  310. url_list = self.get_urls(formats, req_format)
  311. file_url = self.check_urls(url_list)
  312. format_param = req_format
  313. return [{
  314. 'id': file_id.decode('utf-8'),
  315. 'url': file_url.decode('utf-8'),
  316. 'uploader': uploader.decode('utf-8'),
  317. 'upload_date': None,
  318. 'title': json_data['name'],
  319. 'ext': file_url.split('.')[-1].decode('utf-8'),
  320. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  321. 'thumbnail': json_data['thumbnail_url'],
  322. 'description': json_data['description'],
  323. 'player_url': player_url.decode('utf-8'),
  324. }]
  325. class StanfordOpenClassroomIE(InfoExtractor):
  326. """Information extractor for Stanford's Open ClassRoom"""
  327. _VALID_URL = r'^(?:https?://)?openclassroom.stanford.edu(?P<path>/?|(/MainFolder/(?:HomePage|CoursePage|VideoPage)\.php([?]course=(?P<course>[^&]+)(&video=(?P<video>[^&]+))?(&.*)?)?))$'
  328. IE_NAME = u'stanfordoc'
  329. def _real_extract(self, url):
  330. mobj = re.match(self._VALID_URL, url)
  331. if mobj is None:
  332. raise ExtractorError(u'Invalid URL: %s' % url)
  333. if mobj.group('course') and mobj.group('video'): # A specific video
  334. course = mobj.group('course')
  335. video = mobj.group('video')
  336. info = {
  337. 'id': course + '_' + video,
  338. 'uploader': None,
  339. 'upload_date': None,
  340. }
  341. self.report_extraction(info['id'])
  342. baseUrl = 'http://openclassroom.stanford.edu/MainFolder/courses/' + course + '/videos/'
  343. xmlUrl = baseUrl + video + '.xml'
  344. try:
  345. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  346. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  347. raise ExtractorError(u'Unable to download video info XML: %s' % compat_str(err))
  348. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  349. try:
  350. info['title'] = mdoc.findall('./title')[0].text
  351. info['url'] = baseUrl + mdoc.findall('./videoFile')[0].text
  352. except IndexError:
  353. raise ExtractorError(u'Invalid metadata XML file')
  354. info['ext'] = info['url'].rpartition('.')[2]
  355. return [info]
  356. elif mobj.group('course'): # A course page
  357. course = mobj.group('course')
  358. info = {
  359. 'id': course,
  360. 'type': 'playlist',
  361. 'uploader': None,
  362. 'upload_date': None,
  363. }
  364. coursepage = self._download_webpage(url, info['id'],
  365. note='Downloading course info page',
  366. errnote='Unable to download course info page')
  367. info['title'] = self._html_search_regex('<h1>([^<]+)</h1>', coursepage, 'title', default=info['id'])
  368. info['description'] = self._html_search_regex('<description>([^<]+)</description>',
  369. coursepage, u'description', fatal=False)
  370. links = orderedSet(re.findall('<a href="(VideoPage.php\?[^"]+)">', coursepage))
  371. info['list'] = [
  372. {
  373. 'type': 'reference',
  374. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(vpage),
  375. }
  376. for vpage in links]
  377. results = []
  378. for entry in info['list']:
  379. assert entry['type'] == 'reference'
  380. results += self.extract(entry['url'])
  381. return results
  382. else: # Root page
  383. info = {
  384. 'id': 'Stanford OpenClassroom',
  385. 'type': 'playlist',
  386. 'uploader': None,
  387. 'upload_date': None,
  388. }
  389. self.report_download_webpage(info['id'])
  390. rootURL = 'http://openclassroom.stanford.edu/MainFolder/HomePage.php'
  391. try:
  392. rootpage = compat_urllib_request.urlopen(rootURL).read()
  393. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  394. raise ExtractorError(u'Unable to download course info page: ' + compat_str(err))
  395. info['title'] = info['id']
  396. links = orderedSet(re.findall('<a href="(CoursePage.php\?[^"]+)">', rootpage))
  397. info['list'] = [
  398. {
  399. 'type': 'reference',
  400. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(cpage),
  401. }
  402. for cpage in links]
  403. results = []
  404. for entry in info['list']:
  405. assert entry['type'] == 'reference'
  406. results += self.extract(entry['url'])
  407. return results
  408. class MTVIE(InfoExtractor):
  409. """Information extractor for MTV.com"""
  410. _VALID_URL = r'^(?P<proto>https?://)?(?:www\.)?mtv\.com/videos/[^/]+/(?P<videoid>[0-9]+)/[^/]+$'
  411. IE_NAME = u'mtv'
  412. def _real_extract(self, url):
  413. mobj = re.match(self._VALID_URL, url)
  414. if mobj is None:
  415. raise ExtractorError(u'Invalid URL: %s' % url)
  416. if not mobj.group('proto'):
  417. url = 'http://' + url
  418. video_id = mobj.group('videoid')
  419. webpage = self._download_webpage(url, video_id)
  420. song_name = self._html_search_regex(r'<meta name="mtv_vt" content="([^"]+)"/>',
  421. webpage, u'song name', fatal=False)
  422. video_title = self._html_search_regex(r'<meta name="mtv_an" content="([^"]+)"/>',
  423. webpage, u'title')
  424. mtvn_uri = self._html_search_regex(r'<meta name="mtvn_uri" content="([^"]+)"/>',
  425. webpage, u'mtvn_uri', fatal=False)
  426. content_id = self._search_regex(r'MTVN.Player.defaultPlaylistId = ([0-9]+);',
  427. webpage, u'content id', fatal=False)
  428. videogen_url = 'http://www.mtv.com/player/includes/mediaGen.jhtml?uri=' + mtvn_uri + '&id=' + content_id + '&vid=' + video_id + '&ref=www.mtvn.com&viewUri=' + mtvn_uri
  429. self.report_extraction(video_id)
  430. request = compat_urllib_request.Request(videogen_url)
  431. try:
  432. metadataXml = compat_urllib_request.urlopen(request).read()
  433. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  434. raise ExtractorError(u'Unable to download video metadata: %s' % compat_str(err))
  435. mdoc = xml.etree.ElementTree.fromstring(metadataXml)
  436. renditions = mdoc.findall('.//rendition')
  437. # For now, always pick the highest quality.
  438. rendition = renditions[-1]
  439. try:
  440. _,_,ext = rendition.attrib['type'].partition('/')
  441. format = ext + '-' + rendition.attrib['width'] + 'x' + rendition.attrib['height'] + '_' + rendition.attrib['bitrate']
  442. video_url = rendition.find('./src').text
  443. except KeyError:
  444. raise ExtractorError('Invalid rendition field.')
  445. info = {
  446. 'id': video_id,
  447. 'url': video_url,
  448. 'uploader': performer,
  449. 'upload_date': None,
  450. 'title': video_title,
  451. 'ext': ext,
  452. 'format': format,
  453. }
  454. return [info]
  455. class YoukuIE(InfoExtractor):
  456. _VALID_URL = r'(?:http://)?v\.youku\.com/v_show/id_(?P<ID>[A-Za-z0-9]+)\.html'
  457. def _gen_sid(self):
  458. nowTime = int(time.time() * 1000)
  459. random1 = random.randint(1000,1998)
  460. random2 = random.randint(1000,9999)
  461. return "%d%d%d" %(nowTime,random1,random2)
  462. def _get_file_ID_mix_string(self, seed):
  463. mixed = []
  464. source = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\:._-1234567890")
  465. seed = float(seed)
  466. for i in range(len(source)):
  467. seed = (seed * 211 + 30031 ) % 65536
  468. index = math.floor(seed / 65536 * len(source) )
  469. mixed.append(source[int(index)])
  470. source.remove(source[int(index)])
  471. #return ''.join(mixed)
  472. return mixed
  473. def _get_file_id(self, fileId, seed):
  474. mixed = self._get_file_ID_mix_string(seed)
  475. ids = fileId.split('*')
  476. realId = []
  477. for ch in ids:
  478. if ch:
  479. realId.append(mixed[int(ch)])
  480. return ''.join(realId)
  481. def _real_extract(self, url):
  482. mobj = re.match(self._VALID_URL, url)
  483. if mobj is None:
  484. raise ExtractorError(u'Invalid URL: %s' % url)
  485. video_id = mobj.group('ID')
  486. info_url = 'http://v.youku.com/player/getPlayList/VideoIDS/' + video_id
  487. jsondata = self._download_webpage(info_url, video_id)
  488. self.report_extraction(video_id)
  489. try:
  490. config = json.loads(jsondata)
  491. video_title = config['data'][0]['title']
  492. seed = config['data'][0]['seed']
  493. format = self._downloader.params.get('format', None)
  494. supported_format = list(config['data'][0]['streamfileids'].keys())
  495. if format is None or format == 'best':
  496. if 'hd2' in supported_format:
  497. format = 'hd2'
  498. else:
  499. format = 'flv'
  500. ext = u'flv'
  501. elif format == 'worst':
  502. format = 'mp4'
  503. ext = u'mp4'
  504. else:
  505. format = 'flv'
  506. ext = u'flv'
  507. fileid = config['data'][0]['streamfileids'][format]
  508. keys = [s['k'] for s in config['data'][0]['segs'][format]]
  509. except (UnicodeDecodeError, ValueError, KeyError):
  510. raise ExtractorError(u'Unable to extract info section')
  511. files_info=[]
  512. sid = self._gen_sid()
  513. fileid = self._get_file_id(fileid, seed)
  514. #column 8,9 of fileid represent the segment number
  515. #fileid[7:9] should be changed
  516. for index, key in enumerate(keys):
  517. temp_fileid = '%s%02X%s' % (fileid[0:8], index, fileid[10:])
  518. download_url = 'http://f.youku.com/player/getFlvPath/sid/%s_%02X/st/flv/fileid/%s?k=%s' % (sid, index, temp_fileid, key)
  519. info = {
  520. 'id': '%s_part%02d' % (video_id, index),
  521. 'url': download_url,
  522. 'uploader': None,
  523. 'upload_date': None,
  524. 'title': video_title,
  525. 'ext': ext,
  526. }
  527. files_info.append(info)
  528. return files_info
  529. class XNXXIE(InfoExtractor):
  530. """Information extractor for xnxx.com"""
  531. _VALID_URL = r'^(?:https?://)?video\.xnxx\.com/video([0-9]+)/(.*)'
  532. IE_NAME = u'xnxx'
  533. VIDEO_URL_RE = r'flv_url=(.*?)&amp;'
  534. VIDEO_TITLE_RE = r'<title>(.*?)\s+-\s+XNXX.COM'
  535. VIDEO_THUMB_RE = r'url_bigthumb=(.*?)&amp;'
  536. def _real_extract(self, url):
  537. mobj = re.match(self._VALID_URL, url)
  538. if mobj is None:
  539. raise ExtractorError(u'Invalid URL: %s' % url)
  540. video_id = mobj.group(1)
  541. # Get webpage content
  542. webpage = self._download_webpage(url, video_id)
  543. video_url = self._search_regex(self.VIDEO_URL_RE,
  544. webpage, u'video URL')
  545. video_url = compat_urllib_parse.unquote(video_url)
  546. video_title = self._html_search_regex(self.VIDEO_TITLE_RE,
  547. webpage, u'title')
  548. video_thumbnail = self._search_regex(self.VIDEO_THUMB_RE,
  549. webpage, u'thumbnail', fatal=False)
  550. return [{
  551. 'id': video_id,
  552. 'url': video_url,
  553. 'uploader': None,
  554. 'upload_date': None,
  555. 'title': video_title,
  556. 'ext': 'flv',
  557. 'thumbnail': video_thumbnail,
  558. 'description': None,
  559. }]
  560. class NBAIE(InfoExtractor):
  561. _VALID_URL = r'^(?:https?://)?(?:watch\.|www\.)?nba\.com/(?:nba/)?video(/[^?]*?)(?:/index\.html)?(?:\?.*)?$'
  562. IE_NAME = u'nba'
  563. def _real_extract(self, url):
  564. mobj = re.match(self._VALID_URL, url)
  565. if mobj is None:
  566. raise ExtractorError(u'Invalid URL: %s' % url)
  567. video_id = mobj.group(1)
  568. webpage = self._download_webpage(url, video_id)
  569. video_url = u'http://ht-mobile.cdn.turner.com/nba/big' + video_id + '_nba_1280x720.mp4'
  570. shortened_video_id = video_id.rpartition('/')[2]
  571. title = self._html_search_regex(r'<meta property="og:title" content="(.*?)"',
  572. webpage, 'title', default=shortened_video_id).replace('NBA.com: ', '')
  573. # It isn't there in the HTML it returns to us
  574. # uploader_date = self._html_search_regex(r'<b>Date:</b> (.*?)</div>', webpage, 'upload_date', fatal=False)
  575. description = self._html_search_regex(r'<meta name="description" (?:content|value)="(.*?)" />', webpage, 'description', fatal=False)
  576. info = {
  577. 'id': shortened_video_id,
  578. 'url': video_url,
  579. 'ext': 'mp4',
  580. 'title': title,
  581. # 'uploader_date': uploader_date,
  582. 'description': description,
  583. }
  584. return [info]
  585. class JustinTVIE(InfoExtractor):
  586. """Information extractor for justin.tv and twitch.tv"""
  587. # TODO: One broadcast may be split into multiple videos. The key
  588. # 'broadcast_id' is the same for all parts, and 'broadcast_part'
  589. # starts at 1 and increases. Can we treat all parts as one video?
  590. _VALID_URL = r"""(?x)^(?:http://)?(?:www\.)?(?:twitch|justin)\.tv/
  591. (?:
  592. (?P<channelid>[^/]+)|
  593. (?:(?:[^/]+)/b/(?P<videoid>[^/]+))|
  594. (?:(?:[^/]+)/c/(?P<chapterid>[^/]+))
  595. )
  596. /?(?:\#.*)?$
  597. """
  598. _JUSTIN_PAGE_LIMIT = 100
  599. IE_NAME = u'justin.tv'
  600. def report_download_page(self, channel, offset):
  601. """Report attempt to download a single page of videos."""
  602. self.to_screen(u'%s: Downloading video information from %d to %d' %
  603. (channel, offset, offset + self._JUSTIN_PAGE_LIMIT))
  604. # Return count of items, list of *valid* items
  605. def _parse_page(self, url, video_id):
  606. webpage = self._download_webpage(url, video_id,
  607. u'Downloading video info JSON',
  608. u'unable to download video info JSON')
  609. response = json.loads(webpage)
  610. if type(response) != list:
  611. error_text = response.get('error', 'unknown error')
  612. raise ExtractorError(u'Justin.tv API: %s' % error_text)
  613. info = []
  614. for clip in response:
  615. video_url = clip['video_file_url']
  616. if video_url:
  617. video_extension = os.path.splitext(video_url)[1][1:]
  618. video_date = re.sub('-', '', clip['start_time'][:10])
  619. video_uploader_id = clip.get('user_id', clip.get('channel_id'))
  620. video_id = clip['id']
  621. video_title = clip.get('title', video_id)
  622. info.append({
  623. 'id': video_id,
  624. 'url': video_url,
  625. 'title': video_title,
  626. 'uploader': clip.get('channel_name', video_uploader_id),
  627. 'uploader_id': video_uploader_id,
  628. 'upload_date': video_date,
  629. 'ext': video_extension,
  630. })
  631. return (len(response), info)
  632. def _real_extract(self, url):
  633. mobj = re.match(self._VALID_URL, url)
  634. if mobj is None:
  635. raise ExtractorError(u'invalid URL: %s' % url)
  636. api_base = 'http://api.justin.tv'
  637. paged = False
  638. if mobj.group('channelid'):
  639. paged = True
  640. video_id = mobj.group('channelid')
  641. api = api_base + '/channel/archives/%s.json' % video_id
  642. elif mobj.group('chapterid'):
  643. chapter_id = mobj.group('chapterid')
  644. webpage = self._download_webpage(url, chapter_id)
  645. m = re.search(r'PP\.archive_id = "([0-9]+)";', webpage)
  646. if not m:
  647. raise ExtractorError(u'Cannot find archive of a chapter')
  648. archive_id = m.group(1)
  649. api = api_base + '/broadcast/by_chapter/%s.xml' % chapter_id
  650. chapter_info_xml = self._download_webpage(api, chapter_id,
  651. note=u'Downloading chapter information',
  652. errnote=u'Chapter information download failed')
  653. doc = xml.etree.ElementTree.fromstring(chapter_info_xml)
  654. for a in doc.findall('.//archive'):
  655. if archive_id == a.find('./id').text:
  656. break
  657. else:
  658. raise ExtractorError(u'Could not find chapter in chapter information')
  659. video_url = a.find('./video_file_url').text
  660. video_ext = video_url.rpartition('.')[2] or u'flv'
  661. chapter_api_url = u'https://api.twitch.tv/kraken/videos/c' + chapter_id
  662. chapter_info_json = self._download_webpage(chapter_api_url, u'c' + chapter_id,
  663. note='Downloading chapter metadata',
  664. errnote='Download of chapter metadata failed')
  665. chapter_info = json.loads(chapter_info_json)
  666. bracket_start = int(doc.find('.//bracket_start').text)
  667. bracket_end = int(doc.find('.//bracket_end').text)
  668. # TODO determine start (and probably fix up file)
  669. # youtube-dl -v http://www.twitch.tv/firmbelief/c/1757457
  670. #video_url += u'?start=' + TODO:start_timestamp
  671. # bracket_start is 13290, but we want 51670615
  672. self._downloader.report_warning(u'Chapter detected, but we can just download the whole file. '
  673. u'Chapter starts at %s and ends at %s' % (formatSeconds(bracket_start), formatSeconds(bracket_end)))
  674. info = {
  675. 'id': u'c' + chapter_id,
  676. 'url': video_url,
  677. 'ext': video_ext,
  678. 'title': chapter_info['title'],
  679. 'thumbnail': chapter_info['preview'],
  680. 'description': chapter_info['description'],
  681. 'uploader': chapter_info['channel']['display_name'],
  682. 'uploader_id': chapter_info['channel']['name'],
  683. }
  684. return [info]
  685. else:
  686. video_id = mobj.group('videoid')
  687. api = api_base + '/broadcast/by_archive/%s.json' % video_id
  688. self.report_extraction(video_id)
  689. info = []
  690. offset = 0
  691. limit = self._JUSTIN_PAGE_LIMIT
  692. while True:
  693. if paged:
  694. self.report_download_page(video_id, offset)
  695. page_url = api + ('?offset=%d&limit=%d' % (offset, limit))
  696. page_count, page_info = self._parse_page(page_url, video_id)
  697. info.extend(page_info)
  698. if not paged or page_count != limit:
  699. break
  700. offset += limit
  701. return info
  702. class FunnyOrDieIE(InfoExtractor):
  703. _VALID_URL = r'^(?:https?://)?(?:www\.)?funnyordie\.com/videos/(?P<id>[0-9a-f]+)/.*$'
  704. def _real_extract(self, url):
  705. mobj = re.match(self._VALID_URL, url)
  706. if mobj is None:
  707. raise ExtractorError(u'invalid URL: %s' % url)
  708. video_id = mobj.group('id')
  709. webpage = self._download_webpage(url, video_id)
  710. video_url = self._html_search_regex(r'<video[^>]*>\s*<source[^>]*>\s*<source src="(?P<url>[^"]+)"',
  711. webpage, u'video URL', flags=re.DOTALL)
  712. title = self._html_search_regex((r"<h1 class='player_page_h1'.*?>(?P<title>.*?)</h1>",
  713. r'<title>(?P<title>[^<]+?)</title>'), webpage, 'title', flags=re.DOTALL)
  714. video_description = self._html_search_regex(r'<meta property="og:description" content="(?P<desc>.*?)"',
  715. webpage, u'description', fatal=False, flags=re.DOTALL)
  716. info = {
  717. 'id': video_id,
  718. 'url': video_url,
  719. 'ext': 'mp4',
  720. 'title': title,
  721. 'description': video_description,
  722. }
  723. return [info]
  724. class SteamIE(InfoExtractor):
  725. _VALID_URL = r"""http://store\.steampowered\.com/
  726. (agecheck/)?
  727. (?P<urltype>video|app)/ #If the page is only for videos or for a game
  728. (?P<gameID>\d+)/?
  729. (?P<videoID>\d*)(?P<extra>\??) #For urltype == video we sometimes get the videoID
  730. """
  731. _VIDEO_PAGE_TEMPLATE = 'http://store.steampowered.com/video/%s/'
  732. _AGECHECK_TEMPLATE = 'http://store.steampowered.com/agecheck/video/%s/?snr=1_agecheck_agecheck__age-gate&ageDay=1&ageMonth=January&ageYear=1970'
  733. @classmethod
  734. def suitable(cls, url):
  735. """Receives a URL and returns True if suitable for this IE."""
  736. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  737. def _real_extract(self, url):
  738. m = re.match(self._VALID_URL, url, re.VERBOSE)
  739. gameID = m.group('gameID')
  740. videourl = self._VIDEO_PAGE_TEMPLATE % gameID
  741. webpage = self._download_webpage(videourl, gameID)
  742. if re.search('<h2>Please enter your birth date to continue:</h2>', webpage) is not None:
  743. videourl = self._AGECHECK_TEMPLATE % gameID
  744. self.report_age_confirmation()
  745. webpage = self._download_webpage(videourl, gameID)
  746. self.report_extraction(gameID)
  747. game_title = self._html_search_regex(r'<h2 class="pageheader">(.*?)</h2>',
  748. webpage, 'game title')
  749. urlRE = r"'movie_(?P<videoID>\d+)': \{\s*FILENAME: \"(?P<videoURL>[\w:/\.\?=]+)\"(,\s*MOVIE_NAME: \"(?P<videoName>[\w:/\.\?=\+-]+)\")?\s*\},"
  750. mweb = re.finditer(urlRE, webpage)
  751. namesRE = r'<span class="title">(?P<videoName>.+?)</span>'
  752. titles = re.finditer(namesRE, webpage)
  753. thumbsRE = r'<img class="movie_thumb" src="(?P<thumbnail>.+?)">'
  754. thumbs = re.finditer(thumbsRE, webpage)
  755. videos = []
  756. for vid,vtitle,thumb in zip(mweb,titles,thumbs):
  757. video_id = vid.group('videoID')
  758. title = vtitle.group('videoName')
  759. video_url = vid.group('videoURL')
  760. video_thumb = thumb.group('thumbnail')
  761. if not video_url:
  762. raise ExtractorError(u'Cannot find video url for %s' % video_id)
  763. info = {
  764. 'id':video_id,
  765. 'url':video_url,
  766. 'ext': 'flv',
  767. 'title': unescapeHTML(title),
  768. 'thumbnail': video_thumb
  769. }
  770. videos.append(info)
  771. return [self.playlist_result(videos, gameID, game_title)]
  772. class UstreamIE(InfoExtractor):
  773. _VALID_URL = r'https?://www\.ustream\.tv/recorded/(?P<videoID>\d+)'
  774. IE_NAME = u'ustream'
  775. def _real_extract(self, url):
  776. m = re.match(self._VALID_URL, url)
  777. video_id = m.group('videoID')
  778. video_url = u'http://tcdn.ustream.tv/video/%s' % video_id
  779. webpage = self._download_webpage(url, video_id)
  780. self.report_extraction(video_id)
  781. video_title = self._html_search_regex(r'data-title="(?P<title>.+)"',
  782. webpage, u'title')
  783. uploader = self._html_search_regex(r'data-content-type="channel".*?>(?P<uploader>.*?)</a>',
  784. webpage, u'uploader', fatal=False, flags=re.DOTALL)
  785. thumbnail = self._html_search_regex(r'<link rel="image_src" href="(?P<thumb>.*?)"',
  786. webpage, u'thumbnail', fatal=False)
  787. info = {
  788. 'id': video_id,
  789. 'url': video_url,
  790. 'ext': 'flv',
  791. 'title': video_title,
  792. 'uploader': uploader,
  793. 'thumbnail': thumbnail,
  794. }
  795. return info
  796. class WorldStarHipHopIE(InfoExtractor):
  797. _VALID_URL = r'https?://(?:www|m)\.worldstar(?:candy|hiphop)\.com/videos/video\.php\?v=(?P<id>.*)'
  798. IE_NAME = u'WorldStarHipHop'
  799. def _real_extract(self, url):
  800. m = re.match(self._VALID_URL, url)
  801. video_id = m.group('id')
  802. webpage_src = self._download_webpage(url, video_id)
  803. video_url = self._search_regex(r'so\.addVariable\("file","(.*?)"\)',
  804. webpage_src, u'video URL')
  805. if 'mp4' in video_url:
  806. ext = 'mp4'
  807. else:
  808. ext = 'flv'
  809. video_title = self._html_search_regex(r"<title>(.*)</title>",
  810. webpage_src, u'title')
  811. # Getting thumbnail and if not thumbnail sets correct title for WSHH candy video.
  812. thumbnail = self._html_search_regex(r'rel="image_src" href="(.*)" />',
  813. webpage_src, u'thumbnail', fatal=False)
  814. if not thumbnail:
  815. _title = r"""candytitles.*>(.*)</span>"""
  816. mobj = re.search(_title, webpage_src)
  817. if mobj is not None:
  818. video_title = mobj.group(1)
  819. results = [{
  820. 'id': video_id,
  821. 'url' : video_url,
  822. 'title' : video_title,
  823. 'thumbnail' : thumbnail,
  824. 'ext' : ext,
  825. }]
  826. return results
  827. class RBMARadioIE(InfoExtractor):
  828. _VALID_URL = r'https?://(?:www\.)?rbmaradio\.com/shows/(?P<videoID>[^/]+)$'
  829. def _real_extract(self, url):
  830. m = re.match(self._VALID_URL, url)
  831. video_id = m.group('videoID')
  832. webpage = self._download_webpage(url, video_id)
  833. json_data = self._search_regex(r'window\.gon.*?gon\.show=(.+?);$',
  834. webpage, u'json data', flags=re.MULTILINE)
  835. try:
  836. data = json.loads(json_data)
  837. except ValueError as e:
  838. raise ExtractorError(u'Invalid JSON: ' + str(e))
  839. video_url = data['akamai_url'] + '&cbr=256'
  840. url_parts = compat_urllib_parse_urlparse(video_url)
  841. video_ext = url_parts.path.rpartition('.')[2]
  842. info = {
  843. 'id': video_id,
  844. 'url': video_url,
  845. 'ext': video_ext,
  846. 'title': data['title'],
  847. 'description': data.get('teaser_text'),
  848. 'location': data.get('country_of_origin'),
  849. 'uploader': data.get('host', {}).get('name'),
  850. 'uploader_id': data.get('host', {}).get('slug'),
  851. 'thumbnail': data.get('image', {}).get('large_url_2x'),
  852. 'duration': data.get('duration'),
  853. }
  854. return [info]
  855. class YouPornIE(InfoExtractor):
  856. """Information extractor for youporn.com."""
  857. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youporn\.com/watch/(?P<videoid>[0-9]+)/(?P<title>[^/]+)'
  858. def _print_formats(self, formats):
  859. """Print all available formats"""
  860. print(u'Available formats:')
  861. print(u'ext\t\tformat')
  862. print(u'---------------------------------')
  863. for format in formats:
  864. print(u'%s\t\t%s' % (format['ext'], format['format']))
  865. def _specific(self, req_format, formats):
  866. for x in formats:
  867. if(x["format"]==req_format):
  868. return x
  869. return None
  870. def _real_extract(self, url):
  871. mobj = re.match(self._VALID_URL, url)
  872. if mobj is None:
  873. raise ExtractorError(u'Invalid URL: %s' % url)
  874. video_id = mobj.group('videoid')
  875. req = compat_urllib_request.Request(url)
  876. req.add_header('Cookie', 'age_verified=1')
  877. webpage = self._download_webpage(req, video_id)
  878. # Get JSON parameters
  879. json_params = self._search_regex(r'var currentVideo = new Video\((.*)\);', webpage, u'JSON parameters')
  880. try:
  881. params = json.loads(json_params)
  882. except:
  883. raise ExtractorError(u'Invalid JSON')
  884. self.report_extraction(video_id)
  885. try:
  886. video_title = params['title']
  887. upload_date = unified_strdate(params['release_date_f'])
  888. video_description = params['description']
  889. video_uploader = params['submitted_by']
  890. thumbnail = params['thumbnails'][0]['image']
  891. except KeyError:
  892. raise ExtractorError('Missing JSON parameter: ' + sys.exc_info()[1])
  893. # Get all of the formats available
  894. DOWNLOAD_LIST_RE = r'(?s)<ul class="downloadList">(?P<download_list>.*?)</ul>'
  895. download_list_html = self._search_regex(DOWNLOAD_LIST_RE,
  896. webpage, u'download list').strip()
  897. # Get all of the links from the page
  898. LINK_RE = r'(?s)<a href="(?P<url>[^"]+)">'
  899. links = re.findall(LINK_RE, download_list_html)
  900. if(len(links) == 0):
  901. raise ExtractorError(u'ERROR: no known formats available for video')
  902. self.to_screen(u'Links found: %d' % len(links))
  903. formats = []
  904. for link in links:
  905. # A link looks like this:
  906. # http://cdn1.download.youporn.phncdn.com/201210/31/8004515/480p_370k_8004515/YouPorn%20-%20Nubile%20Films%20The%20Pillow%20Fight.mp4?nvb=20121113051249&nva=20121114051249&ir=1200&sr=1200&hash=014b882080310e95fb6a0
  907. # A path looks like this:
  908. # /201210/31/8004515/480p_370k_8004515/YouPorn%20-%20Nubile%20Films%20The%20Pillow%20Fight.mp4
  909. video_url = unescapeHTML( link )
  910. path = compat_urllib_parse_urlparse( video_url ).path
  911. extension = os.path.splitext( path )[1][1:]
  912. format = path.split('/')[4].split('_')[:2]
  913. size = format[0]
  914. bitrate = format[1]
  915. format = "-".join( format )
  916. # title = u'%s-%s-%s' % (video_title, size, bitrate)
  917. formats.append({
  918. 'id': video_id,
  919. 'url': video_url,
  920. 'uploader': video_uploader,
  921. 'upload_date': upload_date,
  922. 'title': video_title,
  923. 'ext': extension,
  924. 'format': format,
  925. 'thumbnail': thumbnail,
  926. 'description': video_description
  927. })
  928. if self._downloader.params.get('listformats', None):
  929. self._print_formats(formats)
  930. return
  931. req_format = self._downloader.params.get('format', None)
  932. self.to_screen(u'Format: %s' % req_format)
  933. if req_format is None or req_format == 'best':
  934. return [formats[0]]
  935. elif req_format == 'worst':
  936. return [formats[-1]]
  937. elif req_format in ('-1', 'all'):
  938. return formats
  939. else:
  940. format = self._specific( req_format, formats )
  941. if result is None:
  942. raise ExtractorError(u'Requested format not available')
  943. return [format]
  944. class PornotubeIE(InfoExtractor):
  945. """Information extractor for pornotube.com."""
  946. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?pornotube\.com(/c/(?P<channel>[0-9]+))?(/m/(?P<videoid>[0-9]+))(/(?P<title>.+))$'
  947. def _real_extract(self, url):
  948. mobj = re.match(self._VALID_URL, url)
  949. if mobj is None:
  950. raise ExtractorError(u'Invalid URL: %s' % url)
  951. video_id = mobj.group('videoid')
  952. video_title = mobj.group('title')
  953. # Get webpage content
  954. webpage = self._download_webpage(url, video_id)
  955. # Get the video URL
  956. VIDEO_URL_RE = r'url: "(?P<url>http://video[0-9].pornotube.com/.+\.flv)",'
  957. video_url = self._search_regex(VIDEO_URL_RE, webpage, u'video url')
  958. video_url = compat_urllib_parse.unquote(video_url)
  959. #Get the uploaded date
  960. VIDEO_UPLOADED_RE = r'<div class="video_added_by">Added (?P<date>[0-9\/]+) by'
  961. upload_date = self._html_search_regex(VIDEO_UPLOADED_RE, webpage, u'upload date', fatal=False)
  962. if upload_date: upload_date = unified_strdate(upload_date)
  963. info = {'id': video_id,
  964. 'url': video_url,
  965. 'uploader': None,
  966. 'upload_date': upload_date,
  967. 'title': video_title,
  968. 'ext': 'flv',
  969. 'format': 'flv'}
  970. return [info]
  971. class YouJizzIE(InfoExtractor):
  972. """Information extractor for youjizz.com."""
  973. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youjizz\.com/videos/(?P<videoid>[^.]+).html$'
  974. def _real_extract(self, url):
  975. mobj = re.match(self._VALID_URL, url)
  976. if mobj is None:
  977. raise ExtractorError(u'Invalid URL: %s' % url)
  978. video_id = mobj.group('videoid')
  979. # Get webpage content
  980. webpage = self._download_webpage(url, video_id)
  981. # Get the video title
  982. video_title = self._html_search_regex(r'<title>(?P<title>.*)</title>',
  983. webpage, u'title').strip()
  984. # Get the embed page
  985. result = re.search(r'https?://www.youjizz.com/videos/embed/(?P<videoid>[0-9]+)', webpage)
  986. if result is None:
  987. raise ExtractorError(u'ERROR: unable to extract embed page')
  988. embed_page_url = result.group(0).strip()
  989. video_id = result.group('videoid')
  990. webpage = self._download_webpage(embed_page_url, video_id)
  991. # Get the video URL
  992. video_url = self._search_regex(r'so.addVariable\("file",encodeURIComponent\("(?P<source>[^"]+)"\)\);',
  993. webpage, u'video URL')
  994. info = {'id': video_id,
  995. 'url': video_url,
  996. 'title': video_title,
  997. 'ext': 'flv',
  998. 'format': 'flv',
  999. 'player_url': embed_page_url}
  1000. return [info]
  1001. class EightTracksIE(InfoExtractor):
  1002. IE_NAME = '8tracks'
  1003. _VALID_URL = r'https?://8tracks.com/(?P<user>[^/]+)/(?P<id>[^/#]+)(?:#.*)?$'
  1004. def _real_extract(self, url):
  1005. mobj = re.match(self._VALID_URL, url)
  1006. if mobj is None:
  1007. raise ExtractorError(u'Invalid URL: %s' % url)
  1008. playlist_id = mobj.group('id')
  1009. webpage = self._download_webpage(url, playlist_id)
  1010. json_like = self._search_regex(r"PAGE.mix = (.*?);\n", webpage, u'trax information', flags=re.DOTALL)
  1011. data = json.loads(json_like)
  1012. session = str(random.randint(0, 1000000000))
  1013. mix_id = data['id']
  1014. track_count = data['tracks_count']
  1015. first_url = 'http://8tracks.com/sets/%s/play?player=sm&mix_id=%s&format=jsonh' % (session, mix_id)
  1016. next_url = first_url
  1017. res = []
  1018. for i in itertools.count():
  1019. api_json = self._download_webpage(next_url, playlist_id,
  1020. note=u'Downloading song information %s/%s' % (str(i+1), track_count),
  1021. errnote=u'Failed to download song information')
  1022. api_data = json.loads(api_json)
  1023. track_data = api_data[u'set']['track']
  1024. info = {
  1025. 'id': track_data['id'],
  1026. 'url': track_data['track_file_stream_url'],
  1027. 'title': track_data['performer'] + u' - ' + track_data['name'],
  1028. 'raw_title': track_data['name'],
  1029. 'uploader_id': data['user']['login'],
  1030. 'ext': 'm4a',
  1031. }
  1032. res.append(info)
  1033. if api_data['set']['at_last_track']:
  1034. break
  1035. next_url = 'http://8tracks.com/sets/%s/next?player=sm&mix_id=%s&format=jsonh&track_id=%s' % (session, mix_id, track_data['id'])
  1036. return res
  1037. class KeekIE(InfoExtractor):
  1038. _VALID_URL = r'http://(?:www\.)?keek\.com/(?:!|\w+/keeks/)(?P<videoID>\w+)'
  1039. IE_NAME = u'keek'
  1040. def _real_extract(self, url):
  1041. m = re.match(self._VALID_URL, url)
  1042. video_id = m.group('videoID')
  1043. video_url = u'http://cdn.keek.com/keek/video/%s' % video_id
  1044. thumbnail = u'http://cdn.keek.com/keek/thumbnail/%s/w100/h75' % video_id
  1045. webpage = self._download_webpage(url, video_id)
  1046. video_title = self._html_search_regex(r'<meta property="og:title" content="(?P<title>.*?)"',
  1047. webpage, u'title')
  1048. uploader = self._html_search_regex(r'<div class="user-name-and-bio">[\S\s]+?<h2>(?P<uploader>.+?)</h2>',
  1049. webpage, u'uploader', fatal=False)
  1050. info = {
  1051. 'id': video_id,
  1052. 'url': video_url,
  1053. 'ext': 'mp4',
  1054. 'title': video_title,
  1055. 'thumbnail': thumbnail,
  1056. 'uploader': uploader
  1057. }
  1058. return [info]
  1059. class TEDIE(InfoExtractor):
  1060. _VALID_URL=r'''http://www\.ted\.com/
  1061. (
  1062. ((?P<type_playlist>playlists)/(?P<playlist_id>\d+)) # We have a playlist
  1063. |
  1064. ((?P<type_talk>talks)) # We have a simple talk
  1065. )
  1066. (/lang/(.*?))? # The url may contain the language
  1067. /(?P<name>\w+) # Here goes the name and then ".html"
  1068. '''
  1069. @classmethod
  1070. def suitable(cls, url):
  1071. """Receives a URL and returns True if suitable for this IE."""
  1072. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1073. def _real_extract(self, url):
  1074. m=re.match(self._VALID_URL, url, re.VERBOSE)
  1075. if m.group('type_talk'):
  1076. return [self._talk_info(url)]
  1077. else :
  1078. playlist_id=m.group('playlist_id')
  1079. name=m.group('name')
  1080. self.to_screen(u'Getting info of playlist %s: "%s"' % (playlist_id,name))
  1081. return [self._playlist_videos_info(url,name,playlist_id)]
  1082. def _playlist_videos_info(self,url,name,playlist_id=0):
  1083. '''Returns the videos of the playlist'''
  1084. video_RE=r'''
  1085. <li\ id="talk_(\d+)"([.\s]*?)data-id="(?P<video_id>\d+)"
  1086. ([.\s]*?)data-playlist_item_id="(\d+)"
  1087. ([.\s]*?)data-mediaslug="(?P<mediaSlug>.+?)"
  1088. '''
  1089. video_name_RE=r'<p\ class="talk-title"><a href="(?P<talk_url>/talks/(.+).html)">(?P<fullname>.+?)</a></p>'
  1090. webpage=self._download_webpage(url, playlist_id, 'Downloading playlist webpage')
  1091. m_videos=re.finditer(video_RE,webpage,re.VERBOSE)
  1092. m_names=re.finditer(video_name_RE,webpage)
  1093. playlist_title = self._html_search_regex(r'div class="headline">\s*?<h1>\s*?<span>(.*?)</span>',
  1094. webpage, 'playlist title')
  1095. playlist_entries = []
  1096. for m_video, m_name in zip(m_videos,m_names):
  1097. video_id=m_video.group('video_id')
  1098. talk_url='http://www.ted.com%s' % m_name.group('talk_url')
  1099. playlist_entries.append(self.url_result(talk_url, 'TED'))
  1100. return self.playlist_result(playlist_entries, playlist_id = playlist_id, playlist_title = playlist_title)
  1101. def _talk_info(self, url, video_id=0):
  1102. """Return the video for the talk in the url"""
  1103. m = re.match(self._VALID_URL, url,re.VERBOSE)
  1104. video_name = m.group('name')
  1105. webpage = self._download_webpage(url, video_id, 'Downloading \"%s\" page' % video_name)
  1106. self.report_extraction(video_name)
  1107. # If the url includes the language we get the title translated
  1108. title = self._html_search_regex(r'<span id="altHeadline" >(?P<title>.*)</span>',
  1109. webpage, 'title')
  1110. json_data = self._search_regex(r'<script.*?>var talkDetails = ({.*?})</script>',
  1111. webpage, 'json data')
  1112. info = json.loads(json_data)
  1113. desc = self._html_search_regex(r'<div class="talk-intro">.*?<p.*?>(.*?)</p>',
  1114. webpage, 'description', flags = re.DOTALL)
  1115. thumbnail = self._search_regex(r'</span>[\s.]*</div>[\s.]*<img src="(.*?)"',
  1116. webpage, 'thumbnail')
  1117. info = {
  1118. 'id': info['id'],
  1119. 'url': info['htmlStreams'][-1]['file'],
  1120. 'ext': 'mp4',
  1121. 'title': title,
  1122. 'thumbnail': thumbnail,
  1123. 'description': desc,
  1124. }
  1125. return info
  1126. class MySpassIE(InfoExtractor):
  1127. _VALID_URL = r'http://www.myspass.de/.*'
  1128. def _real_extract(self, url):
  1129. META_DATA_URL_TEMPLATE = 'http://www.myspass.de/myspass/includes/apps/video/getvideometadataxml.php?id=%s'
  1130. # video id is the last path element of the URL
  1131. # usually there is a trailing slash, so also try the second but last
  1132. url_path = compat_urllib_parse_urlparse(url).path
  1133. url_parent_path, video_id = os.path.split(url_path)
  1134. if not video_id:
  1135. _, video_id = os.path.split(url_parent_path)
  1136. # get metadata
  1137. metadata_url = META_DATA_URL_TEMPLATE % video_id
  1138. metadata_text = self._download_webpage(metadata_url, video_id)
  1139. metadata = xml.etree.ElementTree.fromstring(metadata_text.encode('utf-8'))
  1140. # extract values from metadata
  1141. url_flv_el = metadata.find('url_flv')
  1142. if url_flv_el is None:
  1143. raise ExtractorError(u'Unable to extract download url')
  1144. video_url = url_flv_el.text
  1145. extension = os.path.splitext(video_url)[1][1:]
  1146. title_el = metadata.find('title')
  1147. if title_el is None:
  1148. raise ExtractorError(u'Unable to extract title')
  1149. title = title_el.text
  1150. format_id_el = metadata.find('format_id')
  1151. if format_id_el is None:
  1152. format = ext
  1153. else:
  1154. format = format_id_el.text
  1155. description_el = metadata.find('description')
  1156. if description_el is not None:
  1157. description = description_el.text
  1158. else:
  1159. description = None
  1160. imagePreview_el = metadata.find('imagePreview')
  1161. if imagePreview_el is not None:
  1162. thumbnail = imagePreview_el.text
  1163. else:
  1164. thumbnail = None
  1165. info = {
  1166. 'id': video_id,
  1167. 'url': video_url,
  1168. 'title': title,
  1169. 'ext': extension,
  1170. 'format': format,
  1171. 'thumbnail': thumbnail,
  1172. 'description': description
  1173. }
  1174. return [info]
  1175. class SpiegelIE(InfoExtractor):
  1176. _VALID_URL = r'https?://(?:www\.)?spiegel\.de/video/[^/]*-(?P<videoID>[0-9]+)(?:\.html)?(?:#.*)?$'
  1177. def _real_extract(self, url):
  1178. m = re.match(self._VALID_URL, url)
  1179. video_id = m.group('videoID')
  1180. webpage = self._download_webpage(url, video_id)
  1181. video_title = self._html_search_regex(r'<div class="module-title">(.*?)</div>',
  1182. webpage, u'title')
  1183. xml_url = u'http://video2.spiegel.de/flash/' + video_id + u'.xml'
  1184. xml_code = self._download_webpage(xml_url, video_id,
  1185. note=u'Downloading XML', errnote=u'Failed to download XML')
  1186. idoc = xml.etree.ElementTree.fromstring(xml_code)
  1187. last_type = idoc[-1]
  1188. filename = last_type.findall('./filename')[0].text
  1189. duration = float(last_type.findall('./duration')[0].text)
  1190. video_url = 'http://video2.spiegel.de/flash/' + filename
  1191. video_ext = filename.rpartition('.')[2]
  1192. info = {
  1193. 'id': video_id,
  1194. 'url': video_url,
  1195. 'ext': video_ext,
  1196. 'title': video_title,
  1197. 'duration': duration,
  1198. }
  1199. return [info]
  1200. class LiveLeakIE(InfoExtractor):
  1201. _VALID_URL = r'^(?:http?://)?(?:\w+\.)?liveleak\.com/view\?(?:.*?)i=(?P<video_id>[\w_]+)(?:.*)'
  1202. IE_NAME = u'liveleak'
  1203. def _real_extract(self, url):
  1204. mobj = re.match(self._VALID_URL, url)
  1205. if mobj is None:
  1206. raise ExtractorError(u'Invalid URL: %s' % url)
  1207. video_id = mobj.group('video_id')
  1208. webpage = self._download_webpage(url, video_id)
  1209. video_url = self._search_regex(r'file: "(.*?)",',
  1210. webpage, u'video URL')
  1211. video_title = self._html_search_regex(r'<meta property="og:title" content="(?P<title>.*?)"',
  1212. webpage, u'title').replace('LiveLeak.com -', '').strip()
  1213. video_description = self._html_search_regex(r'<meta property="og:description" content="(?P<desc>.*?)"',
  1214. webpage, u'description', fatal=False)
  1215. video_uploader = self._html_search_regex(r'By:.*?(\w+)</a>',
  1216. webpage, u'uploader', fatal=False)
  1217. info = {
  1218. 'id': video_id,
  1219. 'url': video_url,
  1220. 'ext': 'mp4',
  1221. 'title': video_title,
  1222. 'description': video_description,
  1223. 'uploader': video_uploader
  1224. }
  1225. return [info]
  1226. class TumblrIE(InfoExtractor):
  1227. _VALID_URL = r'http://(?P<blog_name>.*?)\.tumblr\.com/((post)|(video))/(?P<id>\d*)/(.*?)'
  1228. def _real_extract(self, url):
  1229. m_url = re.match(self._VALID_URL, url)
  1230. video_id = m_url.group('id')
  1231. blog = m_url.group('blog_name')
  1232. url = 'http://%s.tumblr.com/post/%s/' % (blog, video_id)
  1233. webpage = self._download_webpage(url, video_id)
  1234. re_video = r'src=\\x22(?P<video_url>http://%s\.tumblr\.com/video_file/%s/(.*?))\\x22 type=\\x22video/(?P<ext>.*?)\\x22' % (blog, video_id)
  1235. video = re.search(re_video, webpage)
  1236. if video is None:
  1237. raise ExtractorError(u'Unable to extract video')
  1238. video_url = video.group('video_url')
  1239. ext = video.group('ext')
  1240. video_thumbnail = self._search_regex(r'posters(.*?)\[\\x22(?P<thumb>.*?)\\x22',
  1241. webpage, u'thumbnail', fatal=False) # We pick the first poster
  1242. if video_thumbnail: video_thumbnail = video_thumbnail.replace('\\', '')
  1243. # The only place where you can get a title, it's not complete,
  1244. # but searching in other places doesn't work for all videos
  1245. video_title = self._html_search_regex(r'<title>(?P<title>.*?)</title>',
  1246. webpage, u'title', flags=re.DOTALL)
  1247. return [{'id': video_id,
  1248. 'url': video_url,
  1249. 'title': video_title,
  1250. 'thumbnail': video_thumbnail,
  1251. 'ext': ext
  1252. }]
  1253. class BandcampIE(InfoExtractor):
  1254. _VALID_URL = r'http://.*?\.bandcamp\.com/track/(?P<title>.*)'
  1255. def _real_extract(self, url):
  1256. mobj = re.match(self._VALID_URL, url)
  1257. title = mobj.group('title')
  1258. webpage = self._download_webpage(url, title)
  1259. # We get the link to the free download page
  1260. m_download = re.search(r'freeDownloadPage: "(.*?)"', webpage)
  1261. if m_download is None:
  1262. raise ExtractorError(u'No free songs found')
  1263. download_link = m_download.group(1)
  1264. id = re.search(r'var TralbumData = {(.*?)id: (?P<id>\d*?)$',
  1265. webpage, re.MULTILINE|re.DOTALL).group('id')
  1266. download_webpage = self._download_webpage(download_link, id,
  1267. 'Downloading free downloads page')
  1268. # We get the dictionary of the track from some javascrip code
  1269. info = re.search(r'items: (.*?),$',
  1270. download_webpage, re.MULTILINE).group(1)
  1271. info = json.loads(info)[0]
  1272. # We pick mp3-320 for now, until format selection can be easily implemented.
  1273. mp3_info = info[u'downloads'][u'mp3-320']
  1274. # If we try to use this url it says the link has expired
  1275. initial_url = mp3_info[u'url']
  1276. re_url = r'(?P<server>http://(.*?)\.bandcamp\.com)/download/track\?enc=mp3-320&fsig=(?P<fsig>.*?)&id=(?P<id>.*?)&ts=(?P<ts>.*)$'
  1277. m_url = re.match(re_url, initial_url)
  1278. #We build the url we will use to get the final track url
  1279. # This url is build in Bandcamp in the script download_bunde_*.js
  1280. request_url = '%s/statdownload/track?enc=mp3-320&fsig=%s&id=%s&ts=%s&.rand=665028774616&.vrs=1' % (m_url.group('server'), m_url.group('fsig'), id, m_url.group('ts'))
  1281. final_url_webpage = self._download_webpage(request_url, id, 'Requesting download url')
  1282. # If we could correctly generate the .rand field the url would be
  1283. #in the "download_url" key
  1284. final_url = re.search(r'"retry_url":"(.*?)"', final_url_webpage).group(1)
  1285. track_info = {'id':id,
  1286. 'title' : info[u'title'],
  1287. 'ext' : 'mp3',
  1288. 'url' : final_url,
  1289. 'thumbnail' : info[u'thumb_url'],
  1290. 'uploader' : info[u'artist']
  1291. }
  1292. return [track_info]
  1293. class RedTubeIE(InfoExtractor):
  1294. """Information Extractor for redtube"""
  1295. _VALID_URL = r'(?:http://)?(?:www\.)?redtube\.com/(?P<id>[0-9]+)'
  1296. def _real_extract(self,url):
  1297. mobj = re.match(self._VALID_URL, url)
  1298. if mobj is None:
  1299. raise ExtractorError(u'Invalid URL: %s' % url)
  1300. video_id = mobj.group('id')
  1301. video_extension = 'mp4'
  1302. webpage = self._download_webpage(url, video_id)
  1303. self.report_extraction(video_id)
  1304. video_url = self._html_search_regex(r'<source src="(.+?)" type="video/mp4">',
  1305. webpage, u'video URL')
  1306. video_title = self._html_search_regex('<h1 class="videoTitle slidePanelMovable">(.+?)</h1>',
  1307. webpage, u'title')
  1308. return [{
  1309. 'id': video_id,
  1310. 'url': video_url,
  1311. 'ext': video_extension,
  1312. 'title': video_title,
  1313. }]
  1314. class InaIE(InfoExtractor):
  1315. """Information Extractor for Ina.fr"""
  1316. _VALID_URL = r'(?:http://)?(?:www\.)?ina\.fr/video/(?P<id>I[0-9]+)/.*'
  1317. def _real_extract(self,url):
  1318. mobj = re.match(self._VALID_URL, url)
  1319. video_id = mobj.group('id')
  1320. mrss_url='http://player.ina.fr/notices/%s.mrss' % video_id
  1321. video_extension = 'mp4'
  1322. webpage = self._download_webpage(mrss_url, video_id)
  1323. self.report_extraction(video_id)
  1324. video_url = self._html_search_regex(r'<media:player url="(?P<mp4url>http://mp4.ina.fr/[^"]+\.mp4)',
  1325. webpage, u'video URL')
  1326. video_title = self._search_regex(r'<title><!\[CDATA\[(?P<titre>.*?)]]></title>',
  1327. webpage, u'title')
  1328. return [{
  1329. 'id': video_id,
  1330. 'url': video_url,
  1331. 'ext': video_extension,
  1332. 'title': video_title,
  1333. }]
  1334. class HowcastIE(InfoExtractor):
  1335. """Information Extractor for Howcast.com"""
  1336. _VALID_URL = r'(?:https?://)?(?:www\.)?howcast\.com/videos/(?P<id>\d+)'
  1337. def _real_extract(self, url):
  1338. mobj = re.match(self._VALID_URL, url)
  1339. video_id = mobj.group('id')
  1340. webpage_url = 'http://www.howcast.com/videos/' + video_id
  1341. webpage = self._download_webpage(webpage_url, video_id)
  1342. self.report_extraction(video_id)
  1343. video_url = self._search_regex(r'\'?file\'?: "(http://mobile-media\.howcast\.com/[0-9]+\.mp4)',
  1344. webpage, u'video URL')
  1345. video_title = self._html_search_regex(r'<meta content=(?:"([^"]+)"|\'([^\']+)\') property=\'og:title\'',
  1346. webpage, u'title')
  1347. video_description = self._html_search_regex(r'<meta content=(?:"([^"]+)"|\'([^\']+)\') name=\'description\'',
  1348. webpage, u'description', fatal=False)
  1349. thumbnail = self._html_search_regex(r'<meta content=\'(.+?)\' property=\'og:image\'',
  1350. webpage, u'thumbnail', fatal=False)
  1351. return [{
  1352. 'id': video_id,
  1353. 'url': video_url,
  1354. 'ext': 'mp4',
  1355. 'title': video_title,
  1356. 'description': video_description,
  1357. 'thumbnail': thumbnail,
  1358. }]
  1359. class VineIE(InfoExtractor):
  1360. """Information Extractor for Vine.co"""
  1361. _VALID_URL = r'(?:https?://)?(?:www\.)?vine\.co/v/(?P<id>\w+)'
  1362. def _real_extract(self, url):
  1363. mobj = re.match(self._VALID_URL, url)
  1364. video_id = mobj.group('id')
  1365. webpage_url = 'https://vine.co/v/' + video_id
  1366. webpage = self._download_webpage(webpage_url, video_id)
  1367. self.report_extraction(video_id)
  1368. video_url = self._html_search_regex(r'<meta property="twitter:player:stream" content="(.+?)"',
  1369. webpage, u'video URL')
  1370. video_title = self._html_search_regex(r'<meta property="og:title" content="(.+?)"',
  1371. webpage, u'title')
  1372. thumbnail = self._html_search_regex(r'<meta property="og:image" content="(.+?)(\?.*?)?"',
  1373. webpage, u'thumbnail', fatal=False)
  1374. uploader = self._html_search_regex(r'<div class="user">.*?<h2>(.+?)</h2>',
  1375. webpage, u'uploader', fatal=False, flags=re.DOTALL)
  1376. return [{
  1377. 'id': video_id,
  1378. 'url': video_url,
  1379. 'ext': 'mp4',
  1380. 'title': video_title,
  1381. 'thumbnail': thumbnail,
  1382. 'uploader': uploader,
  1383. }]
  1384. class FlickrIE(InfoExtractor):
  1385. """Information Extractor for Flickr videos"""
  1386. _VALID_URL = r'(?:https?://)?(?:www\.)?flickr\.com/photos/(?P<uploader_id>[\w\-_@]+)/(?P<id>\d+).*'
  1387. def _real_extract(self, url):
  1388. mobj = re.match(self._VALID_URL, url)
  1389. video_id = mobj.group('id')
  1390. video_uploader_id = mobj.group('uploader_id')
  1391. webpage_url = 'http://www.flickr.com/photos/' + video_uploader_id + '/' + video_id
  1392. webpage = self._download_webpage(webpage_url, video_id)
  1393. secret = self._search_regex(r"photo_secret: '(\w+)'", webpage, u'secret')
  1394. first_url = 'https://secure.flickr.com/apps/video/video_mtl_xml.gne?v=x&photo_id=' + video_id + '&secret=' + secret + '&bitrate=700&target=_self'
  1395. first_xml = self._download_webpage(first_url, video_id, 'Downloading first data webpage')
  1396. node_id = self._html_search_regex(r'<Item id="id">(\d+-\d+)</Item>',
  1397. first_xml, u'node_id')
  1398. second_url = 'https://secure.flickr.com/video_playlist.gne?node_id=' + node_id + '&tech=flash&mode=playlist&bitrate=700&secret=' + secret + '&rd=video.yahoo.com&noad=1'
  1399. second_xml = self._download_webpage(second_url, video_id, 'Downloading second data webpage')
  1400. self.report_extraction(video_id)
  1401. mobj = re.search(r'<STREAM APP="(.+?)" FULLPATH="(.+?)"', second_xml)
  1402. if mobj is None:
  1403. raise ExtractorError(u'Unable to extract video url')
  1404. video_url = mobj.group(1) + unescapeHTML(mobj.group(2))
  1405. video_title = self._html_search_regex(r'<meta property="og:title" content=(?:"([^"]+)"|\'([^\']+)\')',
  1406. webpage, u'video title')
  1407. video_description = self._html_search_regex(r'<meta property="og:description" content=(?:"([^"]+)"|\'([^\']+)\')',
  1408. webpage, u'description', fatal=False)
  1409. thumbnail = self._html_search_regex(r'<meta property="og:image" content=(?:"([^"]+)"|\'([^\']+)\')',
  1410. webpage, u'thumbnail', fatal=False)
  1411. return [{
  1412. 'id': video_id,
  1413. 'url': video_url,
  1414. 'ext': 'mp4',
  1415. 'title': video_title,
  1416. 'description': video_description,
  1417. 'thumbnail': thumbnail,
  1418. 'uploader_id': video_uploader_id,
  1419. }]
  1420. class TeamcocoIE(InfoExtractor):
  1421. _VALID_URL = r'http://teamcoco\.com/video/(?P<url_title>.*)'
  1422. def _real_extract(self, url):
  1423. mobj = re.match(self._VALID_URL, url)
  1424. if mobj is None:
  1425. raise ExtractorError(u'Invalid URL: %s' % url)
  1426. url_title = mobj.group('url_title')
  1427. webpage = self._download_webpage(url, url_title)
  1428. video_id = self._html_search_regex(r'<article class="video" data-id="(\d+?)"',
  1429. webpage, u'video id')
  1430. self.report_extraction(video_id)
  1431. video_title = self._html_search_regex(r'<meta property="og:title" content="(.+?)"',
  1432. webpage, u'title')
  1433. thumbnail = self._html_search_regex(r'<meta property="og:image" content="(.+?)"',
  1434. webpage, u'thumbnail', fatal=False)
  1435. video_description = self._html_search_regex(r'<meta property="og:description" content="(.*?)"',
  1436. webpage, u'description', fatal=False)
  1437. data_url = 'http://teamcoco.com/cvp/2.0/%s.xml' % video_id
  1438. data = self._download_webpage(data_url, video_id, 'Downloading data webpage')
  1439. video_url = self._html_search_regex(r'<file type="high".*?>(.*?)</file>',
  1440. data, u'video URL')
  1441. return [{
  1442. 'id': video_id,
  1443. 'url': video_url,
  1444. 'ext': 'mp4',
  1445. 'title': video_title,
  1446. 'thumbnail': thumbnail,
  1447. 'description': video_description,
  1448. }]
  1449. class XHamsterIE(InfoExtractor):
  1450. """Information Extractor for xHamster"""
  1451. _VALID_URL = r'(?:http://)?(?:www.)?xhamster\.com/movies/(?P<id>[0-9]+)/.*\.html'
  1452. def _real_extract(self,url):
  1453. mobj = re.match(self._VALID_URL, url)
  1454. video_id = mobj.group('id')
  1455. mrss_url = 'http://xhamster.com/movies/%s/.html' % video_id
  1456. webpage = self._download_webpage(mrss_url, video_id)
  1457. mobj = re.search(r'\'srv\': \'(?P<server>[^\']*)\',\s*\'file\': \'(?P<file>[^\']+)\',', webpage)
  1458. if mobj is None:
  1459. raise ExtractorError(u'Unable to extract media URL')
  1460. if len(mobj.group('server')) == 0:
  1461. video_url = compat_urllib_parse.unquote(mobj.group('file'))
  1462. else:
  1463. video_url = mobj.group('server')+'/key='+mobj.group('file')
  1464. video_extension = video_url.split('.')[-1]
  1465. video_title = self._html_search_regex(r'<title>(?P<title>.+?) - xHamster\.com</title>',
  1466. webpage, u'title')
  1467. # Can't see the description anywhere in the UI
  1468. # video_description = self._html_search_regex(r'<span>Description: </span>(?P<description>[^<]+)',
  1469. # webpage, u'description', fatal=False)
  1470. # if video_description: video_description = unescapeHTML(video_description)
  1471. mobj = re.search(r'hint=\'(?P<upload_date_Y>[0-9]{4})-(?P<upload_date_m>[0-9]{2})-(?P<upload_date_d>[0-9]{2}) [0-9]{2}:[0-9]{2}:[0-9]{2} [A-Z]{3,4}\'', webpage)
  1472. if mobj:
  1473. video_upload_date = mobj.group('upload_date_Y')+mobj.group('upload_date_m')+mobj.group('upload_date_d')
  1474. else:
  1475. video_upload_date = None
  1476. self._downloader.report_warning(u'Unable to extract upload date')
  1477. video_uploader_id = self._html_search_regex(r'<a href=\'/user/[^>]+>(?P<uploader_id>[^<]+)',
  1478. webpage, u'uploader id', default=u'anonymous')
  1479. video_thumbnail = self._search_regex(r'\'image\':\'(?P<thumbnail>[^\']+)\'',
  1480. webpage, u'thumbnail', fatal=False)
  1481. return [{
  1482. 'id': video_id,
  1483. 'url': video_url,
  1484. 'ext': video_extension,
  1485. 'title': video_title,
  1486. # 'description': video_description,
  1487. 'upload_date': video_upload_date,
  1488. 'uploader_id': video_uploader_id,
  1489. 'thumbnail': video_thumbnail
  1490. }]
  1491. class HypemIE(InfoExtractor):
  1492. """Information Extractor for hypem"""
  1493. _VALID_URL = r'(?:http://)?(?:www\.)?hypem\.com/track/([^/]+)/([^/]+)'
  1494. def _real_extract(self, url):
  1495. mobj = re.match(self._VALID_URL, url)
  1496. if mobj is None:
  1497. raise ExtractorError(u'Invalid URL: %s' % url)
  1498. track_id = mobj.group(1)
  1499. data = { 'ax': 1, 'ts': time.time() }
  1500. data_encoded = compat_urllib_parse.urlencode(data)
  1501. complete_url = url + "?" + data_encoded
  1502. request = compat_urllib_request.Request(complete_url)
  1503. response, urlh = self._download_webpage_handle(request, track_id, u'Downloading webpage with the url')
  1504. cookie = urlh.headers.get('Set-Cookie', '')
  1505. self.report_extraction(track_id)
  1506. html_tracks = self._html_search_regex(r'<script type="application/json" id="displayList-data">(.*?)</script>',
  1507. response, u'tracks', flags=re.MULTILINE|re.DOTALL).strip()
  1508. try:
  1509. track_list = json.loads(html_tracks)
  1510. track = track_list[u'tracks'][0]
  1511. except ValueError:
  1512. raise ExtractorError(u'Hypemachine contained invalid JSON.')
  1513. key = track[u"key"]
  1514. track_id = track[u"id"]
  1515. artist = track[u"artist"]
  1516. title = track[u"song"]
  1517. serve_url = "http://hypem.com/serve/source/%s/%s" % (compat_str(track_id), compat_str(key))
  1518. request = compat_urllib_request.Request(serve_url, "" , {'Content-Type': 'application/json'})
  1519. request.add_header('cookie', cookie)
  1520. song_data_json = self._download_webpage(request, track_id, u'Downloading metadata')
  1521. try:
  1522. song_data = json.loads(song_data_json)
  1523. except ValueError:
  1524. raise ExtractorError(u'Hypemachine contained invalid JSON.')
  1525. final_url = song_data[u"url"]
  1526. return [{
  1527. 'id': track_id,
  1528. 'url': final_url,
  1529. 'ext': "mp3",
  1530. 'title': title,
  1531. 'artist': artist,
  1532. }]
  1533. class Vbox7IE(InfoExtractor):
  1534. """Information Extractor for Vbox7"""
  1535. _VALID_URL = r'(?:http://)?(?:www\.)?vbox7\.com/play:([^/]+)'
  1536. def _real_extract(self,url):
  1537. mobj = re.match(self._VALID_URL, url)
  1538. if mobj is None:
  1539. raise ExtractorError(u'Invalid URL: %s' % url)
  1540. video_id = mobj.group(1)
  1541. redirect_page, urlh = self._download_webpage_handle(url, video_id)
  1542. new_location = self._search_regex(r'window\.location = \'(.*)\';', redirect_page, u'redirect location')
  1543. redirect_url = urlh.geturl() + new_location
  1544. webpage = self._download_webpage(redirect_url, video_id, u'Downloading redirect page')
  1545. title = self._html_search_regex(r'<title>(.*)</title>',
  1546. webpage, u'title').split('/')[0].strip()
  1547. ext = "flv"
  1548. info_url = "http://vbox7.com/play/magare.do"
  1549. data = compat_urllib_parse.urlencode({'as3':'1','vid':video_id})
  1550. info_request = compat_urllib_request.Request(info_url, data)
  1551. info_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  1552. info_response = self._download_webpage(info_request, video_id, u'Downloading info webpage')
  1553. if info_response is None:
  1554. raise ExtractorError(u'Unable to extract the media url')
  1555. (final_url, thumbnail_url) = map(lambda x: x.split('=')[1], info_response.split('&'))
  1556. return [{
  1557. 'id': video_id,
  1558. 'url': final_url,
  1559. 'ext': ext,
  1560. 'title': title,
  1561. 'thumbnail': thumbnail_url,
  1562. }]
  1563. def gen_extractors():
  1564. """ Return a list of an instance of every supported extractor.
  1565. The order does matter; the first extractor matched is the one handling the URL.
  1566. """
  1567. return [
  1568. YoutubePlaylistIE(),
  1569. YoutubeChannelIE(),
  1570. YoutubeUserIE(),
  1571. YoutubeSearchIE(),
  1572. YoutubeIE(),
  1573. MetacafeIE(),
  1574. DailymotionIE(),
  1575. GoogleSearchIE(),
  1576. PhotobucketIE(),
  1577. YahooIE(),
  1578. YahooSearchIE(),
  1579. DepositFilesIE(),
  1580. FacebookIE(),
  1581. BlipTVIE(),
  1582. BlipTVUserIE(),
  1583. VimeoIE(),
  1584. MyVideoIE(),
  1585. ComedyCentralIE(),
  1586. EscapistIE(),
  1587. CollegeHumorIE(),
  1588. XVideosIE(),
  1589. SoundcloudSetIE(),
  1590. SoundcloudIE(),
  1591. InfoQIE(),
  1592. MixcloudIE(),
  1593. StanfordOpenClassroomIE(),
  1594. MTVIE(),
  1595. YoukuIE(),
  1596. XNXXIE(),
  1597. YouJizzIE(),
  1598. PornotubeIE(),
  1599. YouPornIE(),
  1600. GooglePlusIE(),
  1601. ArteTvIE(),
  1602. NBAIE(),
  1603. WorldStarHipHopIE(),
  1604. JustinTVIE(),
  1605. FunnyOrDieIE(),
  1606. SteamIE(),
  1607. UstreamIE(),
  1608. RBMARadioIE(),
  1609. EightTracksIE(),
  1610. KeekIE(),
  1611. TEDIE(),
  1612. MySpassIE(),
  1613. SpiegelIE(),
  1614. LiveLeakIE(),
  1615. ARDIE(),
  1616. ZDFIE(),
  1617. TumblrIE(),
  1618. BandcampIE(),
  1619. RedTubeIE(),
  1620. InaIE(),
  1621. HowcastIE(),
  1622. VineIE(),
  1623. FlickrIE(),
  1624. TeamcocoIE(),
  1625. XHamsterIE(),
  1626. HypemIE(),
  1627. Vbox7IE(),
  1628. GametrailersIE(),
  1629. StatigramIE(),
  1630. GenericIE()
  1631. ]
  1632. def get_info_extractor(ie_name):
  1633. """Returns the info extractor class with the given ie_name"""
  1634. return globals()[ie_name+'IE']