InfoExtractors.py 75 KB

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