InfoExtractors.py 62 KB

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