InfoExtractors.py 88 KB

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