InfoExtractors.py 100 KB

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