2
0

InfoExtractors.py 175 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import
  4. import base64
  5. import datetime
  6. import itertools
  7. import netrc
  8. import os
  9. import re
  10. import socket
  11. import time
  12. import email.utils
  13. import xml.etree.ElementTree
  14. import random
  15. import math
  16. import operator
  17. from .utils import *
  18. class InfoExtractor(object):
  19. """Information Extractor class.
  20. Information extractors are the classes that, given a URL, extract
  21. information about the video (or videos) the URL refers to. This
  22. information includes the real video URL, the video title, author and
  23. others. The information is stored in a dictionary which is then
  24. passed to the FileDownloader. The FileDownloader processes this
  25. information possibly downloading the video to the file system, among
  26. other possible outcomes.
  27. The dictionaries must include the following fields:
  28. id: Video identifier.
  29. url: Final video URL.
  30. title: Video title, unescaped.
  31. ext: Video filename extension.
  32. The following fields are optional:
  33. format: The video format, defaults to ext (used for --get-format)
  34. thumbnail: Full URL to a video thumbnail image.
  35. description: One-line video description.
  36. uploader: Full name of the video uploader.
  37. upload_date: Video upload date (YYYYMMDD).
  38. uploader_id: Nickname or id of the video uploader.
  39. location: Physical location of the video.
  40. player_url: SWF Player URL (used for rtmpdump).
  41. subtitles: The subtitle file contents.
  42. urlhandle: [internal] The urlHandle to be used to download the file,
  43. like returned by urllib.request.urlopen
  44. The fields should all be Unicode strings.
  45. Subclasses of this one should re-define the _real_initialize() and
  46. _real_extract() methods and define a _VALID_URL regexp.
  47. Probably, they should also be added to the list of extractors.
  48. _real_extract() must return a *list* of information dictionaries as
  49. described above.
  50. Finally, the _WORKING attribute should be set to False for broken IEs
  51. in order to warn the users and skip the tests.
  52. """
  53. _ready = False
  54. _downloader = None
  55. _WORKING = True
  56. def __init__(self, downloader=None):
  57. """Constructor. Receives an optional downloader."""
  58. self._ready = False
  59. self.set_downloader(downloader)
  60. @classmethod
  61. def suitable(cls, url):
  62. """Receives a URL and returns True if suitable for this IE."""
  63. return re.match(cls._VALID_URL, url) is not None
  64. @classmethod
  65. def working(cls):
  66. """Getter method for _WORKING."""
  67. return cls._WORKING
  68. def initialize(self):
  69. """Initializes an instance (authentication, etc)."""
  70. if not self._ready:
  71. self._real_initialize()
  72. self._ready = True
  73. def extract(self, url):
  74. """Extracts URL information and returns it in list of dicts."""
  75. self.initialize()
  76. return self._real_extract(url)
  77. def set_downloader(self, downloader):
  78. """Sets the downloader for this IE."""
  79. self._downloader = downloader
  80. def _real_initialize(self):
  81. """Real initialization process. Redefine in subclasses."""
  82. pass
  83. def _real_extract(self, url):
  84. """Real extraction process. Redefine in subclasses."""
  85. pass
  86. @property
  87. def IE_NAME(self):
  88. return type(self).__name__[:-2]
  89. def _request_webpage(self, url_or_request, video_id, note=None, errnote=None):
  90. """ Returns the response handle """
  91. if note is None:
  92. note = u'Downloading video webpage'
  93. self._downloader.to_screen(u'[%s] %s: %s' % (self.IE_NAME, video_id, note))
  94. try:
  95. return compat_urllib_request.urlopen(url_or_request)
  96. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  97. if errnote is None:
  98. errnote = u'Unable to download webpage'
  99. raise ExtractorError(u'%s: %s' % (errnote, compat_str(err)), sys.exc_info()[2])
  100. def _download_webpage(self, url_or_request, video_id, note=None, errnote=None):
  101. """ Returns the data of the page as a string """
  102. urlh = self._request_webpage(url_or_request, video_id, note, errnote)
  103. content_type = urlh.headers.get('Content-Type', '')
  104. m = re.match(r'[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)', content_type)
  105. if m:
  106. encoding = m.group(1)
  107. else:
  108. encoding = 'utf-8'
  109. webpage_bytes = urlh.read()
  110. return webpage_bytes.decode(encoding, 'replace')
  111. class YoutubeIE(InfoExtractor):
  112. """Information extractor for youtube.com."""
  113. _VALID_URL = r"""^
  114. (
  115. (?:https?://)? # http(s):// (optional)
  116. (?:youtu\.be/|(?:\w+\.)?youtube(?:-nocookie)?\.com/|
  117. tube\.majestyc\.net/) # the various hostnames, with wildcard subdomains
  118. (?:.*?\#/)? # handle anchor (#/) redirect urls
  119. (?: # the various things that can precede the ID:
  120. (?:(?:v|embed|e)/) # v/ or embed/ or e/
  121. |(?: # or the v= param in all its forms
  122. (?:watch(?:_popup)?(?:\.php)?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  123. (?:\?|\#!?) # the params delimiter ? or # or #!
  124. (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
  125. v=
  126. )
  127. )? # optional -> youtube.com/xxxx is OK
  128. )? # all until now is optional -> you can pass the naked ID
  129. ([0-9A-Za-z_-]+) # here is it! the YouTube video ID
  130. (?(1).+)? # if we found the ID, everything can follow
  131. $"""
  132. _LANG_URL = r'http://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  133. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  134. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  135. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  136. _NETRC_MACHINE = 'youtube'
  137. # Listed in order of quality
  138. _available_formats = ['38', '37', '46', '22', '45', '35', '44', '34', '18', '43', '6', '5', '17', '13']
  139. _available_formats_prefer_free = ['38', '46', '37', '45', '22', '44', '35', '43', '34', '18', '6', '5', '17', '13']
  140. _video_extensions = {
  141. '13': '3gp',
  142. '17': 'mp4',
  143. '18': 'mp4',
  144. '22': 'mp4',
  145. '37': 'mp4',
  146. '38': 'video', # You actually don't know if this will be MOV, AVI or whatever
  147. '43': 'webm',
  148. '44': 'webm',
  149. '45': 'webm',
  150. '46': 'webm',
  151. }
  152. _video_dimensions = {
  153. '5': '240x400',
  154. '6': '???',
  155. '13': '???',
  156. '17': '144x176',
  157. '18': '360x640',
  158. '22': '720x1280',
  159. '34': '360x640',
  160. '35': '480x854',
  161. '37': '1080x1920',
  162. '38': '3072x4096',
  163. '43': '360x640',
  164. '44': '480x854',
  165. '45': '720x1280',
  166. '46': '1080x1920',
  167. }
  168. IE_NAME = u'youtube'
  169. @classmethod
  170. def suitable(cls, url):
  171. """Receives a URL and returns True if suitable for this IE."""
  172. if YoutubePlaylistIE.suitable(url): return False
  173. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  174. def report_lang(self):
  175. """Report attempt to set language."""
  176. self._downloader.to_screen(u'[youtube] Setting language')
  177. def report_login(self):
  178. """Report attempt to log in."""
  179. self._downloader.to_screen(u'[youtube] Logging in')
  180. def report_age_confirmation(self):
  181. """Report attempt to confirm age."""
  182. self._downloader.to_screen(u'[youtube] Confirming age')
  183. def report_video_webpage_download(self, video_id):
  184. """Report attempt to download video webpage."""
  185. self._downloader.to_screen(u'[youtube] %s: Downloading video webpage' % video_id)
  186. def report_video_info_webpage_download(self, video_id):
  187. """Report attempt to download video info webpage."""
  188. self._downloader.to_screen(u'[youtube] %s: Downloading video info webpage' % video_id)
  189. def report_video_subtitles_download(self, video_id):
  190. """Report attempt to download video info webpage."""
  191. self._downloader.to_screen(u'[youtube] %s: Checking available subtitles' % video_id)
  192. def report_video_subtitles_request(self, video_id, sub_lang, format):
  193. """Report attempt to download video info webpage."""
  194. self._downloader.to_screen(u'[youtube] %s: Downloading video subtitles for %s.%s' % (video_id, sub_lang, format))
  195. def report_video_subtitles_available(self, video_id, sub_lang_list):
  196. """Report available subtitles."""
  197. sub_lang = ",".join(list(sub_lang_list.keys()))
  198. self._downloader.to_screen(u'[youtube] %s: Available subtitles for video: %s' % (video_id, sub_lang))
  199. def report_information_extraction(self, video_id):
  200. """Report attempt to extract video information."""
  201. self._downloader.to_screen(u'[youtube] %s: Extracting video information' % video_id)
  202. def report_unavailable_format(self, video_id, format):
  203. """Report extracted video URL."""
  204. self._downloader.to_screen(u'[youtube] %s: Format %s not available' % (video_id, format))
  205. def report_rtmp_download(self):
  206. """Indicate the download will use the RTMP protocol."""
  207. self._downloader.to_screen(u'[youtube] RTMP download detected')
  208. def _get_available_subtitles(self, video_id):
  209. self.report_video_subtitles_download(video_id)
  210. request = compat_urllib_request.Request('http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id)
  211. try:
  212. sub_list = compat_urllib_request.urlopen(request).read().decode('utf-8')
  213. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  214. return (u'unable to download video subtitles: %s' % compat_str(err), None)
  215. sub_lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
  216. sub_lang_list = dict((l[1], l[0]) for l in sub_lang_list)
  217. if not sub_lang_list:
  218. return (u'video doesn\'t have subtitles', None)
  219. return sub_lang_list
  220. def _list_available_subtitles(self, video_id):
  221. sub_lang_list = self._get_available_subtitles(video_id)
  222. self.report_video_subtitles_available(video_id, sub_lang_list)
  223. def _request_subtitle(self, sub_lang, sub_name, video_id, format):
  224. """
  225. Return tuple:
  226. (error_message, sub_lang, sub)
  227. """
  228. self.report_video_subtitles_request(video_id, sub_lang, format)
  229. params = compat_urllib_parse.urlencode({
  230. 'lang': sub_lang,
  231. 'name': sub_name,
  232. 'v': video_id,
  233. 'fmt': format,
  234. })
  235. url = 'http://www.youtube.com/api/timedtext?' + params
  236. try:
  237. sub = compat_urllib_request.urlopen(url).read().decode('utf-8')
  238. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  239. return (u'unable to download video subtitles: %s' % compat_str(err), None, None)
  240. if not sub:
  241. return (u'Did not fetch video subtitles', None, None)
  242. return (None, sub_lang, sub)
  243. def _extract_subtitle(self, video_id):
  244. """
  245. Return a list with a tuple:
  246. [(error_message, sub_lang, sub)]
  247. """
  248. sub_lang_list = self._get_available_subtitles(video_id)
  249. sub_format = self._downloader.params.get('subtitlesformat')
  250. if isinstance(sub_lang_list,tuple): #There was some error, it didn't get the available subtitles
  251. return [(sub_lang_list[0], None, None)]
  252. if self._downloader.params.get('subtitleslang', False):
  253. sub_lang = self._downloader.params.get('subtitleslang')
  254. elif 'en' in sub_lang_list:
  255. sub_lang = 'en'
  256. else:
  257. sub_lang = list(sub_lang_list.keys())[0]
  258. if not sub_lang in sub_lang_list:
  259. return [(u'no closed captions found in the specified language "%s"' % sub_lang, None, None)]
  260. subtitle = self._request_subtitle(sub_lang, sub_lang_list[sub_lang].encode('utf-8'), video_id, sub_format)
  261. return [subtitle]
  262. def _extract_all_subtitles(self, video_id):
  263. sub_lang_list = self._get_available_subtitles(video_id)
  264. sub_format = self._downloader.params.get('subtitlesformat')
  265. if isinstance(sub_lang_list,tuple): #There was some error, it didn't get the available subtitles
  266. return [(sub_lang_list[0], None, None)]
  267. subtitles = []
  268. for sub_lang in sub_lang_list:
  269. subtitle = self._request_subtitle(sub_lang, sub_lang_list[sub_lang].encode('utf-8'), video_id, sub_format)
  270. subtitles.append(subtitle)
  271. return subtitles
  272. def _print_formats(self, formats):
  273. print('Available formats:')
  274. for x in formats:
  275. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'flv'), self._video_dimensions.get(x, '???')))
  276. def _real_initialize(self):
  277. if self._downloader is None:
  278. return
  279. username = None
  280. password = None
  281. downloader_params = self._downloader.params
  282. # Attempt to use provided username and password or .netrc data
  283. if downloader_params.get('username', None) is not None:
  284. username = downloader_params['username']
  285. password = downloader_params['password']
  286. elif downloader_params.get('usenetrc', False):
  287. try:
  288. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  289. if info is not None:
  290. username = info[0]
  291. password = info[2]
  292. else:
  293. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  294. except (IOError, netrc.NetrcParseError) as err:
  295. self._downloader.report_warning(u'parsing .netrc: %s' % compat_str(err))
  296. return
  297. # Set language
  298. request = compat_urllib_request.Request(self._LANG_URL)
  299. try:
  300. self.report_lang()
  301. compat_urllib_request.urlopen(request).read()
  302. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  303. self._downloader.report_warning(u'unable to set language: %s' % compat_str(err))
  304. return
  305. # No authentication to be performed
  306. if username is None:
  307. return
  308. request = compat_urllib_request.Request(self._LOGIN_URL)
  309. try:
  310. login_page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  311. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  312. self._downloader.report_warning(u'unable to fetch login page: %s' % compat_str(err))
  313. return
  314. galx = None
  315. dsh = None
  316. match = re.search(re.compile(r'<input.+?name="GALX".+?value="(.+?)"', re.DOTALL), login_page)
  317. if match:
  318. galx = match.group(1)
  319. match = re.search(re.compile(r'<input.+?name="dsh".+?value="(.+?)"', re.DOTALL), login_page)
  320. if match:
  321. dsh = match.group(1)
  322. # Log in
  323. login_form_strs = {
  324. u'continue': u'http://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
  325. u'Email': username,
  326. u'GALX': galx,
  327. u'Passwd': password,
  328. u'PersistentCookie': u'yes',
  329. u'_utf8': u'霱',
  330. u'bgresponse': u'js_disabled',
  331. u'checkConnection': u'',
  332. u'checkedDomains': u'youtube',
  333. u'dnConn': u'',
  334. u'dsh': dsh,
  335. u'pstMsg': u'0',
  336. u'rmShown': u'1',
  337. u'secTok': u'',
  338. u'signIn': u'Sign in',
  339. u'timeStmp': u'',
  340. u'service': u'youtube',
  341. u'uilel': u'3',
  342. u'hl': u'en_US',
  343. }
  344. # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
  345. # chokes on unicode
  346. login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
  347. login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
  348. request = compat_urllib_request.Request(self._LOGIN_URL, login_data)
  349. try:
  350. self.report_login()
  351. login_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
  352. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
  353. self._downloader.report_warning(u'unable to log in: bad username or password')
  354. return
  355. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  356. self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
  357. return
  358. # Confirm age
  359. age_form = {
  360. 'next_url': '/',
  361. 'action_confirm': 'Confirm',
  362. }
  363. request = compat_urllib_request.Request(self._AGE_URL, compat_urllib_parse.urlencode(age_form))
  364. try:
  365. self.report_age_confirmation()
  366. age_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
  367. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  368. self._downloader.report_error(u'unable to confirm age: %s' % compat_str(err))
  369. return
  370. def _extract_id(self, url):
  371. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  372. if mobj is None:
  373. self._downloader.report_error(u'invalid URL: %s' % url)
  374. return
  375. video_id = mobj.group(2)
  376. return video_id
  377. def _real_extract(self, url):
  378. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  379. mobj = re.search(self._NEXT_URL_RE, url)
  380. if mobj:
  381. url = 'http://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  382. video_id = self._extract_id(url)
  383. # Get video webpage
  384. self.report_video_webpage_download(video_id)
  385. url = 'http://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
  386. request = compat_urllib_request.Request(url)
  387. try:
  388. video_webpage_bytes = compat_urllib_request.urlopen(request).read()
  389. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  390. self._downloader.report_error(u'unable to download video webpage: %s' % compat_str(err))
  391. return
  392. video_webpage = video_webpage_bytes.decode('utf-8', 'ignore')
  393. # Attempt to extract SWF player URL
  394. mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  395. if mobj is not None:
  396. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  397. else:
  398. player_url = None
  399. # Get video info
  400. self.report_video_info_webpage_download(video_id)
  401. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  402. video_info_url = ('http://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  403. % (video_id, el_type))
  404. request = compat_urllib_request.Request(video_info_url)
  405. try:
  406. video_info_webpage_bytes = compat_urllib_request.urlopen(request).read()
  407. video_info_webpage = video_info_webpage_bytes.decode('utf-8', 'ignore')
  408. video_info = compat_parse_qs(video_info_webpage)
  409. if 'token' in video_info:
  410. break
  411. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  412. self._downloader.report_error(u'unable to download video info webpage: %s' % compat_str(err))
  413. return
  414. if 'token' not in video_info:
  415. if 'reason' in video_info:
  416. self._downloader.report_error(u'YouTube said: %s' % video_info['reason'][0])
  417. else:
  418. self._downloader.report_error(u'"token" parameter not in video info for unknown reason')
  419. return
  420. # Check for "rental" videos
  421. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  422. self._downloader.report_error(u'"rental" videos not supported')
  423. return
  424. # Start extracting information
  425. self.report_information_extraction(video_id)
  426. # uploader
  427. if 'author' not in video_info:
  428. self._downloader.report_error(u'unable to extract uploader name')
  429. return
  430. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  431. # uploader_id
  432. video_uploader_id = None
  433. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  434. if mobj is not None:
  435. video_uploader_id = mobj.group(1)
  436. else:
  437. self._downloader.report_warning(u'unable to extract uploader nickname')
  438. # title
  439. if 'title' not in video_info:
  440. self._downloader.report_error(u'unable to extract video title')
  441. return
  442. video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
  443. # thumbnail image
  444. if 'thumbnail_url' not in video_info:
  445. self._downloader.report_warning(u'unable to extract video thumbnail')
  446. video_thumbnail = ''
  447. else: # don't panic if we can't find it
  448. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  449. # upload date
  450. upload_date = None
  451. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  452. if mobj is not None:
  453. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  454. format_expressions = ['%d %B %Y', '%B %d %Y', '%b %d %Y']
  455. for expression in format_expressions:
  456. try:
  457. upload_date = datetime.datetime.strptime(upload_date, expression).strftime('%Y%m%d')
  458. except:
  459. pass
  460. # description
  461. video_description = get_element_by_id("eow-description", video_webpage)
  462. if video_description:
  463. video_description = clean_html(video_description)
  464. else:
  465. video_description = ''
  466. # subtitles
  467. video_subtitles = None
  468. if self._downloader.params.get('writesubtitles', False):
  469. video_subtitles = self._extract_subtitle(video_id)
  470. if video_subtitles:
  471. (sub_error, sub_lang, sub) = video_subtitles[0]
  472. if sub_error:
  473. self._downloader.report_error(sub_error)
  474. if self._downloader.params.get('allsubtitles', False):
  475. video_subtitles = self._extract_all_subtitles(video_id)
  476. for video_subtitle in video_subtitles:
  477. (sub_error, sub_lang, sub) = video_subtitle
  478. if sub_error:
  479. self._downloader.report_error(sub_error)
  480. if self._downloader.params.get('listsubtitles', False):
  481. sub_lang_list = self._list_available_subtitles(video_id)
  482. return
  483. if 'length_seconds' not in video_info:
  484. self._downloader.report_warning(u'unable to extract video duration')
  485. video_duration = ''
  486. else:
  487. video_duration = compat_urllib_parse.unquote_plus(video_info['length_seconds'][0])
  488. # token
  489. video_token = compat_urllib_parse.unquote_plus(video_info['token'][0])
  490. # Decide which formats to download
  491. req_format = self._downloader.params.get('format', None)
  492. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  493. self.report_rtmp_download()
  494. video_url_list = [(None, video_info['conn'][0])]
  495. elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
  496. url_data_strs = video_info['url_encoded_fmt_stream_map'][0].split(',')
  497. url_data = [compat_parse_qs(uds) for uds in url_data_strs]
  498. url_data = [ud for ud in url_data if 'itag' in ud and 'url' in ud]
  499. url_map = dict((ud['itag'][0], ud['url'][0] + '&signature=' + ud['sig'][0]) for ud in url_data)
  500. format_limit = self._downloader.params.get('format_limit', None)
  501. available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
  502. if format_limit is not None and format_limit in available_formats:
  503. format_list = available_formats[available_formats.index(format_limit):]
  504. else:
  505. format_list = available_formats
  506. existing_formats = [x for x in format_list if x in url_map]
  507. if len(existing_formats) == 0:
  508. self._downloader.report_error(u'no known formats available for video')
  509. return
  510. if self._downloader.params.get('listformats', None):
  511. self._print_formats(existing_formats)
  512. return
  513. if req_format is None or req_format == 'best':
  514. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  515. elif req_format == 'worst':
  516. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  517. elif req_format in ('-1', 'all'):
  518. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  519. else:
  520. # Specific formats. We pick the first in a slash-delimeted sequence.
  521. # For example, if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
  522. req_formats = req_format.split('/')
  523. video_url_list = None
  524. for rf in req_formats:
  525. if rf in url_map:
  526. video_url_list = [(rf, url_map[rf])]
  527. break
  528. if video_url_list is None:
  529. self._downloader.report_error(u'requested format not available')
  530. return
  531. else:
  532. self._downloader.report_error(u'no conn or url_encoded_fmt_stream_map information found in video info')
  533. return
  534. results = []
  535. for format_param, video_real_url in video_url_list:
  536. # Extension
  537. video_extension = self._video_extensions.get(format_param, 'flv')
  538. video_format = '{0} - {1}'.format(format_param if format_param else video_extension,
  539. self._video_dimensions.get(format_param, '???'))
  540. results.append({
  541. 'id': video_id,
  542. 'url': video_real_url,
  543. 'uploader': video_uploader,
  544. 'uploader_id': video_uploader_id,
  545. 'upload_date': upload_date,
  546. 'title': video_title,
  547. 'ext': video_extension,
  548. 'format': video_format,
  549. 'thumbnail': video_thumbnail,
  550. 'description': video_description,
  551. 'player_url': player_url,
  552. 'subtitles': video_subtitles,
  553. 'duration': video_duration
  554. })
  555. return results
  556. class MetacafeIE(InfoExtractor):
  557. """Information Extractor for metacafe.com."""
  558. _VALID_URL = r'(?:http://)?(?:www\.)?metacafe\.com/watch/([^/]+)/([^/]+)/.*'
  559. _DISCLAIMER = 'http://www.metacafe.com/family_filter/'
  560. _FILTER_POST = 'http://www.metacafe.com/f/index.php?inputType=filter&controllerGroup=user'
  561. IE_NAME = u'metacafe'
  562. def __init__(self, downloader=None):
  563. InfoExtractor.__init__(self, downloader)
  564. def report_disclaimer(self):
  565. """Report disclaimer retrieval."""
  566. self._downloader.to_screen(u'[metacafe] Retrieving disclaimer')
  567. def report_age_confirmation(self):
  568. """Report attempt to confirm age."""
  569. self._downloader.to_screen(u'[metacafe] Confirming age')
  570. def report_download_webpage(self, video_id):
  571. """Report webpage download."""
  572. self._downloader.to_screen(u'[metacafe] %s: Downloading webpage' % video_id)
  573. def report_extraction(self, video_id):
  574. """Report information extraction."""
  575. self._downloader.to_screen(u'[metacafe] %s: Extracting information' % video_id)
  576. def _real_initialize(self):
  577. # Retrieve disclaimer
  578. request = compat_urllib_request.Request(self._DISCLAIMER)
  579. try:
  580. self.report_disclaimer()
  581. disclaimer = compat_urllib_request.urlopen(request).read()
  582. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  583. self._downloader.report_error(u'unable to retrieve disclaimer: %s' % compat_str(err))
  584. return
  585. # Confirm age
  586. disclaimer_form = {
  587. 'filters': '0',
  588. 'submit': "Continue - I'm over 18",
  589. }
  590. request = compat_urllib_request.Request(self._FILTER_POST, compat_urllib_parse.urlencode(disclaimer_form))
  591. try:
  592. self.report_age_confirmation()
  593. disclaimer = compat_urllib_request.urlopen(request).read()
  594. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  595. self._downloader.report_error(u'unable to confirm age: %s' % compat_str(err))
  596. return
  597. def _real_extract(self, url):
  598. # Extract id and simplified title from URL
  599. mobj = re.match(self._VALID_URL, url)
  600. if mobj is None:
  601. self._downloader.report_error(u'invalid URL: %s' % url)
  602. return
  603. video_id = mobj.group(1)
  604. # Check if video comes from YouTube
  605. mobj2 = re.match(r'^yt-(.*)$', video_id)
  606. if mobj2 is not None:
  607. self._downloader.download(['http://www.youtube.com/watch?v=%s' % mobj2.group(1)])
  608. return
  609. # Retrieve video webpage to extract further information
  610. request = compat_urllib_request.Request('http://www.metacafe.com/watch/%s/' % video_id)
  611. try:
  612. self.report_download_webpage(video_id)
  613. webpage = compat_urllib_request.urlopen(request).read()
  614. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  615. self._downloader.report_error(u'unable retrieve video webpage: %s' % compat_str(err))
  616. return
  617. # Extract URL, uploader and title from webpage
  618. self.report_extraction(video_id)
  619. mobj = re.search(r'(?m)&mediaURL=([^&]+)', webpage)
  620. if mobj is not None:
  621. mediaURL = compat_urllib_parse.unquote(mobj.group(1))
  622. video_extension = mediaURL[-3:]
  623. # Extract gdaKey if available
  624. mobj = re.search(r'(?m)&gdaKey=(.*?)&', webpage)
  625. if mobj is None:
  626. video_url = mediaURL
  627. else:
  628. gdaKey = mobj.group(1)
  629. video_url = '%s?__gda__=%s' % (mediaURL, gdaKey)
  630. else:
  631. mobj = re.search(r' name="flashvars" value="(.*?)"', webpage)
  632. if mobj is None:
  633. self._downloader.report_error(u'unable to extract media URL')
  634. return
  635. vardict = compat_parse_qs(mobj.group(1))
  636. if 'mediaData' not in vardict:
  637. self._downloader.report_error(u'unable to extract media URL')
  638. return
  639. mobj = re.search(r'"mediaURL":"(http.*?)","key":"(.*?)"', vardict['mediaData'][0])
  640. if mobj is None:
  641. self._downloader.report_error(u'unable to extract media URL')
  642. return
  643. mediaURL = mobj.group(1).replace('\\/', '/')
  644. video_extension = mediaURL[-3:]
  645. video_url = '%s?__gda__=%s' % (mediaURL, mobj.group(2))
  646. mobj = re.search(r'(?im)<title>(.*) - Video</title>', webpage)
  647. if mobj is None:
  648. self._downloader.report_error(u'unable to extract title')
  649. return
  650. video_title = mobj.group(1).decode('utf-8')
  651. mobj = re.search(r'submitter=(.*?);', webpage)
  652. if mobj is None:
  653. self._downloader.report_error(u'unable to extract uploader nickname')
  654. return
  655. video_uploader = mobj.group(1)
  656. return [{
  657. 'id': video_id.decode('utf-8'),
  658. 'url': video_url.decode('utf-8'),
  659. 'uploader': video_uploader.decode('utf-8'),
  660. 'upload_date': None,
  661. 'title': video_title,
  662. 'ext': video_extension.decode('utf-8'),
  663. }]
  664. class DailymotionIE(InfoExtractor):
  665. """Information Extractor for Dailymotion"""
  666. _VALID_URL = r'(?i)(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/video/([^/]+)'
  667. IE_NAME = u'dailymotion'
  668. _WORKING = False
  669. def __init__(self, downloader=None):
  670. InfoExtractor.__init__(self, downloader)
  671. def report_extraction(self, video_id):
  672. """Report information extraction."""
  673. self._downloader.to_screen(u'[dailymotion] %s: Extracting information' % video_id)
  674. def _real_extract(self, url):
  675. # Extract id and simplified title from URL
  676. mobj = re.match(self._VALID_URL, url)
  677. if mobj is None:
  678. self._downloader.report_error(u'invalid URL: %s' % url)
  679. return
  680. video_id = mobj.group(1).split('_')[0].split('?')[0]
  681. video_extension = 'mp4'
  682. # Retrieve video webpage to extract further information
  683. request = compat_urllib_request.Request(url)
  684. request.add_header('Cookie', 'family_filter=off')
  685. webpage = self._download_webpage(request, video_id)
  686. # Extract URL, uploader and title from webpage
  687. self.report_extraction(video_id)
  688. mobj = re.search(r'\s*var flashvars = (.*)', webpage)
  689. if mobj is None:
  690. self._downloader.report_error(u'unable to extract media URL')
  691. return
  692. flashvars = compat_urllib_parse.unquote(mobj.group(1))
  693. for key in ['hd1080URL', 'hd720URL', 'hqURL', 'sdURL', 'ldURL', 'video_url']:
  694. if key in flashvars:
  695. max_quality = key
  696. self._downloader.to_screen(u'[dailymotion] Using %s' % key)
  697. break
  698. else:
  699. self._downloader.report_error(u'unable to extract video URL')
  700. return
  701. mobj = re.search(r'"' + max_quality + r'":"(.+?)"', flashvars)
  702. if mobj is None:
  703. self._downloader.report_error(u'unable to extract video URL')
  704. return
  705. video_url = compat_urllib_parse.unquote(mobj.group(1)).replace('\\/', '/')
  706. # TODO: support choosing qualities
  707. mobj = re.search(r'<meta property="og:title" content="(?P<title>[^"]*)" />', webpage)
  708. if mobj is None:
  709. self._downloader.report_error(u'unable to extract title')
  710. return
  711. video_title = unescapeHTML(mobj.group('title'))
  712. video_uploader = None
  713. mobj = re.search(r'(?im)<span class="owner[^\"]+?">[^<]+?<a [^>]+?>([^<]+?)</a>', webpage)
  714. if mobj is None:
  715. # lookin for official user
  716. mobj_official = re.search(r'<span rel="author"[^>]+?>([^<]+?)</span>', webpage)
  717. if mobj_official is None:
  718. self._downloader.report_warning(u'unable to extract uploader nickname')
  719. else:
  720. video_uploader = mobj_official.group(1)
  721. else:
  722. video_uploader = mobj.group(1)
  723. video_upload_date = None
  724. mobj = re.search(r'<div class="[^"]*uploaded_cont[^"]*" title="[^"]*">([0-9]{2})-([0-9]{2})-([0-9]{4})</div>', webpage)
  725. if mobj is not None:
  726. video_upload_date = mobj.group(3) + mobj.group(2) + mobj.group(1)
  727. return [{
  728. 'id': video_id,
  729. 'url': video_url,
  730. 'uploader': video_uploader,
  731. 'upload_date': video_upload_date,
  732. 'title': video_title,
  733. 'ext': video_extension,
  734. }]
  735. class PhotobucketIE(InfoExtractor):
  736. """Information extractor for photobucket.com."""
  737. _VALID_URL = r'(?:http://)?(?:[a-z0-9]+\.)?photobucket\.com/.*[\?\&]current=(.*\.flv)'
  738. IE_NAME = u'photobucket'
  739. def __init__(self, downloader=None):
  740. InfoExtractor.__init__(self, downloader)
  741. def report_download_webpage(self, video_id):
  742. """Report webpage download."""
  743. self._downloader.to_screen(u'[photobucket] %s: Downloading webpage' % video_id)
  744. def report_extraction(self, video_id):
  745. """Report information extraction."""
  746. self._downloader.to_screen(u'[photobucket] %s: Extracting information' % video_id)
  747. def _real_extract(self, url):
  748. # Extract id from URL
  749. mobj = re.match(self._VALID_URL, url)
  750. if mobj is None:
  751. self._downloader.report_error(u'Invalid URL: %s' % url)
  752. return
  753. video_id = mobj.group(1)
  754. video_extension = 'flv'
  755. # Retrieve video webpage to extract further information
  756. request = compat_urllib_request.Request(url)
  757. try:
  758. self.report_download_webpage(video_id)
  759. webpage = compat_urllib_request.urlopen(request).read()
  760. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  761. self._downloader.report_error(u'Unable to retrieve video webpage: %s' % compat_str(err))
  762. return
  763. # Extract URL, uploader, and title from webpage
  764. self.report_extraction(video_id)
  765. mobj = re.search(r'<link rel="video_src" href=".*\?file=([^"]+)" />', webpage)
  766. if mobj is None:
  767. self._downloader.report_error(u'unable to extract media URL')
  768. return
  769. mediaURL = compat_urllib_parse.unquote(mobj.group(1))
  770. video_url = mediaURL
  771. mobj = re.search(r'<title>(.*) video by (.*) - Photobucket</title>', webpage)
  772. if mobj is None:
  773. self._downloader.report_error(u'unable to extract title')
  774. return
  775. video_title = mobj.group(1).decode('utf-8')
  776. video_uploader = mobj.group(2).decode('utf-8')
  777. return [{
  778. 'id': video_id.decode('utf-8'),
  779. 'url': video_url.decode('utf-8'),
  780. 'uploader': video_uploader,
  781. 'upload_date': None,
  782. 'title': video_title,
  783. 'ext': video_extension.decode('utf-8'),
  784. }]
  785. class YahooIE(InfoExtractor):
  786. """Information extractor for video.yahoo.com."""
  787. _WORKING = False
  788. # _VALID_URL matches all Yahoo! Video URLs
  789. # _VPAGE_URL matches only the extractable '/watch/' URLs
  790. _VALID_URL = r'(?:http://)?(?:[a-z]+\.)?video\.yahoo\.com/(?:watch|network)/([0-9]+)(?:/|\?v=)([0-9]+)(?:[#\?].*)?'
  791. _VPAGE_URL = r'(?:http://)?video\.yahoo\.com/watch/([0-9]+)/([0-9]+)(?:[#\?].*)?'
  792. IE_NAME = u'video.yahoo'
  793. def __init__(self, downloader=None):
  794. InfoExtractor.__init__(self, downloader)
  795. def report_download_webpage(self, video_id):
  796. """Report webpage download."""
  797. self._downloader.to_screen(u'[video.yahoo] %s: Downloading webpage' % video_id)
  798. def report_extraction(self, video_id):
  799. """Report information extraction."""
  800. self._downloader.to_screen(u'[video.yahoo] %s: Extracting information' % video_id)
  801. def _real_extract(self, url, new_video=True):
  802. # Extract ID from URL
  803. mobj = re.match(self._VALID_URL, url)
  804. if mobj is None:
  805. self._downloader.report_error(u'Invalid URL: %s' % url)
  806. return
  807. video_id = mobj.group(2)
  808. video_extension = 'flv'
  809. # Rewrite valid but non-extractable URLs as
  810. # extractable English language /watch/ URLs
  811. if re.match(self._VPAGE_URL, url) is None:
  812. request = compat_urllib_request.Request(url)
  813. try:
  814. webpage = compat_urllib_request.urlopen(request).read()
  815. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  816. self._downloader.report_error(u'Unable to retrieve video webpage: %s' % compat_str(err))
  817. return
  818. mobj = re.search(r'\("id", "([0-9]+)"\);', webpage)
  819. if mobj is None:
  820. self._downloader.report_error(u'Unable to extract id field')
  821. return
  822. yahoo_id = mobj.group(1)
  823. mobj = re.search(r'\("vid", "([0-9]+)"\);', webpage)
  824. if mobj is None:
  825. self._downloader.report_error(u'Unable to extract vid field')
  826. return
  827. yahoo_vid = mobj.group(1)
  828. url = 'http://video.yahoo.com/watch/%s/%s' % (yahoo_vid, yahoo_id)
  829. return self._real_extract(url, new_video=False)
  830. # Retrieve video webpage to extract further information
  831. request = compat_urllib_request.Request(url)
  832. try:
  833. self.report_download_webpage(video_id)
  834. webpage = compat_urllib_request.urlopen(request).read()
  835. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  836. self._downloader.report_error(u'Unable to retrieve video webpage: %s' % compat_str(err))
  837. return
  838. # Extract uploader and title from webpage
  839. self.report_extraction(video_id)
  840. mobj = re.search(r'<meta name="title" content="(.*)" />', webpage)
  841. if mobj is None:
  842. self._downloader.report_error(u'unable to extract video title')
  843. return
  844. video_title = mobj.group(1).decode('utf-8')
  845. mobj = re.search(r'<h2 class="ti-5"><a href="http://video\.yahoo\.com/(people|profile)/[0-9]+" beacon=".*">(.*)</a></h2>', webpage)
  846. if mobj is None:
  847. self._downloader.report_error(u'unable to extract video uploader')
  848. return
  849. video_uploader = mobj.group(1).decode('utf-8')
  850. # Extract video thumbnail
  851. mobj = re.search(r'<link rel="image_src" href="(.*)" />', webpage)
  852. if mobj is None:
  853. self._downloader.report_error(u'unable to extract video thumbnail')
  854. return
  855. video_thumbnail = mobj.group(1).decode('utf-8')
  856. # Extract video description
  857. mobj = re.search(r'<meta name="description" content="(.*)" />', webpage)
  858. if mobj is None:
  859. self._downloader.report_error(u'unable to extract video description')
  860. return
  861. video_description = mobj.group(1).decode('utf-8')
  862. if not video_description:
  863. video_description = 'No description available.'
  864. # Extract video height and width
  865. mobj = re.search(r'<meta name="video_height" content="([0-9]+)" />', webpage)
  866. if mobj is None:
  867. self._downloader.report_error(u'unable to extract video height')
  868. return
  869. yv_video_height = mobj.group(1)
  870. mobj = re.search(r'<meta name="video_width" content="([0-9]+)" />', webpage)
  871. if mobj is None:
  872. self._downloader.report_error(u'unable to extract video width')
  873. return
  874. yv_video_width = mobj.group(1)
  875. # Retrieve video playlist to extract media URL
  876. # I'm not completely sure what all these options are, but we
  877. # seem to need most of them, otherwise the server sends a 401.
  878. yv_lg = 'R0xx6idZnW2zlrKP8xxAIR' # not sure what this represents
  879. yv_bitrate = '700' # according to Wikipedia this is hard-coded
  880. request = compat_urllib_request.Request('http://cosmos.bcst.yahoo.com/up/yep/process/getPlaylistFOP.php?node_id=' + video_id +
  881. '&tech=flash&mode=playlist&lg=' + yv_lg + '&bitrate=' + yv_bitrate + '&vidH=' + yv_video_height +
  882. '&vidW=' + yv_video_width + '&swf=as3&rd=video.yahoo.com&tk=null&adsupported=v1,v2,&eventid=1301797')
  883. try:
  884. self.report_download_webpage(video_id)
  885. webpage = compat_urllib_request.urlopen(request).read()
  886. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  887. self._downloader.report_error(u'Unable to retrieve video webpage: %s' % compat_str(err))
  888. return
  889. # Extract media URL from playlist XML
  890. mobj = re.search(r'<STREAM APP="(http://.*)" FULLPATH="/?(/.*\.flv\?[^"]*)"', webpage)
  891. if mobj is None:
  892. self._downloader.report_error(u'Unable to extract media URL')
  893. return
  894. video_url = compat_urllib_parse.unquote(mobj.group(1) + mobj.group(2)).decode('utf-8')
  895. video_url = unescapeHTML(video_url)
  896. return [{
  897. 'id': video_id.decode('utf-8'),
  898. 'url': video_url,
  899. 'uploader': video_uploader,
  900. 'upload_date': None,
  901. 'title': video_title,
  902. 'ext': video_extension.decode('utf-8'),
  903. 'thumbnail': video_thumbnail.decode('utf-8'),
  904. 'description': video_description,
  905. }]
  906. class VimeoIE(InfoExtractor):
  907. """Information extractor for vimeo.com."""
  908. # _VALID_URL matches Vimeo URLs
  909. _VALID_URL = r'(?P<proto>https?://)?(?:(?:www|player)\.)?vimeo\.com/(?:(?:groups|album)/[^/]+/)?(?P<direct_link>play_redirect_hls\?clip_id=)?(?:videos?/)?(?P<id>[0-9]+)'
  910. IE_NAME = u'vimeo'
  911. def __init__(self, downloader=None):
  912. InfoExtractor.__init__(self, downloader)
  913. def report_download_webpage(self, video_id):
  914. """Report webpage download."""
  915. self._downloader.to_screen(u'[vimeo] %s: Downloading webpage' % video_id)
  916. def report_extraction(self, video_id):
  917. """Report information extraction."""
  918. self._downloader.to_screen(u'[vimeo] %s: Extracting information' % video_id)
  919. def _real_extract(self, url, new_video=True):
  920. # Extract ID from URL
  921. mobj = re.match(self._VALID_URL, url)
  922. if mobj is None:
  923. self._downloader.report_error(u'Invalid URL: %s' % url)
  924. return
  925. video_id = mobj.group('id')
  926. if not mobj.group('proto'):
  927. url = 'https://' + url
  928. if mobj.group('direct_link'):
  929. url = 'https://vimeo.com/' + video_id
  930. # Retrieve video webpage to extract further information
  931. request = compat_urllib_request.Request(url, None, std_headers)
  932. try:
  933. self.report_download_webpage(video_id)
  934. webpage_bytes = compat_urllib_request.urlopen(request).read()
  935. webpage = webpage_bytes.decode('utf-8')
  936. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  937. self._downloader.report_error(u'Unable to retrieve video webpage: %s' % compat_str(err))
  938. return
  939. # Now we begin extracting as much information as we can from what we
  940. # retrieved. First we extract the information common to all extractors,
  941. # and latter we extract those that are Vimeo specific.
  942. self.report_extraction(video_id)
  943. # Extract the config JSON
  944. try:
  945. config = webpage.split(' = {config:')[1].split(',assets:')[0]
  946. config = json.loads(config)
  947. except:
  948. self._downloader.report_error(u'unable to extract info section')
  949. return
  950. # Extract title
  951. video_title = config["video"]["title"]
  952. # Extract uploader and uploader_id
  953. video_uploader = config["video"]["owner"]["name"]
  954. video_uploader_id = config["video"]["owner"]["url"].split('/')[-1]
  955. # Extract video thumbnail
  956. video_thumbnail = config["video"]["thumbnail"]
  957. # Extract video description
  958. video_description = get_element_by_attribute("itemprop", "description", webpage)
  959. if video_description: video_description = clean_html(video_description)
  960. else: video_description = ''
  961. # Extract upload date
  962. video_upload_date = None
  963. mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
  964. if mobj is not None:
  965. video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
  966. # Vimeo specific: extract request signature and timestamp
  967. sig = config['request']['signature']
  968. timestamp = config['request']['timestamp']
  969. # Vimeo specific: extract video codec and quality information
  970. # First consider quality, then codecs, then take everything
  971. # TODO bind to format param
  972. codecs = [('h264', 'mp4'), ('vp8', 'flv'), ('vp6', 'flv')]
  973. files = { 'hd': [], 'sd': [], 'other': []}
  974. for codec_name, codec_extension in codecs:
  975. if codec_name in config["video"]["files"]:
  976. if 'hd' in config["video"]["files"][codec_name]:
  977. files['hd'].append((codec_name, codec_extension, 'hd'))
  978. elif 'sd' in config["video"]["files"][codec_name]:
  979. files['sd'].append((codec_name, codec_extension, 'sd'))
  980. else:
  981. files['other'].append((codec_name, codec_extension, config["video"]["files"][codec_name][0]))
  982. for quality in ('hd', 'sd', 'other'):
  983. if len(files[quality]) > 0:
  984. video_quality = files[quality][0][2]
  985. video_codec = files[quality][0][0]
  986. video_extension = files[quality][0][1]
  987. self._downloader.to_screen(u'[vimeo] %s: Downloading %s file at %s quality' % (video_id, video_codec.upper(), video_quality))
  988. break
  989. else:
  990. self._downloader.report_error(u'no known codec found')
  991. return
  992. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  993. %(video_id, sig, timestamp, video_quality, video_codec.upper())
  994. return [{
  995. 'id': video_id,
  996. 'url': video_url,
  997. 'uploader': video_uploader,
  998. 'uploader_id': video_uploader_id,
  999. 'upload_date': video_upload_date,
  1000. 'title': video_title,
  1001. 'ext': video_extension,
  1002. 'thumbnail': video_thumbnail,
  1003. 'description': video_description,
  1004. }]
  1005. class ArteTvIE(InfoExtractor):
  1006. """arte.tv information extractor."""
  1007. _VALID_URL = r'(?:http://)?videos\.arte\.tv/(?:fr|de)/videos/.*'
  1008. _LIVE_URL = r'index-[0-9]+\.html$'
  1009. IE_NAME = u'arte.tv'
  1010. def __init__(self, downloader=None):
  1011. InfoExtractor.__init__(self, downloader)
  1012. def report_download_webpage(self, video_id):
  1013. """Report webpage download."""
  1014. self._downloader.to_screen(u'[arte.tv] %s: Downloading webpage' % video_id)
  1015. def report_extraction(self, video_id):
  1016. """Report information extraction."""
  1017. self._downloader.to_screen(u'[arte.tv] %s: Extracting information' % video_id)
  1018. def fetch_webpage(self, url):
  1019. request = compat_urllib_request.Request(url)
  1020. try:
  1021. self.report_download_webpage(url)
  1022. webpage = compat_urllib_request.urlopen(request).read()
  1023. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1024. self._downloader.report_error(u'Unable to retrieve video webpage: %s' % compat_str(err))
  1025. return
  1026. except ValueError as err:
  1027. self._downloader.report_error(u'Invalid URL: %s' % url)
  1028. return
  1029. return webpage
  1030. def grep_webpage(self, url, regex, regexFlags, matchTuples):
  1031. page = self.fetch_webpage(url)
  1032. mobj = re.search(regex, page, regexFlags)
  1033. info = {}
  1034. if mobj is None:
  1035. self._downloader.report_error(u'Invalid URL: %s' % url)
  1036. return
  1037. for (i, key, err) in matchTuples:
  1038. if mobj.group(i) is None:
  1039. self._downloader.trouble(err)
  1040. return
  1041. else:
  1042. info[key] = mobj.group(i)
  1043. return info
  1044. def extractLiveStream(self, url):
  1045. video_lang = url.split('/')[-4]
  1046. info = self.grep_webpage(
  1047. url,
  1048. r'src="(.*?/videothek_js.*?\.js)',
  1049. 0,
  1050. [
  1051. (1, 'url', u'ERROR: Invalid URL: %s' % url)
  1052. ]
  1053. )
  1054. http_host = url.split('/')[2]
  1055. next_url = 'http://%s%s' % (http_host, compat_urllib_parse.unquote(info.get('url')))
  1056. info = self.grep_webpage(
  1057. next_url,
  1058. r'(s_artestras_scst_geoFRDE_' + video_lang + '.*?)\'.*?' +
  1059. '(http://.*?\.swf).*?' +
  1060. '(rtmp://.*?)\'',
  1061. re.DOTALL,
  1062. [
  1063. (1, 'path', u'ERROR: could not extract video path: %s' % url),
  1064. (2, 'player', u'ERROR: could not extract video player: %s' % url),
  1065. (3, 'url', u'ERROR: could not extract video url: %s' % url)
  1066. ]
  1067. )
  1068. video_url = u'%s/%s' % (info.get('url'), info.get('path'))
  1069. def extractPlus7Stream(self, url):
  1070. video_lang = url.split('/')[-3]
  1071. info = self.grep_webpage(
  1072. url,
  1073. r'param name="movie".*?videorefFileUrl=(http[^\'"&]*)',
  1074. 0,
  1075. [
  1076. (1, 'url', u'ERROR: Invalid URL: %s' % url)
  1077. ]
  1078. )
  1079. next_url = compat_urllib_parse.unquote(info.get('url'))
  1080. info = self.grep_webpage(
  1081. next_url,
  1082. r'<video lang="%s" ref="(http[^\'"&]*)' % video_lang,
  1083. 0,
  1084. [
  1085. (1, 'url', u'ERROR: Could not find <video> tag: %s' % url)
  1086. ]
  1087. )
  1088. next_url = compat_urllib_parse.unquote(info.get('url'))
  1089. info = self.grep_webpage(
  1090. next_url,
  1091. r'<video id="(.*?)".*?>.*?' +
  1092. '<name>(.*?)</name>.*?' +
  1093. '<dateVideo>(.*?)</dateVideo>.*?' +
  1094. '<url quality="hd">(.*?)</url>',
  1095. re.DOTALL,
  1096. [
  1097. (1, 'id', u'ERROR: could not extract video id: %s' % url),
  1098. (2, 'title', u'ERROR: could not extract video title: %s' % url),
  1099. (3, 'date', u'ERROR: could not extract video date: %s' % url),
  1100. (4, 'url', u'ERROR: could not extract video url: %s' % url)
  1101. ]
  1102. )
  1103. return {
  1104. 'id': info.get('id'),
  1105. 'url': compat_urllib_parse.unquote(info.get('url')),
  1106. 'uploader': u'arte.tv',
  1107. 'upload_date': info.get('date'),
  1108. 'title': info.get('title').decode('utf-8'),
  1109. 'ext': u'mp4',
  1110. 'format': u'NA',
  1111. 'player_url': None,
  1112. }
  1113. def _real_extract(self, url):
  1114. video_id = url.split('/')[-1]
  1115. self.report_extraction(video_id)
  1116. if re.search(self._LIVE_URL, video_id) is not None:
  1117. self.extractLiveStream(url)
  1118. return
  1119. else:
  1120. info = self.extractPlus7Stream(url)
  1121. return [info]
  1122. class GenericIE(InfoExtractor):
  1123. """Generic last-resort information extractor."""
  1124. _VALID_URL = r'.*'
  1125. IE_NAME = u'generic'
  1126. def __init__(self, downloader=None):
  1127. InfoExtractor.__init__(self, downloader)
  1128. def report_download_webpage(self, video_id):
  1129. """Report webpage download."""
  1130. if not self._downloader.params.get('test', False):
  1131. self._downloader.to_screen(u'WARNING: Falling back on generic information extractor.')
  1132. self._downloader.to_screen(u'[generic] %s: Downloading webpage' % video_id)
  1133. def report_extraction(self, video_id):
  1134. """Report information extraction."""
  1135. self._downloader.to_screen(u'[generic] %s: Extracting information' % video_id)
  1136. def report_following_redirect(self, new_url):
  1137. """Report information extraction."""
  1138. self._downloader.to_screen(u'[redirect] Following redirect to %s' % new_url)
  1139. def _test_redirect(self, url):
  1140. """Check if it is a redirect, like url shorteners, in case restart chain."""
  1141. class HeadRequest(compat_urllib_request.Request):
  1142. def get_method(self):
  1143. return "HEAD"
  1144. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  1145. """
  1146. Subclass the HTTPRedirectHandler to make it use our
  1147. HeadRequest also on the redirected URL
  1148. """
  1149. def redirect_request(self, req, fp, code, msg, headers, newurl):
  1150. if code in (301, 302, 303, 307):
  1151. newurl = newurl.replace(' ', '%20')
  1152. newheaders = dict((k,v) for k,v in req.headers.items()
  1153. if k.lower() not in ("content-length", "content-type"))
  1154. return HeadRequest(newurl,
  1155. headers=newheaders,
  1156. origin_req_host=req.get_origin_req_host(),
  1157. unverifiable=True)
  1158. else:
  1159. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  1160. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  1161. """
  1162. Fallback to GET if HEAD is not allowed (405 HTTP error)
  1163. """
  1164. def http_error_405(self, req, fp, code, msg, headers):
  1165. fp.read()
  1166. fp.close()
  1167. newheaders = dict((k,v) for k,v in req.headers.items()
  1168. if k.lower() not in ("content-length", "content-type"))
  1169. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  1170. headers=newheaders,
  1171. origin_req_host=req.get_origin_req_host(),
  1172. unverifiable=True))
  1173. # Build our opener
  1174. opener = compat_urllib_request.OpenerDirector()
  1175. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  1176. HTTPMethodFallback, HEADRedirectHandler,
  1177. compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  1178. opener.add_handler(handler())
  1179. response = opener.open(HeadRequest(url))
  1180. new_url = response.geturl()
  1181. if url == new_url:
  1182. return False
  1183. self.report_following_redirect(new_url)
  1184. self._downloader.download([new_url])
  1185. return True
  1186. def _real_extract(self, url):
  1187. if self._test_redirect(url): return
  1188. video_id = url.split('/')[-1]
  1189. try:
  1190. webpage = self._download_webpage(url, video_id)
  1191. except ValueError as err:
  1192. # since this is the last-resort InfoExtractor, if
  1193. # this error is thrown, it'll be thrown here
  1194. self._downloader.report_error(u'Invalid URL: %s' % url)
  1195. return
  1196. self.report_extraction(video_id)
  1197. # Start with something easy: JW Player in SWFObject
  1198. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  1199. if mobj is None:
  1200. # Broaden the search a little bit
  1201. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  1202. if mobj is None:
  1203. # Broaden the search a little bit: JWPlayer JS loader
  1204. mobj = re.search(r'[^A-Za-z0-9]?file:\s*["\'](http[^\'"&]*)', webpage)
  1205. if mobj is None:
  1206. self._downloader.report_error(u'Invalid URL: %s' % url)
  1207. return
  1208. # It's possible that one of the regexes
  1209. # matched, but returned an empty group:
  1210. if mobj.group(1) is None:
  1211. self._downloader.report_error(u'Invalid URL: %s' % url)
  1212. return
  1213. video_url = compat_urllib_parse.unquote(mobj.group(1))
  1214. video_id = os.path.basename(video_url)
  1215. # here's a fun little line of code for you:
  1216. video_extension = os.path.splitext(video_id)[1][1:]
  1217. video_id = os.path.splitext(video_id)[0]
  1218. # it's tempting to parse this further, but you would
  1219. # have to take into account all the variations like
  1220. # Video Title - Site Name
  1221. # Site Name | Video Title
  1222. # Video Title - Tagline | Site Name
  1223. # and so on and so forth; it's just not practical
  1224. mobj = re.search(r'<title>(.*)</title>', webpage)
  1225. if mobj is None:
  1226. self._downloader.report_error(u'unable to extract title')
  1227. return
  1228. video_title = mobj.group(1)
  1229. # video uploader is domain name
  1230. mobj = re.match(r'(?:https?://)?([^/]*)/.*', url)
  1231. if mobj is None:
  1232. self._downloader.report_error(u'unable to extract title')
  1233. return
  1234. video_uploader = mobj.group(1)
  1235. return [{
  1236. 'id': video_id,
  1237. 'url': video_url,
  1238. 'uploader': video_uploader,
  1239. 'upload_date': None,
  1240. 'title': video_title,
  1241. 'ext': video_extension,
  1242. }]
  1243. class YoutubeSearchIE(InfoExtractor):
  1244. """Information Extractor for YouTube search queries."""
  1245. _VALID_URL = r'ytsearch(\d+|all)?:[\s\S]+'
  1246. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1247. _max_youtube_results = 1000
  1248. IE_NAME = u'youtube:search'
  1249. def __init__(self, downloader=None):
  1250. InfoExtractor.__init__(self, downloader)
  1251. def report_download_page(self, query, pagenum):
  1252. """Report attempt to download search page with given number."""
  1253. query = query.decode(preferredencoding())
  1254. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  1255. def _real_extract(self, query):
  1256. mobj = re.match(self._VALID_URL, query)
  1257. if mobj is None:
  1258. self._downloader.report_error(u'invalid search query "%s"' % query)
  1259. return
  1260. prefix, query = query.split(':')
  1261. prefix = prefix[8:]
  1262. query = query.encode('utf-8')
  1263. if prefix == '':
  1264. self._download_n_results(query, 1)
  1265. return
  1266. elif prefix == 'all':
  1267. self._download_n_results(query, self._max_youtube_results)
  1268. return
  1269. else:
  1270. try:
  1271. n = int(prefix)
  1272. if n <= 0:
  1273. self._downloader.report_error(u'invalid download number %s for query "%s"' % (n, query))
  1274. return
  1275. elif n > self._max_youtube_results:
  1276. self._downloader.report_warning(u'ytsearch returns max %i results (you requested %i)' % (self._max_youtube_results, n))
  1277. n = self._max_youtube_results
  1278. self._download_n_results(query, n)
  1279. return
  1280. except ValueError: # parsing prefix as integer fails
  1281. self._download_n_results(query, 1)
  1282. return
  1283. def _download_n_results(self, query, n):
  1284. """Downloads a specified number of results for a query"""
  1285. video_ids = []
  1286. pagenum = 0
  1287. limit = n
  1288. while (50 * pagenum) < limit:
  1289. self.report_download_page(query, pagenum+1)
  1290. result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
  1291. request = compat_urllib_request.Request(result_url)
  1292. try:
  1293. data = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1294. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1295. self._downloader.report_error(u'unable to download API page: %s' % compat_str(err))
  1296. return
  1297. api_response = json.loads(data)['data']
  1298. if not 'items' in api_response:
  1299. self._downloader.trouble(u'[youtube] No video results')
  1300. return
  1301. new_ids = list(video['id'] for video in api_response['items'])
  1302. video_ids += new_ids
  1303. limit = min(n, api_response['totalItems'])
  1304. pagenum += 1
  1305. if len(video_ids) > n:
  1306. video_ids = video_ids[:n]
  1307. for id in video_ids:
  1308. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1309. return
  1310. class GoogleSearchIE(InfoExtractor):
  1311. """Information Extractor for Google Video search queries."""
  1312. _VALID_URL = r'gvsearch(\d+|all)?:[\s\S]+'
  1313. _TEMPLATE_URL = 'http://video.google.com/videosearch?q=%s+site:video.google.com&start=%s&hl=en'
  1314. _VIDEO_INDICATOR = r'<a href="http://video\.google\.com/videoplay\?docid=([^"\&]+)'
  1315. _MORE_PAGES_INDICATOR = r'class="pn" id="pnnext"'
  1316. _max_google_results = 1000
  1317. IE_NAME = u'video.google:search'
  1318. def __init__(self, downloader=None):
  1319. InfoExtractor.__init__(self, downloader)
  1320. def report_download_page(self, query, pagenum):
  1321. """Report attempt to download playlist page with given number."""
  1322. query = query.decode(preferredencoding())
  1323. self._downloader.to_screen(u'[video.google] query "%s": Downloading page %s' % (query, pagenum))
  1324. def _real_extract(self, query):
  1325. mobj = re.match(self._VALID_URL, query)
  1326. if mobj is None:
  1327. self._downloader.report_error(u'invalid search query "%s"' % query)
  1328. return
  1329. prefix, query = query.split(':')
  1330. prefix = prefix[8:]
  1331. query = query.encode('utf-8')
  1332. if prefix == '':
  1333. self._download_n_results(query, 1)
  1334. return
  1335. elif prefix == 'all':
  1336. self._download_n_results(query, self._max_google_results)
  1337. return
  1338. else:
  1339. try:
  1340. n = int(prefix)
  1341. if n <= 0:
  1342. self._downloader.report_error(u'invalid download number %s for query "%s"' % (n, query))
  1343. return
  1344. elif n > self._max_google_results:
  1345. self._downloader.report_warning(u'gvsearch returns max %i results (you requested %i)' % (self._max_google_results, n))
  1346. n = self._max_google_results
  1347. self._download_n_results(query, n)
  1348. return
  1349. except ValueError: # parsing prefix as integer fails
  1350. self._download_n_results(query, 1)
  1351. return
  1352. def _download_n_results(self, query, n):
  1353. """Downloads a specified number of results for a query"""
  1354. video_ids = []
  1355. pagenum = 0
  1356. while True:
  1357. self.report_download_page(query, pagenum)
  1358. result_url = self._TEMPLATE_URL % (compat_urllib_parse.quote_plus(query), pagenum*10)
  1359. request = compat_urllib_request.Request(result_url)
  1360. try:
  1361. page = compat_urllib_request.urlopen(request).read()
  1362. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1363. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  1364. return
  1365. # Extract video identifiers
  1366. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1367. video_id = mobj.group(1)
  1368. if video_id not in video_ids:
  1369. video_ids.append(video_id)
  1370. if len(video_ids) == n:
  1371. # Specified n videos reached
  1372. for id in video_ids:
  1373. self._downloader.download(['http://video.google.com/videoplay?docid=%s' % id])
  1374. return
  1375. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1376. for id in video_ids:
  1377. self._downloader.download(['http://video.google.com/videoplay?docid=%s' % id])
  1378. return
  1379. pagenum = pagenum + 1
  1380. class YahooSearchIE(InfoExtractor):
  1381. """Information Extractor for Yahoo! Video search queries."""
  1382. _WORKING = False
  1383. _VALID_URL = r'yvsearch(\d+|all)?:[\s\S]+'
  1384. _TEMPLATE_URL = 'http://video.yahoo.com/search/?p=%s&o=%s'
  1385. _VIDEO_INDICATOR = r'href="http://video\.yahoo\.com/watch/([0-9]+/[0-9]+)"'
  1386. _MORE_PAGES_INDICATOR = r'\s*Next'
  1387. _max_yahoo_results = 1000
  1388. IE_NAME = u'video.yahoo:search'
  1389. def __init__(self, downloader=None):
  1390. InfoExtractor.__init__(self, downloader)
  1391. def report_download_page(self, query, pagenum):
  1392. """Report attempt to download playlist page with given number."""
  1393. query = query.decode(preferredencoding())
  1394. self._downloader.to_screen(u'[video.yahoo] query "%s": Downloading page %s' % (query, pagenum))
  1395. def _real_extract(self, query):
  1396. mobj = re.match(self._VALID_URL, query)
  1397. if mobj is None:
  1398. self._downloader.report_error(u'invalid search query "%s"' % query)
  1399. return
  1400. prefix, query = query.split(':')
  1401. prefix = prefix[8:]
  1402. query = query.encode('utf-8')
  1403. if prefix == '':
  1404. self._download_n_results(query, 1)
  1405. return
  1406. elif prefix == 'all':
  1407. self._download_n_results(query, self._max_yahoo_results)
  1408. return
  1409. else:
  1410. try:
  1411. n = int(prefix)
  1412. if n <= 0:
  1413. self._downloader.report_error(u'invalid download number %s for query "%s"' % (n, query))
  1414. return
  1415. elif n > self._max_yahoo_results:
  1416. self._downloader.report_warning(u'yvsearch returns max %i results (you requested %i)' % (self._max_yahoo_results, n))
  1417. n = self._max_yahoo_results
  1418. self._download_n_results(query, n)
  1419. return
  1420. except ValueError: # parsing prefix as integer fails
  1421. self._download_n_results(query, 1)
  1422. return
  1423. def _download_n_results(self, query, n):
  1424. """Downloads a specified number of results for a query"""
  1425. video_ids = []
  1426. already_seen = set()
  1427. pagenum = 1
  1428. while True:
  1429. self.report_download_page(query, pagenum)
  1430. result_url = self._TEMPLATE_URL % (compat_urllib_parse.quote_plus(query), pagenum)
  1431. request = compat_urllib_request.Request(result_url)
  1432. try:
  1433. page = compat_urllib_request.urlopen(request).read()
  1434. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1435. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  1436. return
  1437. # Extract video identifiers
  1438. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1439. video_id = mobj.group(1)
  1440. if video_id not in already_seen:
  1441. video_ids.append(video_id)
  1442. already_seen.add(video_id)
  1443. if len(video_ids) == n:
  1444. # Specified n videos reached
  1445. for id in video_ids:
  1446. self._downloader.download(['http://video.yahoo.com/watch/%s' % id])
  1447. return
  1448. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1449. for id in video_ids:
  1450. self._downloader.download(['http://video.yahoo.com/watch/%s' % id])
  1451. return
  1452. pagenum = pagenum + 1
  1453. class YoutubePlaylistIE(InfoExtractor):
  1454. """Information Extractor for YouTube playlists."""
  1455. _VALID_URL = r"""(?:
  1456. (?:https?://)?
  1457. (?:\w+\.)?
  1458. youtube\.com/
  1459. (?:
  1460. (?:course|view_play_list|my_playlists|artist|playlist|watch)
  1461. \? (?:.*?&)*? (?:p|a|list)=
  1462. | user/.*?/user/
  1463. | p/
  1464. | user/.*?#[pg]/c/
  1465. )
  1466. ((?:PL|EC|UU)?[0-9A-Za-z-_]{10,})
  1467. .*
  1468. |
  1469. ((?:PL|EC|UU)[0-9A-Za-z-_]{10,})
  1470. )"""
  1471. _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/playlists/%s?max-results=%i&start-index=%i&v=2&alt=json'
  1472. _MAX_RESULTS = 50
  1473. IE_NAME = u'youtube:playlist'
  1474. def __init__(self, downloader=None):
  1475. InfoExtractor.__init__(self, downloader)
  1476. @classmethod
  1477. def suitable(cls, url):
  1478. """Receives a URL and returns True if suitable for this IE."""
  1479. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1480. def report_download_page(self, playlist_id, pagenum):
  1481. """Report attempt to download playlist page with given number."""
  1482. self._downloader.to_screen(u'[youtube] PL %s: Downloading page #%s' % (playlist_id, pagenum))
  1483. def _real_extract(self, url):
  1484. # Extract playlist id
  1485. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1486. if mobj is None:
  1487. self._downloader.report_error(u'invalid url: %s' % url)
  1488. return
  1489. # Download playlist videos from API
  1490. playlist_id = mobj.group(1) or mobj.group(2)
  1491. page_num = 1
  1492. videos = []
  1493. while True:
  1494. self.report_download_page(playlist_id, page_num)
  1495. url = self._TEMPLATE_URL % (playlist_id, self._MAX_RESULTS, self._MAX_RESULTS * (page_num - 1) + 1)
  1496. try:
  1497. page = compat_urllib_request.urlopen(url).read().decode('utf8')
  1498. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1499. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  1500. return
  1501. try:
  1502. response = json.loads(page)
  1503. except ValueError as err:
  1504. self._downloader.report_error(u'Invalid JSON in API response: ' + compat_str(err))
  1505. return
  1506. if not 'feed' in response or not 'entry' in response['feed']:
  1507. self._downloader.report_error(u'Got a malformed response from YouTube API')
  1508. return
  1509. videos += [ (entry['yt$position']['$t'], entry['content']['src'])
  1510. for entry in response['feed']['entry']
  1511. if 'content' in entry ]
  1512. if len(response['feed']['entry']) < self._MAX_RESULTS:
  1513. break
  1514. page_num += 1
  1515. videos = [v[1] for v in sorted(videos)]
  1516. total = len(videos)
  1517. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1518. playlistend = self._downloader.params.get('playlistend', -1)
  1519. if playlistend == -1:
  1520. videos = videos[playliststart:]
  1521. else:
  1522. videos = videos[playliststart:playlistend]
  1523. if len(videos) == total:
  1524. self._downloader.to_screen(u'[youtube] PL %s: Found %i videos' % (playlist_id, total))
  1525. else:
  1526. self._downloader.to_screen(u'[youtube] PL %s: Found %i videos, downloading %i' % (playlist_id, total, len(videos)))
  1527. for video in videos:
  1528. self._downloader.download([video])
  1529. return
  1530. class YoutubeChannelIE(InfoExtractor):
  1531. """Information Extractor for YouTube channels."""
  1532. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)(?:/.*)?$"
  1533. _TEMPLATE_URL = 'http://www.youtube.com/channel/%s/videos?sort=da&flow=list&view=0&page=%s&gl=US&hl=en'
  1534. _MORE_PAGES_INDICATOR = u"Next \N{RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK}"
  1535. IE_NAME = u'youtube:channel'
  1536. def report_download_page(self, channel_id, pagenum):
  1537. """Report attempt to download channel page with given number."""
  1538. self._downloader.to_screen(u'[youtube] Channel %s: Downloading page #%s' % (channel_id, pagenum))
  1539. def _real_extract(self, url):
  1540. # Extract channel id
  1541. mobj = re.match(self._VALID_URL, url)
  1542. if mobj is None:
  1543. self._downloader.report_error(u'invalid url: %s' % url)
  1544. return
  1545. # Download channel pages
  1546. channel_id = mobj.group(1)
  1547. video_ids = []
  1548. pagenum = 1
  1549. while True:
  1550. self.report_download_page(channel_id, pagenum)
  1551. url = self._TEMPLATE_URL % (channel_id, pagenum)
  1552. request = compat_urllib_request.Request(url)
  1553. try:
  1554. page = compat_urllib_request.urlopen(request).read().decode('utf8')
  1555. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1556. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  1557. return
  1558. # Extract video identifiers
  1559. ids_in_page = []
  1560. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&', page):
  1561. if mobj.group(1) not in ids_in_page:
  1562. ids_in_page.append(mobj.group(1))
  1563. video_ids.extend(ids_in_page)
  1564. if self._MORE_PAGES_INDICATOR not in page:
  1565. break
  1566. pagenum = pagenum + 1
  1567. self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  1568. for id in video_ids:
  1569. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1570. return
  1571. class YoutubeUserIE(InfoExtractor):
  1572. """Information Extractor for YouTube users."""
  1573. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
  1574. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  1575. _GDATA_PAGE_SIZE = 50
  1576. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
  1577. _VIDEO_INDICATOR = r'/watch\?v=(.+?)[\<&]'
  1578. IE_NAME = u'youtube:user'
  1579. def __init__(self, downloader=None):
  1580. InfoExtractor.__init__(self, downloader)
  1581. def report_download_page(self, username, start_index):
  1582. """Report attempt to download user page."""
  1583. self._downloader.to_screen(u'[youtube] user %s: Downloading video ids from %d to %d' %
  1584. (username, start_index, start_index + self._GDATA_PAGE_SIZE))
  1585. def _real_extract(self, url):
  1586. # Extract username
  1587. mobj = re.match(self._VALID_URL, url)
  1588. if mobj is None:
  1589. self._downloader.report_error(u'invalid url: %s' % url)
  1590. return
  1591. username = mobj.group(1)
  1592. # Download video ids using YouTube Data API. Result size per
  1593. # query is limited (currently to 50 videos) so we need to query
  1594. # page by page until there are no video ids - it means we got
  1595. # all of them.
  1596. video_ids = []
  1597. pagenum = 0
  1598. while True:
  1599. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1600. self.report_download_page(username, start_index)
  1601. request = compat_urllib_request.Request(self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index))
  1602. try:
  1603. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1604. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1605. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  1606. return
  1607. # Extract video identifiers
  1608. ids_in_page = []
  1609. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1610. if mobj.group(1) not in ids_in_page:
  1611. ids_in_page.append(mobj.group(1))
  1612. video_ids.extend(ids_in_page)
  1613. # A little optimization - if current page is not
  1614. # "full", ie. does not contain PAGE_SIZE video ids then
  1615. # we can assume that this page is the last one - there
  1616. # are no more ids on further pages - no need to query
  1617. # again.
  1618. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  1619. break
  1620. pagenum += 1
  1621. all_ids_count = len(video_ids)
  1622. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1623. playlistend = self._downloader.params.get('playlistend', -1)
  1624. if playlistend == -1:
  1625. video_ids = video_ids[playliststart:]
  1626. else:
  1627. video_ids = video_ids[playliststart:playlistend]
  1628. self._downloader.to_screen(u"[youtube] user %s: Collected %d video ids (downloading %d of them)" %
  1629. (username, all_ids_count, len(video_ids)))
  1630. for video_id in video_ids:
  1631. self._downloader.download(['http://www.youtube.com/watch?v=%s' % video_id])
  1632. class BlipTVUserIE(InfoExtractor):
  1633. """Information Extractor for blip.tv users."""
  1634. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
  1635. _PAGE_SIZE = 12
  1636. IE_NAME = u'blip.tv:user'
  1637. def __init__(self, downloader=None):
  1638. InfoExtractor.__init__(self, downloader)
  1639. def report_download_page(self, username, pagenum):
  1640. """Report attempt to download user page."""
  1641. self._downloader.to_screen(u'[%s] user %s: Downloading video ids from page %d' %
  1642. (self.IE_NAME, username, pagenum))
  1643. def _real_extract(self, url):
  1644. # Extract username
  1645. mobj = re.match(self._VALID_URL, url)
  1646. if mobj is None:
  1647. self._downloader.report_error(u'invalid url: %s' % url)
  1648. return
  1649. username = mobj.group(1)
  1650. page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
  1651. request = compat_urllib_request.Request(url)
  1652. try:
  1653. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1654. mobj = re.search(r'data-users-id="([^"]+)"', page)
  1655. page_base = page_base % mobj.group(1)
  1656. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1657. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  1658. return
  1659. # Download video ids using BlipTV Ajax calls. Result size per
  1660. # query is limited (currently to 12 videos) so we need to query
  1661. # page by page until there are no video ids - it means we got
  1662. # all of them.
  1663. video_ids = []
  1664. pagenum = 1
  1665. while True:
  1666. self.report_download_page(username, pagenum)
  1667. url = page_base + "&page=" + str(pagenum)
  1668. request = compat_urllib_request.Request( url )
  1669. try:
  1670. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1671. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1672. self._downloader.report_error(u'unable to download webpage: %s' % str(err))
  1673. return
  1674. # Extract video identifiers
  1675. ids_in_page = []
  1676. for mobj in re.finditer(r'href="/([^"]+)"', page):
  1677. if mobj.group(1) not in ids_in_page:
  1678. ids_in_page.append(unescapeHTML(mobj.group(1)))
  1679. video_ids.extend(ids_in_page)
  1680. # A little optimization - if current page is not
  1681. # "full", ie. does not contain PAGE_SIZE video ids then
  1682. # we can assume that this page is the last one - there
  1683. # are no more ids on further pages - no need to query
  1684. # again.
  1685. if len(ids_in_page) < self._PAGE_SIZE:
  1686. break
  1687. pagenum += 1
  1688. all_ids_count = len(video_ids)
  1689. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1690. playlistend = self._downloader.params.get('playlistend', -1)
  1691. if playlistend == -1:
  1692. video_ids = video_ids[playliststart:]
  1693. else:
  1694. video_ids = video_ids[playliststart:playlistend]
  1695. self._downloader.to_screen(u"[%s] user %s: Collected %d video ids (downloading %d of them)" %
  1696. (self.IE_NAME, username, all_ids_count, len(video_ids)))
  1697. for video_id in video_ids:
  1698. self._downloader.download([u'http://blip.tv/'+video_id])
  1699. class DepositFilesIE(InfoExtractor):
  1700. """Information extractor for depositfiles.com"""
  1701. _VALID_URL = r'(?:http://)?(?:\w+\.)?depositfiles\.com/(?:../(?#locale))?files/(.+)'
  1702. def report_download_webpage(self, file_id):
  1703. """Report webpage download."""
  1704. self._downloader.to_screen(u'[DepositFiles] %s: Downloading webpage' % file_id)
  1705. def report_extraction(self, file_id):
  1706. """Report information extraction."""
  1707. self._downloader.to_screen(u'[DepositFiles] %s: Extracting information' % file_id)
  1708. def _real_extract(self, url):
  1709. file_id = url.split('/')[-1]
  1710. # Rebuild url in english locale
  1711. url = 'http://depositfiles.com/en/files/' + file_id
  1712. # Retrieve file webpage with 'Free download' button pressed
  1713. free_download_indication = { 'gateway_result' : '1' }
  1714. request = compat_urllib_request.Request(url, compat_urllib_parse.urlencode(free_download_indication))
  1715. try:
  1716. self.report_download_webpage(file_id)
  1717. webpage = compat_urllib_request.urlopen(request).read()
  1718. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1719. self._downloader.report_error(u'Unable to retrieve file webpage: %s' % compat_str(err))
  1720. return
  1721. # Search for the real file URL
  1722. mobj = re.search(r'<form action="(http://fileshare.+?)"', webpage)
  1723. if (mobj is None) or (mobj.group(1) is None):
  1724. # Try to figure out reason of the error.
  1725. mobj = re.search(r'<strong>(Attention.*?)</strong>', webpage, re.DOTALL)
  1726. if (mobj is not None) and (mobj.group(1) is not None):
  1727. restriction_message = re.sub('\s+', ' ', mobj.group(1)).strip()
  1728. self._downloader.report_error(u'%s' % restriction_message)
  1729. else:
  1730. self._downloader.report_error(u'unable to extract download URL from: %s' % url)
  1731. return
  1732. file_url = mobj.group(1)
  1733. file_extension = os.path.splitext(file_url)[1][1:]
  1734. # Search for file title
  1735. mobj = re.search(r'<b title="(.*?)">', webpage)
  1736. if mobj is None:
  1737. self._downloader.report_error(u'unable to extract title')
  1738. return
  1739. file_title = mobj.group(1).decode('utf-8')
  1740. return [{
  1741. 'id': file_id.decode('utf-8'),
  1742. 'url': file_url.decode('utf-8'),
  1743. 'uploader': None,
  1744. 'upload_date': None,
  1745. 'title': file_title,
  1746. 'ext': file_extension.decode('utf-8'),
  1747. }]
  1748. class FacebookIE(InfoExtractor):
  1749. """Information Extractor for Facebook"""
  1750. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?facebook\.com/(?:video/video|photo)\.php\?(?:.*?)v=(?P<ID>\d+)(?:.*)'
  1751. _LOGIN_URL = 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php&'
  1752. _NETRC_MACHINE = 'facebook'
  1753. IE_NAME = u'facebook'
  1754. def report_login(self):
  1755. """Report attempt to log in."""
  1756. self._downloader.to_screen(u'[%s] Logging in' % self.IE_NAME)
  1757. def _real_initialize(self):
  1758. if self._downloader is None:
  1759. return
  1760. useremail = None
  1761. password = None
  1762. downloader_params = self._downloader.params
  1763. # Attempt to use provided username and password or .netrc data
  1764. if downloader_params.get('username', None) is not None:
  1765. useremail = downloader_params['username']
  1766. password = downloader_params['password']
  1767. elif downloader_params.get('usenetrc', False):
  1768. try:
  1769. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  1770. if info is not None:
  1771. useremail = info[0]
  1772. password = info[2]
  1773. else:
  1774. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  1775. except (IOError, netrc.NetrcParseError) as err:
  1776. self._downloader.report_warning(u'parsing .netrc: %s' % compat_str(err))
  1777. return
  1778. if useremail is None:
  1779. return
  1780. # Log in
  1781. login_form = {
  1782. 'email': useremail,
  1783. 'pass': password,
  1784. 'login': 'Log+In'
  1785. }
  1786. request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
  1787. try:
  1788. self.report_login()
  1789. login_results = compat_urllib_request.urlopen(request).read()
  1790. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  1791. self._downloader.report_warning(u'unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  1792. return
  1793. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1794. self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
  1795. return
  1796. def _real_extract(self, url):
  1797. mobj = re.match(self._VALID_URL, url)
  1798. if mobj is None:
  1799. self._downloader.report_error(u'invalid URL: %s' % url)
  1800. return
  1801. video_id = mobj.group('ID')
  1802. url = 'https://www.facebook.com/video/video.php?v=%s' % video_id
  1803. webpage = self._download_webpage(url, video_id)
  1804. BEFORE = '[["allowFullScreen","true"],["allowScriptAccess","always"],["salign","tl"],["scale","noscale"],["wmode","opaque"]].forEach(function(param) {swf.addParam(param[0], param[1]);});\n'
  1805. AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
  1806. m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
  1807. if not m:
  1808. raise ExtractorError(u'Cannot parse data')
  1809. data = dict(json.loads(m.group(1)))
  1810. params_raw = compat_urllib_parse.unquote(data['params'])
  1811. params = json.loads(params_raw)
  1812. video_url = params['hd_src']
  1813. if not video_url:
  1814. video_url = params['sd_src']
  1815. if not video_url:
  1816. raise ExtractorError(u'Cannot find video URL')
  1817. video_duration = int(params['video_duration'])
  1818. m = re.search('<h2 class="uiHeaderTitle">([^<]+)</h2>', webpage)
  1819. if not m:
  1820. raise ExtractorError(u'Cannot find title in webpage')
  1821. video_title = unescapeHTML(m.group(1))
  1822. info = {
  1823. 'id': video_id,
  1824. 'title': video_title,
  1825. 'url': video_url,
  1826. 'ext': 'mp4',
  1827. 'duration': video_duration,
  1828. 'thumbnail': params['thumbnail_src'],
  1829. }
  1830. return [info]
  1831. class BlipTVIE(InfoExtractor):
  1832. """Information extractor for blip.tv"""
  1833. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?blip\.tv(/.+)$'
  1834. _URL_EXT = r'^.*\.([a-z0-9]+)$'
  1835. IE_NAME = u'blip.tv'
  1836. def report_extraction(self, file_id):
  1837. """Report information extraction."""
  1838. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  1839. def report_direct_download(self, title):
  1840. """Report information extraction."""
  1841. self._downloader.to_screen(u'[%s] %s: Direct download detected' % (self.IE_NAME, title))
  1842. def _real_extract(self, url):
  1843. mobj = re.match(self._VALID_URL, url)
  1844. if mobj is None:
  1845. self._downloader.report_error(u'invalid URL: %s' % url)
  1846. return
  1847. urlp = compat_urllib_parse_urlparse(url)
  1848. if urlp.path.startswith('/play/'):
  1849. request = compat_urllib_request.Request(url)
  1850. response = compat_urllib_request.urlopen(request)
  1851. redirecturl = response.geturl()
  1852. rurlp = compat_urllib_parse_urlparse(redirecturl)
  1853. file_id = compat_parse_qs(rurlp.fragment)['file'][0].rpartition('/')[2]
  1854. url = 'http://blip.tv/a/a-' + file_id
  1855. return self._real_extract(url)
  1856. if '?' in url:
  1857. cchar = '&'
  1858. else:
  1859. cchar = '?'
  1860. json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
  1861. request = compat_urllib_request.Request(json_url)
  1862. request.add_header('User-Agent', 'iTunes/10.6.1')
  1863. self.report_extraction(mobj.group(1))
  1864. info = None
  1865. try:
  1866. urlh = compat_urllib_request.urlopen(request)
  1867. if urlh.headers.get('Content-Type', '').startswith('video/'): # Direct download
  1868. basename = url.split('/')[-1]
  1869. title,ext = os.path.splitext(basename)
  1870. title = title.decode('UTF-8')
  1871. ext = ext.replace('.', '')
  1872. self.report_direct_download(title)
  1873. info = {
  1874. 'id': title,
  1875. 'url': url,
  1876. 'uploader': None,
  1877. 'upload_date': None,
  1878. 'title': title,
  1879. 'ext': ext,
  1880. 'urlhandle': urlh
  1881. }
  1882. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1883. raise ExtractorError(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
  1884. if info is None: # Regular URL
  1885. try:
  1886. json_code_bytes = urlh.read()
  1887. json_code = json_code_bytes.decode('utf-8')
  1888. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1889. self._downloader.report_error(u'unable to read video info webpage: %s' % compat_str(err))
  1890. return
  1891. try:
  1892. json_data = json.loads(json_code)
  1893. if 'Post' in json_data:
  1894. data = json_data['Post']
  1895. else:
  1896. data = json_data
  1897. upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
  1898. video_url = data['media']['url']
  1899. umobj = re.match(self._URL_EXT, video_url)
  1900. if umobj is None:
  1901. raise ValueError('Can not determine filename extension')
  1902. ext = umobj.group(1)
  1903. info = {
  1904. 'id': data['item_id'],
  1905. 'url': video_url,
  1906. 'uploader': data['display_name'],
  1907. 'upload_date': upload_date,
  1908. 'title': data['title'],
  1909. 'ext': ext,
  1910. 'format': data['media']['mimeType'],
  1911. 'thumbnail': data['thumbnailUrl'],
  1912. 'description': data['description'],
  1913. 'player_url': data['embedUrl'],
  1914. 'user_agent': 'iTunes/10.6.1',
  1915. }
  1916. except (ValueError,KeyError) as err:
  1917. self._downloader.report_error(u'unable to parse video information: %s' % repr(err))
  1918. return
  1919. return [info]
  1920. class MyVideoIE(InfoExtractor):
  1921. """Information Extractor for myvideo.de."""
  1922. _VALID_URL = r'(?:http://)?(?:www\.)?myvideo\.de/watch/([0-9]+)/([^?/]+).*'
  1923. IE_NAME = u'myvideo'
  1924. def __init__(self, downloader=None):
  1925. InfoExtractor.__init__(self, downloader)
  1926. def report_extraction(self, video_id):
  1927. """Report information extraction."""
  1928. self._downloader.to_screen(u'[myvideo] %s: Extracting information' % video_id)
  1929. def _real_extract(self,url):
  1930. mobj = re.match(self._VALID_URL, url)
  1931. if mobj is None:
  1932. self._download.report_error(u'invalid URL: %s' % url)
  1933. return
  1934. video_id = mobj.group(1)
  1935. # Get video webpage
  1936. webpage_url = 'http://www.myvideo.de/watch/%s' % video_id
  1937. webpage = self._download_webpage(webpage_url, video_id)
  1938. self.report_extraction(video_id)
  1939. mobj = re.search(r'<link rel=\'image_src\' href=\'(http://is[0-9].myvideo\.de/de/movie[0-9]+/[a-f0-9]+)/thumbs/.*?\.jpg\'',
  1940. webpage)
  1941. if mobj is None:
  1942. self._downloader.report_error(u'unable to extract media URL')
  1943. return
  1944. video_url = mobj.group(1) + ('/%s.flv' % video_id)
  1945. mobj = re.search('<title>([^<]+)</title>', webpage)
  1946. if mobj is None:
  1947. self._downloader.report_error(u'unable to extract title')
  1948. return
  1949. video_title = mobj.group(1)
  1950. return [{
  1951. 'id': video_id,
  1952. 'url': video_url,
  1953. 'uploader': None,
  1954. 'upload_date': None,
  1955. 'title': video_title,
  1956. 'ext': u'flv',
  1957. }]
  1958. class ComedyCentralIE(InfoExtractor):
  1959. """Information extractor for The Daily Show and Colbert Report """
  1960. # urls can be abbreviations like :thedailyshow or :colbert
  1961. # urls for episodes like:
  1962. # or urls for clips like: http://www.thedailyshow.com/watch/mon-december-10-2012/any-given-gun-day
  1963. # or: http://www.colbertnation.com/the-colbert-report-videos/421667/november-29-2012/moon-shattering-news
  1964. # or: http://www.colbertnation.com/the-colbert-report-collections/422008/festival-of-lights/79524
  1965. _VALID_URL = r"""^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport)
  1966. |(https?://)?(www\.)?
  1967. (?P<showname>thedailyshow|colbertnation)\.com/
  1968. (full-episodes/(?P<episode>.*)|
  1969. (?P<clip>
  1970. (the-colbert-report-(videos|collections)/(?P<clipID>[0-9]+)/[^/]*/(?P<cntitle>.*?))
  1971. |(watch/(?P<date>[^/]*)/(?P<tdstitle>.*)))))
  1972. $"""
  1973. _available_formats = ['3500', '2200', '1700', '1200', '750', '400']
  1974. _video_extensions = {
  1975. '3500': 'mp4',
  1976. '2200': 'mp4',
  1977. '1700': 'mp4',
  1978. '1200': 'mp4',
  1979. '750': 'mp4',
  1980. '400': 'mp4',
  1981. }
  1982. _video_dimensions = {
  1983. '3500': '1280x720',
  1984. '2200': '960x540',
  1985. '1700': '768x432',
  1986. '1200': '640x360',
  1987. '750': '512x288',
  1988. '400': '384x216',
  1989. }
  1990. @classmethod
  1991. def suitable(cls, url):
  1992. """Receives a URL and returns True if suitable for this IE."""
  1993. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1994. def report_extraction(self, episode_id):
  1995. self._downloader.to_screen(u'[comedycentral] %s: Extracting information' % episode_id)
  1996. def report_config_download(self, episode_id, media_id):
  1997. self._downloader.to_screen(u'[comedycentral] %s: Downloading configuration for %s' % (episode_id, media_id))
  1998. def report_index_download(self, episode_id):
  1999. self._downloader.to_screen(u'[comedycentral] %s: Downloading show index' % episode_id)
  2000. def _print_formats(self, formats):
  2001. print('Available formats:')
  2002. for x in formats:
  2003. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'mp4'), self._video_dimensions.get(x, '???')))
  2004. def _real_extract(self, url):
  2005. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  2006. if mobj is None:
  2007. self._downloader.report_error(u'invalid URL: %s' % url)
  2008. return
  2009. if mobj.group('shortname'):
  2010. if mobj.group('shortname') in ('tds', 'thedailyshow'):
  2011. url = u'http://www.thedailyshow.com/full-episodes/'
  2012. else:
  2013. url = u'http://www.colbertnation.com/full-episodes/'
  2014. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  2015. assert mobj is not None
  2016. if mobj.group('clip'):
  2017. if mobj.group('showname') == 'thedailyshow':
  2018. epTitle = mobj.group('tdstitle')
  2019. else:
  2020. epTitle = mobj.group('cntitle')
  2021. dlNewest = False
  2022. else:
  2023. dlNewest = not mobj.group('episode')
  2024. if dlNewest:
  2025. epTitle = mobj.group('showname')
  2026. else:
  2027. epTitle = mobj.group('episode')
  2028. req = compat_urllib_request.Request(url)
  2029. self.report_extraction(epTitle)
  2030. try:
  2031. htmlHandle = compat_urllib_request.urlopen(req)
  2032. html = htmlHandle.read()
  2033. webpage = html.decode('utf-8')
  2034. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2035. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  2036. return
  2037. if dlNewest:
  2038. url = htmlHandle.geturl()
  2039. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  2040. if mobj is None:
  2041. self._downloader.report_error(u'Invalid redirected URL: ' + url)
  2042. return
  2043. if mobj.group('episode') == '':
  2044. self._downloader.report_error(u'Redirected URL is still not specific: ' + url)
  2045. return
  2046. epTitle = mobj.group('episode')
  2047. mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', webpage)
  2048. if len(mMovieParams) == 0:
  2049. # The Colbert Report embeds the information in a without
  2050. # a URL prefix; so extract the alternate reference
  2051. # and then add the URL prefix manually.
  2052. altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video).*?:.*?)"', webpage)
  2053. if len(altMovieParams) == 0:
  2054. self._downloader.report_error(u'unable to find Flash URL in webpage ' + url)
  2055. return
  2056. else:
  2057. mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
  2058. uri = mMovieParams[0][1]
  2059. indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + compat_urllib_parse.urlencode({'uri': uri})
  2060. self.report_index_download(epTitle)
  2061. try:
  2062. indexXml = compat_urllib_request.urlopen(indexUrl).read()
  2063. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2064. self._downloader.report_error(u'unable to download episode index: ' + compat_str(err))
  2065. return
  2066. results = []
  2067. idoc = xml.etree.ElementTree.fromstring(indexXml)
  2068. itemEls = idoc.findall('.//item')
  2069. for partNum,itemEl in enumerate(itemEls):
  2070. mediaId = itemEl.findall('./guid')[0].text
  2071. shortMediaId = mediaId.split(':')[-1]
  2072. showId = mediaId.split(':')[-2].replace('.com', '')
  2073. officialTitle = itemEl.findall('./title')[0].text
  2074. officialDate = itemEl.findall('./pubDate')[0].text
  2075. configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
  2076. compat_urllib_parse.urlencode({'uri': mediaId}))
  2077. configReq = compat_urllib_request.Request(configUrl)
  2078. self.report_config_download(epTitle, shortMediaId)
  2079. try:
  2080. configXml = compat_urllib_request.urlopen(configReq).read()
  2081. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2082. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  2083. return
  2084. cdoc = xml.etree.ElementTree.fromstring(configXml)
  2085. turls = []
  2086. for rendition in cdoc.findall('.//rendition'):
  2087. finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
  2088. turls.append(finfo)
  2089. if len(turls) == 0:
  2090. self._downloader.report_error(u'unable to download ' + mediaId + ': No videos found')
  2091. continue
  2092. if self._downloader.params.get('listformats', None):
  2093. self._print_formats([i[0] for i in turls])
  2094. return
  2095. # For now, just pick the highest bitrate
  2096. format,rtmp_video_url = turls[-1]
  2097. # Get the format arg from the arg stream
  2098. req_format = self._downloader.params.get('format', None)
  2099. # Select format if we can find one
  2100. for f,v in turls:
  2101. if f == req_format:
  2102. format, rtmp_video_url = f, v
  2103. break
  2104. m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp.comedystor/.*)$', rtmp_video_url)
  2105. if not m:
  2106. raise ExtractorError(u'Cannot transform RTMP url')
  2107. base = 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=1+_pxI0=Ripod-h264+_pxL0=undefined+_pxM0=+_pxK=18639+_pxE=mp4/44620/mtvnorigin/'
  2108. video_url = base + m.group('finalid')
  2109. effTitle = showId + u'-' + epTitle + u' part ' + compat_str(partNum+1)
  2110. info = {
  2111. 'id': shortMediaId,
  2112. 'url': video_url,
  2113. 'uploader': showId,
  2114. 'upload_date': officialDate,
  2115. 'title': effTitle,
  2116. 'ext': 'mp4',
  2117. 'format': format,
  2118. 'thumbnail': None,
  2119. 'description': officialTitle,
  2120. }
  2121. results.append(info)
  2122. return results
  2123. class EscapistIE(InfoExtractor):
  2124. """Information extractor for The Escapist """
  2125. _VALID_URL = r'^(https?://)?(www\.)?escapistmagazine\.com/videos/view/(?P<showname>[^/]+)/(?P<episode>[^/?]+)[/?]?.*$'
  2126. IE_NAME = u'escapist'
  2127. def report_extraction(self, showName):
  2128. self._downloader.to_screen(u'[escapist] %s: Extracting information' % showName)
  2129. def report_config_download(self, showName):
  2130. self._downloader.to_screen(u'[escapist] %s: Downloading configuration' % showName)
  2131. def _real_extract(self, url):
  2132. mobj = re.match(self._VALID_URL, url)
  2133. if mobj is None:
  2134. self._downloader.report_error(u'invalid URL: %s' % url)
  2135. return
  2136. showName = mobj.group('showname')
  2137. videoId = mobj.group('episode')
  2138. self.report_extraction(showName)
  2139. try:
  2140. webPage = compat_urllib_request.urlopen(url)
  2141. webPageBytes = webPage.read()
  2142. m = re.match(r'text/html; charset="?([^"]+)"?', webPage.headers['Content-Type'])
  2143. webPage = webPageBytes.decode(m.group(1) if m else 'utf-8')
  2144. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2145. self._downloader.report_error(u'unable to download webpage: ' + compat_str(err))
  2146. return
  2147. descMatch = re.search('<meta name="description" content="([^"]*)"', webPage)
  2148. description = unescapeHTML(descMatch.group(1))
  2149. imgMatch = re.search('<meta property="og:image" content="([^"]*)"', webPage)
  2150. imgUrl = unescapeHTML(imgMatch.group(1))
  2151. playerUrlMatch = re.search('<meta property="og:video" content="([^"]*)"', webPage)
  2152. playerUrl = unescapeHTML(playerUrlMatch.group(1))
  2153. configUrlMatch = re.search('config=(.*)$', playerUrl)
  2154. configUrl = compat_urllib_parse.unquote(configUrlMatch.group(1))
  2155. self.report_config_download(showName)
  2156. try:
  2157. configJSON = compat_urllib_request.urlopen(configUrl)
  2158. m = re.match(r'text/html; charset="?([^"]+)"?', configJSON.headers['Content-Type'])
  2159. configJSON = configJSON.read().decode(m.group(1) if m else 'utf-8')
  2160. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2161. self._downloader.report_error(u'unable to download configuration: ' + compat_str(err))
  2162. return
  2163. # Technically, it's JavaScript, not JSON
  2164. configJSON = configJSON.replace("'", '"')
  2165. try:
  2166. config = json.loads(configJSON)
  2167. except (ValueError,) as err:
  2168. self._downloader.report_error(u'Invalid JSON in configuration file: ' + compat_str(err))
  2169. return
  2170. playlist = config['playlist']
  2171. videoUrl = playlist[1]['url']
  2172. info = {
  2173. 'id': videoId,
  2174. 'url': videoUrl,
  2175. 'uploader': showName,
  2176. 'upload_date': None,
  2177. 'title': showName,
  2178. 'ext': 'mp4',
  2179. 'thumbnail': imgUrl,
  2180. 'description': description,
  2181. 'player_url': playerUrl,
  2182. }
  2183. return [info]
  2184. class CollegeHumorIE(InfoExtractor):
  2185. """Information extractor for collegehumor.com"""
  2186. _WORKING = False
  2187. _VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/video/(?P<videoid>[0-9]+)/(?P<shorttitle>.*)$'
  2188. IE_NAME = u'collegehumor'
  2189. def report_manifest(self, video_id):
  2190. """Report information extraction."""
  2191. self._downloader.to_screen(u'[%s] %s: Downloading XML manifest' % (self.IE_NAME, video_id))
  2192. def report_extraction(self, video_id):
  2193. """Report information extraction."""
  2194. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2195. def _real_extract(self, url):
  2196. mobj = re.match(self._VALID_URL, url)
  2197. if mobj is None:
  2198. self._downloader.report_error(u'invalid URL: %s' % url)
  2199. return
  2200. video_id = mobj.group('videoid')
  2201. info = {
  2202. 'id': video_id,
  2203. 'uploader': None,
  2204. 'upload_date': None,
  2205. }
  2206. self.report_extraction(video_id)
  2207. xmlUrl = 'http://www.collegehumor.com/moogaloop/video/' + video_id
  2208. try:
  2209. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  2210. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2211. self._downloader.report_error(u'unable to download video info XML: %s' % compat_str(err))
  2212. return
  2213. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2214. try:
  2215. videoNode = mdoc.findall('./video')[0]
  2216. info['description'] = videoNode.findall('./description')[0].text
  2217. info['title'] = videoNode.findall('./caption')[0].text
  2218. info['thumbnail'] = videoNode.findall('./thumbnail')[0].text
  2219. manifest_url = videoNode.findall('./file')[0].text
  2220. except IndexError:
  2221. self._downloader.report_error(u'Invalid metadata XML file')
  2222. return
  2223. manifest_url += '?hdcore=2.10.3'
  2224. self.report_manifest(video_id)
  2225. try:
  2226. manifestXml = compat_urllib_request.urlopen(manifest_url).read()
  2227. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2228. self._downloader.report_error(u'unable to download video info XML: %s' % compat_str(err))
  2229. return
  2230. adoc = xml.etree.ElementTree.fromstring(manifestXml)
  2231. try:
  2232. media_node = adoc.findall('./{http://ns.adobe.com/f4m/1.0}media')[0]
  2233. node_id = media_node.attrib['url']
  2234. video_id = adoc.findall('./{http://ns.adobe.com/f4m/1.0}id')[0].text
  2235. except IndexError as err:
  2236. self._downloader.report_error(u'Invalid manifest file')
  2237. return
  2238. url_pr = compat_urllib_parse_urlparse(manifest_url)
  2239. url = url_pr.scheme + '://' + url_pr.netloc + '/z' + video_id[:-2] + '/' + node_id + 'Seg1-Frag1'
  2240. info['url'] = url
  2241. info['ext'] = 'f4f'
  2242. return [info]
  2243. class XVideosIE(InfoExtractor):
  2244. """Information extractor for xvideos.com"""
  2245. _VALID_URL = r'^(?:https?://)?(?:www\.)?xvideos\.com/video([0-9]+)(?:.*)'
  2246. IE_NAME = u'xvideos'
  2247. def report_extraction(self, video_id):
  2248. """Report information extraction."""
  2249. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2250. def _real_extract(self, url):
  2251. mobj = re.match(self._VALID_URL, url)
  2252. if mobj is None:
  2253. self._downloader.report_error(u'invalid URL: %s' % url)
  2254. return
  2255. video_id = mobj.group(1)
  2256. webpage = self._download_webpage(url, video_id)
  2257. self.report_extraction(video_id)
  2258. # Extract video URL
  2259. mobj = re.search(r'flv_url=(.+?)&', webpage)
  2260. if mobj is None:
  2261. self._downloader.report_error(u'unable to extract video url')
  2262. return
  2263. video_url = compat_urllib_parse.unquote(mobj.group(1))
  2264. # Extract title
  2265. mobj = re.search(r'<title>(.*?)\s+-\s+XVID', webpage)
  2266. if mobj is None:
  2267. self._downloader.report_error(u'unable to extract video title')
  2268. return
  2269. video_title = mobj.group(1)
  2270. # Extract video thumbnail
  2271. mobj = re.search(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)', webpage)
  2272. if mobj is None:
  2273. self._downloader.report_error(u'unable to extract video thumbnail')
  2274. return
  2275. video_thumbnail = mobj.group(0)
  2276. info = {
  2277. 'id': video_id,
  2278. 'url': video_url,
  2279. 'uploader': None,
  2280. 'upload_date': None,
  2281. 'title': video_title,
  2282. 'ext': 'flv',
  2283. 'thumbnail': video_thumbnail,
  2284. 'description': None,
  2285. }
  2286. return [info]
  2287. class SoundcloudIE(InfoExtractor):
  2288. """Information extractor for soundcloud.com
  2289. To access the media, the uid of the song and a stream token
  2290. must be extracted from the page source and the script must make
  2291. a request to media.soundcloud.com/crossdomain.xml. Then
  2292. the media can be grabbed by requesting from an url composed
  2293. of the stream token and uid
  2294. """
  2295. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2296. IE_NAME = u'soundcloud'
  2297. def __init__(self, downloader=None):
  2298. InfoExtractor.__init__(self, downloader)
  2299. def report_resolve(self, video_id):
  2300. """Report information extraction."""
  2301. self._downloader.to_screen(u'[%s] %s: Resolving id' % (self.IE_NAME, video_id))
  2302. def report_extraction(self, video_id):
  2303. """Report information extraction."""
  2304. self._downloader.to_screen(u'[%s] %s: Retrieving stream' % (self.IE_NAME, video_id))
  2305. def _real_extract(self, url):
  2306. mobj = re.match(self._VALID_URL, url)
  2307. if mobj is None:
  2308. self._downloader.report_error(u'invalid URL: %s' % url)
  2309. return
  2310. # extract uploader (which is in the url)
  2311. uploader = mobj.group(1)
  2312. # extract simple title (uploader + slug of song title)
  2313. slug_title = mobj.group(2)
  2314. simple_title = uploader + u'-' + slug_title
  2315. self.report_resolve('%s/%s' % (uploader, slug_title))
  2316. url = 'http://soundcloud.com/%s/%s' % (uploader, slug_title)
  2317. resolv_url = 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  2318. request = compat_urllib_request.Request(resolv_url)
  2319. try:
  2320. info_json_bytes = compat_urllib_request.urlopen(request).read()
  2321. info_json = info_json_bytes.decode('utf-8')
  2322. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2323. self._downloader.report_error(u'unable to download video webpage: %s' % compat_str(err))
  2324. return
  2325. info = json.loads(info_json)
  2326. video_id = info['id']
  2327. self.report_extraction('%s/%s' % (uploader, slug_title))
  2328. streams_url = 'https://api.sndcdn.com/i1/tracks/' + str(video_id) + '/streams?client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  2329. request = compat_urllib_request.Request(streams_url)
  2330. try:
  2331. stream_json_bytes = compat_urllib_request.urlopen(request).read()
  2332. stream_json = stream_json_bytes.decode('utf-8')
  2333. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2334. self._downloader.report_error(u'unable to download stream definitions: %s' % compat_str(err))
  2335. return
  2336. streams = json.loads(stream_json)
  2337. mediaURL = streams['http_mp3_128_url']
  2338. return [{
  2339. 'id': info['id'],
  2340. 'url': mediaURL,
  2341. 'uploader': info['user']['username'],
  2342. 'upload_date': info['created_at'],
  2343. 'title': info['title'],
  2344. 'ext': u'mp3',
  2345. 'description': info['description'],
  2346. }]
  2347. class SoundcloudSetIE(InfoExtractor):
  2348. """Information extractor for soundcloud.com sets
  2349. To access the media, the uid of the song and a stream token
  2350. must be extracted from the page source and the script must make
  2351. a request to media.soundcloud.com/crossdomain.xml. Then
  2352. the media can be grabbed by requesting from an url composed
  2353. of the stream token and uid
  2354. """
  2355. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/sets/([\w\d-]+)'
  2356. IE_NAME = u'soundcloud'
  2357. def __init__(self, downloader=None):
  2358. InfoExtractor.__init__(self, downloader)
  2359. def report_resolve(self, video_id):
  2360. """Report information extraction."""
  2361. self._downloader.to_screen(u'[%s] %s: Resolving id' % (self.IE_NAME, video_id))
  2362. def report_extraction(self, video_id):
  2363. """Report information extraction."""
  2364. self._downloader.to_screen(u'[%s] %s: Retrieving stream' % (self.IE_NAME, video_id))
  2365. def _real_extract(self, url):
  2366. mobj = re.match(self._VALID_URL, url)
  2367. if mobj is None:
  2368. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2369. return
  2370. # extract uploader (which is in the url)
  2371. uploader = mobj.group(1)
  2372. # extract simple title (uploader + slug of song title)
  2373. slug_title = mobj.group(2)
  2374. simple_title = uploader + u'-' + slug_title
  2375. self.report_resolve('%s/sets/%s' % (uploader, slug_title))
  2376. url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
  2377. resolv_url = 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  2378. request = compat_urllib_request.Request(resolv_url)
  2379. try:
  2380. info_json_bytes = compat_urllib_request.urlopen(request).read()
  2381. info_json = info_json_bytes.decode('utf-8')
  2382. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2383. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2384. return
  2385. videos = []
  2386. info = json.loads(info_json)
  2387. if 'errors' in info:
  2388. for err in info['errors']:
  2389. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err['error_message']))
  2390. return
  2391. for track in info['tracks']:
  2392. video_id = track['id']
  2393. self.report_extraction('%s/sets/%s' % (uploader, slug_title))
  2394. streams_url = 'https://api.sndcdn.com/i1/tracks/' + str(video_id) + '/streams?client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  2395. request = compat_urllib_request.Request(streams_url)
  2396. try:
  2397. stream_json_bytes = compat_urllib_request.urlopen(request).read()
  2398. stream_json = stream_json_bytes.decode('utf-8')
  2399. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2400. self._downloader.trouble(u'ERROR: unable to download stream definitions: %s' % compat_str(err))
  2401. return
  2402. streams = json.loads(stream_json)
  2403. mediaURL = streams['http_mp3_128_url']
  2404. videos.append({
  2405. 'id': video_id,
  2406. 'url': mediaURL,
  2407. 'uploader': track['user']['username'],
  2408. 'upload_date': track['created_at'],
  2409. 'title': track['title'],
  2410. 'ext': u'mp3',
  2411. 'description': track['description'],
  2412. })
  2413. return videos
  2414. class InfoQIE(InfoExtractor):
  2415. """Information extractor for infoq.com"""
  2416. _VALID_URL = r'^(?:https?://)?(?:www\.)?infoq\.com/[^/]+/[^/]+$'
  2417. def report_extraction(self, video_id):
  2418. """Report information extraction."""
  2419. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2420. def _real_extract(self, url):
  2421. mobj = re.match(self._VALID_URL, url)
  2422. if mobj is None:
  2423. self._downloader.report_error(u'invalid URL: %s' % url)
  2424. return
  2425. webpage = self._download_webpage(url, video_id=url)
  2426. self.report_extraction(url)
  2427. # Extract video URL
  2428. mobj = re.search(r"jsclassref='([^']*)'", webpage)
  2429. if mobj is None:
  2430. self._downloader.report_error(u'unable to extract video url')
  2431. return
  2432. real_id = compat_urllib_parse.unquote(base64.b64decode(mobj.group(1).encode('ascii')).decode('utf-8'))
  2433. video_url = 'rtmpe://video.infoq.com/cfx/st/' + real_id
  2434. # Extract title
  2435. mobj = re.search(r'contentTitle = "(.*?)";', webpage)
  2436. if mobj is None:
  2437. self._downloader.report_error(u'unable to extract video title')
  2438. return
  2439. video_title = mobj.group(1)
  2440. # Extract description
  2441. video_description = u'No description available.'
  2442. mobj = re.search(r'<meta name="description" content="(.*)"(?:\s*/)?>', webpage)
  2443. if mobj is not None:
  2444. video_description = mobj.group(1)
  2445. video_filename = video_url.split('/')[-1]
  2446. video_id, extension = video_filename.split('.')
  2447. info = {
  2448. 'id': video_id,
  2449. 'url': video_url,
  2450. 'uploader': None,
  2451. 'upload_date': None,
  2452. 'title': video_title,
  2453. 'ext': extension, # Extension is always(?) mp4, but seems to be flv
  2454. 'thumbnail': None,
  2455. 'description': video_description,
  2456. }
  2457. return [info]
  2458. class MixcloudIE(InfoExtractor):
  2459. """Information extractor for www.mixcloud.com"""
  2460. _WORKING = False # New API, but it seems good http://www.mixcloud.com/developers/documentation/
  2461. _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2462. IE_NAME = u'mixcloud'
  2463. def __init__(self, downloader=None):
  2464. InfoExtractor.__init__(self, downloader)
  2465. def report_download_json(self, file_id):
  2466. """Report JSON download."""
  2467. self._downloader.to_screen(u'[%s] Downloading json' % self.IE_NAME)
  2468. def report_extraction(self, file_id):
  2469. """Report information extraction."""
  2470. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  2471. def get_urls(self, jsonData, fmt, bitrate='best'):
  2472. """Get urls from 'audio_formats' section in json"""
  2473. file_url = None
  2474. try:
  2475. bitrate_list = jsonData[fmt]
  2476. if bitrate is None or bitrate == 'best' or bitrate not in bitrate_list:
  2477. bitrate = max(bitrate_list) # select highest
  2478. url_list = jsonData[fmt][bitrate]
  2479. except TypeError: # we have no bitrate info.
  2480. url_list = jsonData[fmt]
  2481. return url_list
  2482. def check_urls(self, url_list):
  2483. """Returns 1st active url from list"""
  2484. for url in url_list:
  2485. try:
  2486. compat_urllib_request.urlopen(url)
  2487. return url
  2488. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2489. url = None
  2490. return None
  2491. def _print_formats(self, formats):
  2492. print('Available formats:')
  2493. for fmt in formats.keys():
  2494. for b in formats[fmt]:
  2495. try:
  2496. ext = formats[fmt][b][0]
  2497. print('%s\t%s\t[%s]' % (fmt, b, ext.split('.')[-1]))
  2498. except TypeError: # we have no bitrate info
  2499. ext = formats[fmt][0]
  2500. print('%s\t%s\t[%s]' % (fmt, '??', ext.split('.')[-1]))
  2501. break
  2502. def _real_extract(self, url):
  2503. mobj = re.match(self._VALID_URL, url)
  2504. if mobj is None:
  2505. self._downloader.report_error(u'invalid URL: %s' % url)
  2506. return
  2507. # extract uploader & filename from url
  2508. uploader = mobj.group(1).decode('utf-8')
  2509. file_id = uploader + "-" + mobj.group(2).decode('utf-8')
  2510. # construct API request
  2511. file_url = 'http://www.mixcloud.com/api/1/cloudcast/' + '/'.join(url.split('/')[-3:-1]) + '.json'
  2512. # retrieve .json file with links to files
  2513. request = compat_urllib_request.Request(file_url)
  2514. try:
  2515. self.report_download_json(file_url)
  2516. jsonData = compat_urllib_request.urlopen(request).read()
  2517. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2518. self._downloader.report_error(u'Unable to retrieve file: %s' % compat_str(err))
  2519. return
  2520. # parse JSON
  2521. json_data = json.loads(jsonData)
  2522. player_url = json_data['player_swf_url']
  2523. formats = dict(json_data['audio_formats'])
  2524. req_format = self._downloader.params.get('format', None)
  2525. bitrate = None
  2526. if self._downloader.params.get('listformats', None):
  2527. self._print_formats(formats)
  2528. return
  2529. if req_format is None or req_format == 'best':
  2530. for format_param in formats.keys():
  2531. url_list = self.get_urls(formats, format_param)
  2532. # check urls
  2533. file_url = self.check_urls(url_list)
  2534. if file_url is not None:
  2535. break # got it!
  2536. else:
  2537. if req_format not in formats:
  2538. self._downloader.report_error(u'format is not available')
  2539. return
  2540. url_list = self.get_urls(formats, req_format)
  2541. file_url = self.check_urls(url_list)
  2542. format_param = req_format
  2543. return [{
  2544. 'id': file_id.decode('utf-8'),
  2545. 'url': file_url.decode('utf-8'),
  2546. 'uploader': uploader.decode('utf-8'),
  2547. 'upload_date': None,
  2548. 'title': json_data['name'],
  2549. 'ext': file_url.split('.')[-1].decode('utf-8'),
  2550. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  2551. 'thumbnail': json_data['thumbnail_url'],
  2552. 'description': json_data['description'],
  2553. 'player_url': player_url.decode('utf-8'),
  2554. }]
  2555. class StanfordOpenClassroomIE(InfoExtractor):
  2556. """Information extractor for Stanford's Open ClassRoom"""
  2557. _VALID_URL = r'^(?:https?://)?openclassroom.stanford.edu(?P<path>/?|(/MainFolder/(?:HomePage|CoursePage|VideoPage)\.php([?]course=(?P<course>[^&]+)(&video=(?P<video>[^&]+))?(&.*)?)?))$'
  2558. IE_NAME = u'stanfordoc'
  2559. def report_download_webpage(self, objid):
  2560. """Report information extraction."""
  2561. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, objid))
  2562. def report_extraction(self, video_id):
  2563. """Report information extraction."""
  2564. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2565. def _real_extract(self, url):
  2566. mobj = re.match(self._VALID_URL, url)
  2567. if mobj is None:
  2568. raise ExtractorError(u'Invalid URL: %s' % url)
  2569. if mobj.group('course') and mobj.group('video'): # A specific video
  2570. course = mobj.group('course')
  2571. video = mobj.group('video')
  2572. info = {
  2573. 'id': course + '_' + video,
  2574. 'uploader': None,
  2575. 'upload_date': None,
  2576. }
  2577. self.report_extraction(info['id'])
  2578. baseUrl = 'http://openclassroom.stanford.edu/MainFolder/courses/' + course + '/videos/'
  2579. xmlUrl = baseUrl + video + '.xml'
  2580. try:
  2581. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  2582. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2583. self._downloader.report_error(u'unable to download video info XML: %s' % compat_str(err))
  2584. return
  2585. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2586. try:
  2587. info['title'] = mdoc.findall('./title')[0].text
  2588. info['url'] = baseUrl + mdoc.findall('./videoFile')[0].text
  2589. except IndexError:
  2590. self._downloader.report_error(u'Invalid metadata XML file')
  2591. return
  2592. info['ext'] = info['url'].rpartition('.')[2]
  2593. return [info]
  2594. elif mobj.group('course'): # A course page
  2595. course = mobj.group('course')
  2596. info = {
  2597. 'id': course,
  2598. 'type': 'playlist',
  2599. 'uploader': None,
  2600. 'upload_date': None,
  2601. }
  2602. coursepage = self._download_webpage(url, info['id'],
  2603. note='Downloading course info page',
  2604. errnote='Unable to download course info page')
  2605. m = re.search('<h1>([^<]+)</h1>', coursepage)
  2606. if m:
  2607. info['title'] = unescapeHTML(m.group(1))
  2608. else:
  2609. info['title'] = info['id']
  2610. m = re.search('<description>([^<]+)</description>', coursepage)
  2611. if m:
  2612. info['description'] = unescapeHTML(m.group(1))
  2613. links = orderedSet(re.findall('<a href="(VideoPage.php\?[^"]+)">', coursepage))
  2614. info['list'] = [
  2615. {
  2616. 'type': 'reference',
  2617. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(vpage),
  2618. }
  2619. for vpage in links]
  2620. results = []
  2621. for entry in info['list']:
  2622. assert entry['type'] == 'reference'
  2623. results += self.extract(entry['url'])
  2624. return results
  2625. else: # Root page
  2626. info = {
  2627. 'id': 'Stanford OpenClassroom',
  2628. 'type': 'playlist',
  2629. 'uploader': None,
  2630. 'upload_date': None,
  2631. }
  2632. self.report_download_webpage(info['id'])
  2633. rootURL = 'http://openclassroom.stanford.edu/MainFolder/HomePage.php'
  2634. try:
  2635. rootpage = compat_urllib_request.urlopen(rootURL).read()
  2636. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2637. self._downloader.report_error(u'unable to download course info page: ' + compat_str(err))
  2638. return
  2639. info['title'] = info['id']
  2640. links = orderedSet(re.findall('<a href="(CoursePage.php\?[^"]+)">', rootpage))
  2641. info['list'] = [
  2642. {
  2643. 'type': 'reference',
  2644. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(cpage),
  2645. }
  2646. for cpage in links]
  2647. results = []
  2648. for entry in info['list']:
  2649. assert entry['type'] == 'reference'
  2650. results += self.extract(entry['url'])
  2651. return results
  2652. class MTVIE(InfoExtractor):
  2653. """Information extractor for MTV.com"""
  2654. _VALID_URL = r'^(?P<proto>https?://)?(?:www\.)?mtv\.com/videos/[^/]+/(?P<videoid>[0-9]+)/[^/]+$'
  2655. IE_NAME = u'mtv'
  2656. def report_extraction(self, video_id):
  2657. """Report information extraction."""
  2658. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2659. def _real_extract(self, url):
  2660. mobj = re.match(self._VALID_URL, url)
  2661. if mobj is None:
  2662. self._downloader.report_error(u'invalid URL: %s' % url)
  2663. return
  2664. if not mobj.group('proto'):
  2665. url = 'http://' + url
  2666. video_id = mobj.group('videoid')
  2667. webpage = self._download_webpage(url, video_id)
  2668. mobj = re.search(r'<meta name="mtv_vt" content="([^"]+)"/>', webpage)
  2669. if mobj is None:
  2670. self._downloader.report_error(u'unable to extract song name')
  2671. return
  2672. song_name = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2673. mobj = re.search(r'<meta name="mtv_an" content="([^"]+)"/>', webpage)
  2674. if mobj is None:
  2675. self._downloader.report_error(u'unable to extract performer')
  2676. return
  2677. performer = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2678. video_title = performer + ' - ' + song_name
  2679. mobj = re.search(r'<meta name="mtvn_uri" content="([^"]+)"/>', webpage)
  2680. if mobj is None:
  2681. self._downloader.report_error(u'unable to mtvn_uri')
  2682. return
  2683. mtvn_uri = mobj.group(1)
  2684. mobj = re.search(r'MTVN.Player.defaultPlaylistId = ([0-9]+);', webpage)
  2685. if mobj is None:
  2686. self._downloader.report_error(u'unable to extract content id')
  2687. return
  2688. content_id = mobj.group(1)
  2689. 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
  2690. self.report_extraction(video_id)
  2691. request = compat_urllib_request.Request(videogen_url)
  2692. try:
  2693. metadataXml = compat_urllib_request.urlopen(request).read()
  2694. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2695. self._downloader.report_error(u'unable to download video metadata: %s' % compat_str(err))
  2696. return
  2697. mdoc = xml.etree.ElementTree.fromstring(metadataXml)
  2698. renditions = mdoc.findall('.//rendition')
  2699. # For now, always pick the highest quality.
  2700. rendition = renditions[-1]
  2701. try:
  2702. _,_,ext = rendition.attrib['type'].partition('/')
  2703. format = ext + '-' + rendition.attrib['width'] + 'x' + rendition.attrib['height'] + '_' + rendition.attrib['bitrate']
  2704. video_url = rendition.find('./src').text
  2705. except KeyError:
  2706. self._downloader.trouble('Invalid rendition field.')
  2707. return
  2708. info = {
  2709. 'id': video_id,
  2710. 'url': video_url,
  2711. 'uploader': performer,
  2712. 'upload_date': None,
  2713. 'title': video_title,
  2714. 'ext': ext,
  2715. 'format': format,
  2716. }
  2717. return [info]
  2718. class YoukuIE(InfoExtractor):
  2719. _VALID_URL = r'(?:http://)?v\.youku\.com/v_show/id_(?P<ID>[A-Za-z0-9]+)\.html'
  2720. def report_download_webpage(self, file_id):
  2721. """Report webpage download."""
  2722. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, file_id))
  2723. def report_extraction(self, file_id):
  2724. """Report information extraction."""
  2725. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  2726. def _gen_sid(self):
  2727. nowTime = int(time.time() * 1000)
  2728. random1 = random.randint(1000,1998)
  2729. random2 = random.randint(1000,9999)
  2730. return "%d%d%d" %(nowTime,random1,random2)
  2731. def _get_file_ID_mix_string(self, seed):
  2732. mixed = []
  2733. source = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\:._-1234567890")
  2734. seed = float(seed)
  2735. for i in range(len(source)):
  2736. seed = (seed * 211 + 30031 ) % 65536
  2737. index = math.floor(seed / 65536 * len(source) )
  2738. mixed.append(source[int(index)])
  2739. source.remove(source[int(index)])
  2740. #return ''.join(mixed)
  2741. return mixed
  2742. def _get_file_id(self, fileId, seed):
  2743. mixed = self._get_file_ID_mix_string(seed)
  2744. ids = fileId.split('*')
  2745. realId = []
  2746. for ch in ids:
  2747. if ch:
  2748. realId.append(mixed[int(ch)])
  2749. return ''.join(realId)
  2750. def _real_extract(self, url):
  2751. mobj = re.match(self._VALID_URL, url)
  2752. if mobj is None:
  2753. self._downloader.report_error(u'invalid URL: %s' % url)
  2754. return
  2755. video_id = mobj.group('ID')
  2756. info_url = 'http://v.youku.com/player/getPlayList/VideoIDS/' + video_id
  2757. request = compat_urllib_request.Request(info_url, None, std_headers)
  2758. try:
  2759. self.report_download_webpage(video_id)
  2760. jsondata = compat_urllib_request.urlopen(request).read()
  2761. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2762. self._downloader.report_error(u'Unable to retrieve video webpage: %s' % compat_str(err))
  2763. return
  2764. self.report_extraction(video_id)
  2765. try:
  2766. jsonstr = jsondata.decode('utf-8')
  2767. config = json.loads(jsonstr)
  2768. video_title = config['data'][0]['title']
  2769. seed = config['data'][0]['seed']
  2770. format = self._downloader.params.get('format', None)
  2771. supported_format = list(config['data'][0]['streamfileids'].keys())
  2772. if format is None or format == 'best':
  2773. if 'hd2' in supported_format:
  2774. format = 'hd2'
  2775. else:
  2776. format = 'flv'
  2777. ext = u'flv'
  2778. elif format == 'worst':
  2779. format = 'mp4'
  2780. ext = u'mp4'
  2781. else:
  2782. format = 'flv'
  2783. ext = u'flv'
  2784. fileid = config['data'][0]['streamfileids'][format]
  2785. keys = [s['k'] for s in config['data'][0]['segs'][format]]
  2786. except (UnicodeDecodeError, ValueError, KeyError):
  2787. self._downloader.report_error(u'unable to extract info section')
  2788. return
  2789. files_info=[]
  2790. sid = self._gen_sid()
  2791. fileid = self._get_file_id(fileid, seed)
  2792. #column 8,9 of fileid represent the segment number
  2793. #fileid[7:9] should be changed
  2794. for index, key in enumerate(keys):
  2795. temp_fileid = '%s%02X%s' % (fileid[0:8], index, fileid[10:])
  2796. download_url = 'http://f.youku.com/player/getFlvPath/sid/%s_%02X/st/flv/fileid/%s?k=%s' % (sid, index, temp_fileid, key)
  2797. info = {
  2798. 'id': '%s_part%02d' % (video_id, index),
  2799. 'url': download_url,
  2800. 'uploader': None,
  2801. 'upload_date': None,
  2802. 'title': video_title,
  2803. 'ext': ext,
  2804. }
  2805. files_info.append(info)
  2806. return files_info
  2807. class XNXXIE(InfoExtractor):
  2808. """Information extractor for xnxx.com"""
  2809. _VALID_URL = r'^(?:https?://)?video\.xnxx\.com/video([0-9]+)/(.*)'
  2810. IE_NAME = u'xnxx'
  2811. VIDEO_URL_RE = r'flv_url=(.*?)&amp;'
  2812. VIDEO_TITLE_RE = r'<title>(.*?)\s+-\s+XNXX.COM'
  2813. VIDEO_THUMB_RE = r'url_bigthumb=(.*?)&amp;'
  2814. def report_webpage(self, video_id):
  2815. """Report information extraction"""
  2816. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2817. def report_extraction(self, video_id):
  2818. """Report information extraction"""
  2819. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2820. def _real_extract(self, url):
  2821. mobj = re.match(self._VALID_URL, url)
  2822. if mobj is None:
  2823. self._downloader.report_error(u'invalid URL: %s' % url)
  2824. return
  2825. video_id = mobj.group(1)
  2826. self.report_webpage(video_id)
  2827. # Get webpage content
  2828. try:
  2829. webpage_bytes = compat_urllib_request.urlopen(url).read()
  2830. webpage = webpage_bytes.decode('utf-8')
  2831. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2832. self._downloader.report_error(u'unable to download video webpage: %s' % err)
  2833. return
  2834. result = re.search(self.VIDEO_URL_RE, webpage)
  2835. if result is None:
  2836. self._downloader.report_error(u'unable to extract video url')
  2837. return
  2838. video_url = compat_urllib_parse.unquote(result.group(1))
  2839. result = re.search(self.VIDEO_TITLE_RE, webpage)
  2840. if result is None:
  2841. self._downloader.report_error(u'unable to extract video title')
  2842. return
  2843. video_title = result.group(1)
  2844. result = re.search(self.VIDEO_THUMB_RE, webpage)
  2845. if result is None:
  2846. self._downloader.report_error(u'unable to extract video thumbnail')
  2847. return
  2848. video_thumbnail = result.group(1)
  2849. return [{
  2850. 'id': video_id,
  2851. 'url': video_url,
  2852. 'uploader': None,
  2853. 'upload_date': None,
  2854. 'title': video_title,
  2855. 'ext': 'flv',
  2856. 'thumbnail': video_thumbnail,
  2857. 'description': None,
  2858. }]
  2859. class GooglePlusIE(InfoExtractor):
  2860. """Information extractor for plus.google.com."""
  2861. _VALID_URL = r'(?:https://)?plus\.google\.com/(?:[^/]+/)*?posts/(\w+)'
  2862. IE_NAME = u'plus.google'
  2863. def __init__(self, downloader=None):
  2864. InfoExtractor.__init__(self, downloader)
  2865. def report_extract_entry(self, url):
  2866. """Report downloading extry"""
  2867. self._downloader.to_screen(u'[plus.google] Downloading entry: %s' % url)
  2868. def report_date(self, upload_date):
  2869. """Report downloading extry"""
  2870. self._downloader.to_screen(u'[plus.google] Entry date: %s' % upload_date)
  2871. def report_uploader(self, uploader):
  2872. """Report downloading extry"""
  2873. self._downloader.to_screen(u'[plus.google] Uploader: %s' % uploader)
  2874. def report_title(self, video_title):
  2875. """Report downloading extry"""
  2876. self._downloader.to_screen(u'[plus.google] Title: %s' % video_title)
  2877. def report_extract_vid_page(self, video_page):
  2878. """Report information extraction."""
  2879. self._downloader.to_screen(u'[plus.google] Extracting video page: %s' % video_page)
  2880. def _real_extract(self, url):
  2881. # Extract id from URL
  2882. mobj = re.match(self._VALID_URL, url)
  2883. if mobj is None:
  2884. self._downloader.report_error(u'Invalid URL: %s' % url)
  2885. return
  2886. post_url = mobj.group(0)
  2887. video_id = mobj.group(1)
  2888. video_extension = 'flv'
  2889. # Step 1, Retrieve post webpage to extract further information
  2890. self.report_extract_entry(post_url)
  2891. request = compat_urllib_request.Request(post_url)
  2892. try:
  2893. webpage = compat_urllib_request.urlopen(request).read().decode('utf-8')
  2894. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2895. self._downloader.report_error(u'Unable to retrieve entry webpage: %s' % compat_str(err))
  2896. return
  2897. # Extract update date
  2898. upload_date = None
  2899. pattern = 'title="Timestamp">(.*?)</a>'
  2900. mobj = re.search(pattern, webpage)
  2901. if mobj:
  2902. upload_date = mobj.group(1)
  2903. # Convert timestring to a format suitable for filename
  2904. upload_date = datetime.datetime.strptime(upload_date, "%Y-%m-%d")
  2905. upload_date = upload_date.strftime('%Y%m%d')
  2906. self.report_date(upload_date)
  2907. # Extract uploader
  2908. uploader = None
  2909. pattern = r'rel\="author".*?>(.*?)</a>'
  2910. mobj = re.search(pattern, webpage)
  2911. if mobj:
  2912. uploader = mobj.group(1)
  2913. self.report_uploader(uploader)
  2914. # Extract title
  2915. # Get the first line for title
  2916. video_title = u'NA'
  2917. pattern = r'<meta name\=\"Description\" content\=\"(.*?)[\n<"]'
  2918. mobj = re.search(pattern, webpage)
  2919. if mobj:
  2920. video_title = mobj.group(1)
  2921. self.report_title(video_title)
  2922. # Step 2, Stimulate clicking the image box to launch video
  2923. pattern = '"(https\://plus\.google\.com/photos/.*?)",,"image/jpeg","video"\]'
  2924. mobj = re.search(pattern, webpage)
  2925. if mobj is None:
  2926. self._downloader.report_error(u'unable to extract video page URL')
  2927. video_page = mobj.group(1)
  2928. request = compat_urllib_request.Request(video_page)
  2929. try:
  2930. webpage = compat_urllib_request.urlopen(request).read().decode('utf-8')
  2931. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2932. self._downloader.report_error(u'Unable to retrieve video webpage: %s' % compat_str(err))
  2933. return
  2934. self.report_extract_vid_page(video_page)
  2935. # Extract video links on video page
  2936. """Extract video links of all sizes"""
  2937. pattern = '\d+,\d+,(\d+),"(http\://redirector\.googlevideo\.com.*?)"'
  2938. mobj = re.findall(pattern, webpage)
  2939. if len(mobj) == 0:
  2940. self._downloader.report_error(u'unable to extract video links')
  2941. # Sort in resolution
  2942. links = sorted(mobj)
  2943. # Choose the lowest of the sort, i.e. highest resolution
  2944. video_url = links[-1]
  2945. # Only get the url. The resolution part in the tuple has no use anymore
  2946. video_url = video_url[-1]
  2947. # Treat escaped \u0026 style hex
  2948. try:
  2949. video_url = video_url.decode("unicode_escape")
  2950. except AttributeError: # Python 3
  2951. video_url = bytes(video_url, 'ascii').decode('unicode-escape')
  2952. return [{
  2953. 'id': video_id,
  2954. 'url': video_url,
  2955. 'uploader': uploader,
  2956. 'upload_date': upload_date,
  2957. 'title': video_title,
  2958. 'ext': video_extension,
  2959. }]
  2960. class NBAIE(InfoExtractor):
  2961. _VALID_URL = r'^(?:https?://)?(?:watch\.|www\.)?nba\.com/(?:nba/)?video(/[^?]*)(\?.*)?$'
  2962. IE_NAME = u'nba'
  2963. def _real_extract(self, url):
  2964. mobj = re.match(self._VALID_URL, url)
  2965. if mobj is None:
  2966. self._downloader.report_error(u'invalid URL: %s' % url)
  2967. return
  2968. video_id = mobj.group(1)
  2969. if video_id.endswith('/index.html'):
  2970. video_id = video_id[:-len('/index.html')]
  2971. webpage = self._download_webpage(url, video_id)
  2972. video_url = u'http://ht-mobile.cdn.turner.com/nba/big' + video_id + '_nba_1280x720.mp4'
  2973. def _findProp(rexp, default=None):
  2974. m = re.search(rexp, webpage)
  2975. if m:
  2976. return unescapeHTML(m.group(1))
  2977. else:
  2978. return default
  2979. shortened_video_id = video_id.rpartition('/')[2]
  2980. title = _findProp(r'<meta property="og:title" content="(.*?)"', shortened_video_id).replace('NBA.com: ', '')
  2981. info = {
  2982. 'id': shortened_video_id,
  2983. 'url': video_url,
  2984. 'ext': 'mp4',
  2985. 'title': title,
  2986. 'uploader_date': _findProp(r'<b>Date:</b> (.*?)</div>'),
  2987. 'description': _findProp(r'<div class="description">(.*?)</h1>'),
  2988. }
  2989. return [info]
  2990. class JustinTVIE(InfoExtractor):
  2991. """Information extractor for justin.tv and twitch.tv"""
  2992. # TODO: One broadcast may be split into multiple videos. The key
  2993. # 'broadcast_id' is the same for all parts, and 'broadcast_part'
  2994. # starts at 1 and increases. Can we treat all parts as one video?
  2995. _VALID_URL = r"""(?x)^(?:http://)?(?:www\.)?(?:twitch|justin)\.tv/
  2996. ([^/]+)(?:/b/([^/]+))?/?(?:\#.*)?$"""
  2997. _JUSTIN_PAGE_LIMIT = 100
  2998. IE_NAME = u'justin.tv'
  2999. def report_extraction(self, file_id):
  3000. """Report information extraction."""
  3001. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  3002. def report_download_page(self, channel, offset):
  3003. """Report attempt to download a single page of videos."""
  3004. self._downloader.to_screen(u'[%s] %s: Downloading video information from %d to %d' %
  3005. (self.IE_NAME, channel, offset, offset + self._JUSTIN_PAGE_LIMIT))
  3006. # Return count of items, list of *valid* items
  3007. def _parse_page(self, url):
  3008. try:
  3009. urlh = compat_urllib_request.urlopen(url)
  3010. webpage_bytes = urlh.read()
  3011. webpage = webpage_bytes.decode('utf-8', 'ignore')
  3012. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  3013. self._downloader.report_error(u'unable to download video info JSON: %s' % compat_str(err))
  3014. return
  3015. response = json.loads(webpage)
  3016. if type(response) != list:
  3017. error_text = response.get('error', 'unknown error')
  3018. self._downloader.report_error(u'Justin.tv API: %s' % error_text)
  3019. return
  3020. info = []
  3021. for clip in response:
  3022. video_url = clip['video_file_url']
  3023. if video_url:
  3024. video_extension = os.path.splitext(video_url)[1][1:]
  3025. video_date = re.sub('-', '', clip['start_time'][:10])
  3026. video_uploader_id = clip.get('user_id', clip.get('channel_id'))
  3027. video_id = clip['id']
  3028. video_title = clip.get('title', video_id)
  3029. info.append({
  3030. 'id': video_id,
  3031. 'url': video_url,
  3032. 'title': video_title,
  3033. 'uploader': clip.get('channel_name', video_uploader_id),
  3034. 'uploader_id': video_uploader_id,
  3035. 'upload_date': video_date,
  3036. 'ext': video_extension,
  3037. })
  3038. return (len(response), info)
  3039. def _real_extract(self, url):
  3040. mobj = re.match(self._VALID_URL, url)
  3041. if mobj is None:
  3042. self._downloader.report_error(u'invalid URL: %s' % url)
  3043. return
  3044. api = 'http://api.justin.tv'
  3045. video_id = mobj.group(mobj.lastindex)
  3046. paged = False
  3047. if mobj.lastindex == 1:
  3048. paged = True
  3049. api += '/channel/archives/%s.json'
  3050. else:
  3051. api += '/broadcast/by_archive/%s.json'
  3052. api = api % (video_id,)
  3053. self.report_extraction(video_id)
  3054. info = []
  3055. offset = 0
  3056. limit = self._JUSTIN_PAGE_LIMIT
  3057. while True:
  3058. if paged:
  3059. self.report_download_page(video_id, offset)
  3060. page_url = api + ('?offset=%d&limit=%d' % (offset, limit))
  3061. page_count, page_info = self._parse_page(page_url)
  3062. info.extend(page_info)
  3063. if not paged or page_count != limit:
  3064. break
  3065. offset += limit
  3066. return info
  3067. class FunnyOrDieIE(InfoExtractor):
  3068. _VALID_URL = r'^(?:https?://)?(?:www\.)?funnyordie\.com/videos/(?P<id>[0-9a-f]+)/.*$'
  3069. def _real_extract(self, url):
  3070. mobj = re.match(self._VALID_URL, url)
  3071. if mobj is None:
  3072. self._downloader.report_error(u'invalid URL: %s' % url)
  3073. return
  3074. video_id = mobj.group('id')
  3075. webpage = self._download_webpage(url, video_id)
  3076. m = re.search(r'<video[^>]*>\s*<source[^>]*>\s*<source src="(?P<url>[^"]+)"', webpage, re.DOTALL)
  3077. if not m:
  3078. self._downloader.report_error(u'unable to find video information')
  3079. video_url = unescapeHTML(m.group('url'))
  3080. m = re.search(r"<h1 class='player_page_h1'.*?>(?P<title>.*?)</h1>", webpage, flags=re.DOTALL)
  3081. if not m:
  3082. self._downloader.trouble(u'Cannot find video title')
  3083. title = clean_html(m.group('title'))
  3084. m = re.search(r'<meta property="og:description" content="(?P<desc>.*?)"', webpage)
  3085. if m:
  3086. desc = unescapeHTML(m.group('desc'))
  3087. else:
  3088. desc = None
  3089. info = {
  3090. 'id': video_id,
  3091. 'url': video_url,
  3092. 'ext': 'mp4',
  3093. 'title': title,
  3094. 'description': desc,
  3095. }
  3096. return [info]
  3097. class SteamIE(InfoExtractor):
  3098. _VALID_URL = r"""http://store.steampowered.com/
  3099. (?P<urltype>video|app)/ #If the page is only for videos or for a game
  3100. (?P<gameID>\d+)/?
  3101. (?P<videoID>\d*)(?P<extra>\??) #For urltype == video we sometimes get the videoID
  3102. """
  3103. @classmethod
  3104. def suitable(cls, url):
  3105. """Receives a URL and returns True if suitable for this IE."""
  3106. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  3107. def _real_extract(self, url):
  3108. m = re.match(self._VALID_URL, url, re.VERBOSE)
  3109. urlRE = r"'movie_(?P<videoID>\d+)': \{\s*FILENAME: \"(?P<videoURL>[\w:/\.\?=]+)\"(,\s*MOVIE_NAME: \"(?P<videoName>[\w:/\.\?=\+-]+)\")?\s*\},"
  3110. gameID = m.group('gameID')
  3111. videourl = 'http://store.steampowered.com/video/%s/' % gameID
  3112. webpage = self._download_webpage(videourl, gameID)
  3113. mweb = re.finditer(urlRE, webpage)
  3114. namesRE = r'<span class="title">(?P<videoName>.+?)</span>'
  3115. titles = re.finditer(namesRE, webpage)
  3116. thumbsRE = r'<img class="movie_thumb" src="(?P<thumbnail>.+?)">'
  3117. thumbs = re.finditer(thumbsRE, webpage)
  3118. videos = []
  3119. for vid,vtitle,thumb in zip(mweb,titles,thumbs):
  3120. video_id = vid.group('videoID')
  3121. title = vtitle.group('videoName')
  3122. video_url = vid.group('videoURL')
  3123. video_thumb = thumb.group('thumbnail')
  3124. if not video_url:
  3125. self._downloader.report_error(u'Cannot find video url for %s' % video_id)
  3126. info = {
  3127. 'id':video_id,
  3128. 'url':video_url,
  3129. 'ext': 'flv',
  3130. 'title': unescapeHTML(title),
  3131. 'thumbnail': video_thumb
  3132. }
  3133. videos.append(info)
  3134. return videos
  3135. class UstreamIE(InfoExtractor):
  3136. _VALID_URL = r'https?://www\.ustream\.tv/recorded/(?P<videoID>\d+)'
  3137. IE_NAME = u'ustream'
  3138. def _real_extract(self, url):
  3139. m = re.match(self._VALID_URL, url)
  3140. video_id = m.group('videoID')
  3141. video_url = u'http://tcdn.ustream.tv/video/%s' % video_id
  3142. webpage = self._download_webpage(url, video_id)
  3143. m = re.search(r'data-title="(?P<title>.+)"',webpage)
  3144. title = m.group('title')
  3145. m = re.search(r'<a class="state" data-content-type="channel" data-content-id="(?P<uploader>\d+)"',webpage)
  3146. uploader = m.group('uploader')
  3147. info = {
  3148. 'id':video_id,
  3149. 'url':video_url,
  3150. 'ext': 'flv',
  3151. 'title': title,
  3152. 'uploader': uploader
  3153. }
  3154. return [info]
  3155. class WorldStarHipHopIE(InfoExtractor):
  3156. _VALID_URL = r'http://(?:www|m)\.worldstar(?:candy|hiphop)\.com/videos/video\.php\?v=(?P<id>.*)'
  3157. IE_NAME = u'WorldStarHipHop'
  3158. def _real_extract(self, url):
  3159. _src_url = r"""(http://hw-videos.*(?:mp4|flv))"""
  3160. webpage_src = compat_urllib_request.urlopen(url).read()
  3161. webpage_src = webpage_src.decode('utf-8')
  3162. mobj = re.search(_src_url, webpage_src)
  3163. m = re.match(self._VALID_URL, url)
  3164. video_id = m.group('id')
  3165. if mobj is not None:
  3166. video_url = mobj.group()
  3167. if 'mp4' in video_url:
  3168. ext = 'mp4'
  3169. else:
  3170. ext = 'flv'
  3171. else:
  3172. self._downloader.trouble(u'ERROR: Cannot find video url for %s' % video_id)
  3173. return
  3174. _title = r"""<title>(.*)</title>"""
  3175. mobj = re.search(_title, webpage_src)
  3176. if mobj is not None:
  3177. title = mobj.group(1)
  3178. else:
  3179. title = 'World Start Hip Hop - %s' % time.ctime()
  3180. _thumbnail = r"""rel="image_src" href="(.*)" />"""
  3181. mobj = re.search(_thumbnail, webpage_src)
  3182. # Getting thumbnail and if not thumbnail sets correct title for WSHH candy video.
  3183. if mobj is not None:
  3184. thumbnail = mobj.group(1)
  3185. else:
  3186. _title = r"""candytitles.*>(.*)</span>"""
  3187. mobj = re.search(_title, webpage_src)
  3188. if mobj is not None:
  3189. title = mobj.group(1)
  3190. thumbnail = None
  3191. results = [{
  3192. 'id': video_id,
  3193. 'url' : video_url,
  3194. 'title' : title,
  3195. 'thumbnail' : thumbnail,
  3196. 'ext' : ext,
  3197. }]
  3198. return results
  3199. class RBMARadioIE(InfoExtractor):
  3200. _VALID_URL = r'https?://(?:www\.)?rbmaradio\.com/shows/(?P<videoID>[^/]+)$'
  3201. def _real_extract(self, url):
  3202. m = re.match(self._VALID_URL, url)
  3203. video_id = m.group('videoID')
  3204. webpage = self._download_webpage(url, video_id)
  3205. m = re.search(r'<script>window.gon = {.*?};gon\.show=(.+?);</script>', webpage)
  3206. if not m:
  3207. raise ExtractorError(u'Cannot find metadata')
  3208. json_data = m.group(1)
  3209. try:
  3210. data = json.loads(json_data)
  3211. except ValueError as e:
  3212. raise ExtractorError(u'Invalid JSON: ' + str(e))
  3213. video_url = data['akamai_url'] + '&cbr=256'
  3214. url_parts = compat_urllib_parse_urlparse(video_url)
  3215. video_ext = url_parts.path.rpartition('.')[2]
  3216. info = {
  3217. 'id': video_id,
  3218. 'url': video_url,
  3219. 'ext': video_ext,
  3220. 'title': data['title'],
  3221. 'description': data.get('teaser_text'),
  3222. 'location': data.get('country_of_origin'),
  3223. 'uploader': data.get('host', {}).get('name'),
  3224. 'uploader_id': data.get('host', {}).get('slug'),
  3225. 'thumbnail': data.get('image', {}).get('large_url_2x'),
  3226. 'duration': data.get('duration'),
  3227. }
  3228. return [info]
  3229. class YouPornIE(InfoExtractor):
  3230. """Information extractor for youporn.com."""
  3231. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youporn\.com/watch/(?P<videoid>[0-9]+)/(?P<title>[^/]+)'
  3232. def _print_formats(self, formats):
  3233. """Print all available formats"""
  3234. print(u'Available formats:')
  3235. print(u'ext\t\tformat')
  3236. print(u'---------------------------------')
  3237. for format in formats:
  3238. print(u'%s\t\t%s' % (format['ext'], format['format']))
  3239. def _specific(self, req_format, formats):
  3240. for x in formats:
  3241. if(x["format"]==req_format):
  3242. return x
  3243. return None
  3244. def _real_extract(self, url):
  3245. mobj = re.match(self._VALID_URL, url)
  3246. if mobj is None:
  3247. self._downloader.report_error(u'invalid URL: %s' % url)
  3248. return
  3249. video_id = mobj.group('videoid')
  3250. req = compat_urllib_request.Request(url)
  3251. req.add_header('Cookie', 'age_verified=1')
  3252. webpage = self._download_webpage(req, video_id)
  3253. # Get the video title
  3254. result = re.search(r'<h1.*?>(?P<title>.*)</h1>', webpage)
  3255. if result is None:
  3256. raise ExtractorError(u'Unable to extract video title')
  3257. video_title = result.group('title').strip()
  3258. # Get the video date
  3259. result = re.search(r'Date:</label>(?P<date>.*) </li>', webpage)
  3260. if result is None:
  3261. self._downloader.report_warning(u'unable to extract video date')
  3262. upload_date = None
  3263. else:
  3264. upload_date = result.group('date').strip()
  3265. # Get the video uploader
  3266. result = re.search(r'Submitted:</label>(?P<uploader>.*)</li>', webpage)
  3267. if result is None:
  3268. self._downloader.report_warning(u'unable to extract uploader')
  3269. video_uploader = None
  3270. else:
  3271. video_uploader = result.group('uploader').strip()
  3272. video_uploader = clean_html( video_uploader )
  3273. # Get all of the formats available
  3274. DOWNLOAD_LIST_RE = r'(?s)<ul class="downloadList">(?P<download_list>.*?)</ul>'
  3275. result = re.search(DOWNLOAD_LIST_RE, webpage)
  3276. if result is None:
  3277. raise ExtractorError(u'Unable to extract download list')
  3278. download_list_html = result.group('download_list').strip()
  3279. # Get all of the links from the page
  3280. LINK_RE = r'(?s)<a href="(?P<url>[^"]+)">'
  3281. links = re.findall(LINK_RE, download_list_html)
  3282. if(len(links) == 0):
  3283. raise ExtractorError(u'ERROR: no known formats available for video')
  3284. self._downloader.to_screen(u'[youporn] Links found: %d' % len(links))
  3285. formats = []
  3286. for link in links:
  3287. # A link looks like this:
  3288. # 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
  3289. # A path looks like this:
  3290. # /201210/31/8004515/480p_370k_8004515/YouPorn%20-%20Nubile%20Films%20The%20Pillow%20Fight.mp4
  3291. video_url = unescapeHTML( link )
  3292. path = compat_urllib_parse_urlparse( video_url ).path
  3293. extension = os.path.splitext( path )[1][1:]
  3294. format = path.split('/')[4].split('_')[:2]
  3295. size = format[0]
  3296. bitrate = format[1]
  3297. format = "-".join( format )
  3298. title = u'%s-%s-%s' % (video_title, size, bitrate)
  3299. formats.append({
  3300. 'id': video_id,
  3301. 'url': video_url,
  3302. 'uploader': video_uploader,
  3303. 'upload_date': upload_date,
  3304. 'title': title,
  3305. 'ext': extension,
  3306. 'format': format,
  3307. 'thumbnail': None,
  3308. 'description': None,
  3309. 'player_url': None
  3310. })
  3311. if self._downloader.params.get('listformats', None):
  3312. self._print_formats(formats)
  3313. return
  3314. req_format = self._downloader.params.get('format', None)
  3315. self._downloader.to_screen(u'[youporn] Format: %s' % req_format)
  3316. if req_format is None or req_format == 'best':
  3317. return [formats[0]]
  3318. elif req_format == 'worst':
  3319. return [formats[-1]]
  3320. elif req_format in ('-1', 'all'):
  3321. return formats
  3322. else:
  3323. format = self._specific( req_format, formats )
  3324. if result is None:
  3325. self._downloader.report_error(u'requested format not available')
  3326. return
  3327. return [format]
  3328. class PornotubeIE(InfoExtractor):
  3329. """Information extractor for pornotube.com."""
  3330. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?pornotube\.com(/c/(?P<channel>[0-9]+))?(/m/(?P<videoid>[0-9]+))(/(?P<title>.+))$'
  3331. def _real_extract(self, url):
  3332. mobj = re.match(self._VALID_URL, url)
  3333. if mobj is None:
  3334. self._downloader.report_error(u'invalid URL: %s' % url)
  3335. return
  3336. video_id = mobj.group('videoid')
  3337. video_title = mobj.group('title')
  3338. # Get webpage content
  3339. webpage = self._download_webpage(url, video_id)
  3340. # Get the video URL
  3341. VIDEO_URL_RE = r'url: "(?P<url>http://video[0-9].pornotube.com/.+\.flv)",'
  3342. result = re.search(VIDEO_URL_RE, webpage)
  3343. if result is None:
  3344. self._downloader.report_error(u'unable to extract video url')
  3345. return
  3346. video_url = compat_urllib_parse.unquote(result.group('url'))
  3347. #Get the uploaded date
  3348. VIDEO_UPLOADED_RE = r'<div class="video_added_by">Added (?P<date>[0-9\/]+) by'
  3349. result = re.search(VIDEO_UPLOADED_RE, webpage)
  3350. if result is None:
  3351. self._downloader.report_error(u'unable to extract video title')
  3352. return
  3353. upload_date = result.group('date')
  3354. info = {'id': video_id,
  3355. 'url': video_url,
  3356. 'uploader': None,
  3357. 'upload_date': upload_date,
  3358. 'title': video_title,
  3359. 'ext': 'flv',
  3360. 'format': 'flv'}
  3361. return [info]
  3362. class YouJizzIE(InfoExtractor):
  3363. """Information extractor for youjizz.com."""
  3364. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youjizz\.com/videos/(?P<videoid>[^.]+).html$'
  3365. def _real_extract(self, url):
  3366. mobj = re.match(self._VALID_URL, url)
  3367. if mobj is None:
  3368. self._downloader.report_error(u'invalid URL: %s' % url)
  3369. return
  3370. video_id = mobj.group('videoid')
  3371. # Get webpage content
  3372. webpage = self._download_webpage(url, video_id)
  3373. # Get the video title
  3374. result = re.search(r'<title>(?P<title>.*)</title>', webpage)
  3375. if result is None:
  3376. raise ExtractorError(u'ERROR: unable to extract video title')
  3377. video_title = result.group('title').strip()
  3378. # Get the embed page
  3379. result = re.search(r'https?://www.youjizz.com/videos/embed/(?P<videoid>[0-9]+)', webpage)
  3380. if result is None:
  3381. raise ExtractorError(u'ERROR: unable to extract embed page')
  3382. embed_page_url = result.group(0).strip()
  3383. video_id = result.group('videoid')
  3384. webpage = self._download_webpage(embed_page_url, video_id)
  3385. # Get the video URL
  3386. result = re.search(r'so.addVariable\("file",encodeURIComponent\("(?P<source>[^"]+)"\)\);', webpage)
  3387. if result is None:
  3388. raise ExtractorError(u'ERROR: unable to extract video url')
  3389. video_url = result.group('source')
  3390. info = {'id': video_id,
  3391. 'url': video_url,
  3392. 'title': video_title,
  3393. 'ext': 'flv',
  3394. 'format': 'flv',
  3395. 'player_url': embed_page_url}
  3396. return [info]
  3397. class EightTracksIE(InfoExtractor):
  3398. IE_NAME = '8tracks'
  3399. _VALID_URL = r'https?://8tracks.com/(?P<user>[^/]+)/(?P<id>[^/#]+)(?:#.*)?$'
  3400. def _real_extract(self, url):
  3401. mobj = re.match(self._VALID_URL, url)
  3402. if mobj is None:
  3403. raise ExtractorError(u'Invalid URL: %s' % url)
  3404. playlist_id = mobj.group('id')
  3405. webpage = self._download_webpage(url, playlist_id)
  3406. m = re.search(r"PAGE.mix = (.*?);\n", webpage, flags=re.DOTALL)
  3407. if not m:
  3408. raise ExtractorError(u'Cannot find trax information')
  3409. json_like = m.group(1)
  3410. data = json.loads(json_like)
  3411. session = str(random.randint(0, 1000000000))
  3412. mix_id = data['id']
  3413. track_count = data['tracks_count']
  3414. first_url = 'http://8tracks.com/sets/%s/play?player=sm&mix_id=%s&format=jsonh' % (session, mix_id)
  3415. next_url = first_url
  3416. res = []
  3417. for i in itertools.count():
  3418. api_json = self._download_webpage(next_url, playlist_id,
  3419. note=u'Downloading song information %s/%s' % (str(i+1), track_count),
  3420. errnote=u'Failed to download song information')
  3421. api_data = json.loads(api_json)
  3422. track_data = api_data[u'set']['track']
  3423. info = {
  3424. 'id': track_data['id'],
  3425. 'url': track_data['track_file_stream_url'],
  3426. 'title': track_data['performer'] + u' - ' + track_data['name'],
  3427. 'raw_title': track_data['name'],
  3428. 'uploader_id': data['user']['login'],
  3429. 'ext': 'm4a',
  3430. }
  3431. res.append(info)
  3432. if api_data['set']['at_last_track']:
  3433. break
  3434. next_url = 'http://8tracks.com/sets/%s/next?player=sm&mix_id=%s&format=jsonh&track_id=%s' % (session, mix_id, track_data['id'])
  3435. return res
  3436. class KeekIE(InfoExtractor):
  3437. _VALID_URL = r'http://(?:www\.)?keek\.com/(?:!|\w+/keeks/)(?P<videoID>\w+)'
  3438. IE_NAME = u'keek'
  3439. def _real_extract(self, url):
  3440. m = re.match(self._VALID_URL, url)
  3441. video_id = m.group('videoID')
  3442. video_url = u'http://cdn.keek.com/keek/video/%s' % video_id
  3443. thumbnail = u'http://cdn.keek.com/keek/thumbnail/%s/w100/h75' % video_id
  3444. webpage = self._download_webpage(url, video_id)
  3445. m = re.search(r'<meta property="og:title" content="(?P<title>.+)"', webpage)
  3446. title = unescapeHTML(m.group('title'))
  3447. m = re.search(r'<div class="user-name-and-bio">[\S\s]+?<h2>(?P<uploader>.+?)</h2>', webpage)
  3448. uploader = clean_html(m.group('uploader'))
  3449. info = {
  3450. 'id': video_id,
  3451. 'url': video_url,
  3452. 'ext': 'mp4',
  3453. 'title': title,
  3454. 'thumbnail': thumbnail,
  3455. 'uploader': uploader
  3456. }
  3457. return [info]
  3458. class TEDIE(InfoExtractor):
  3459. _VALID_URL=r'''http://www.ted.com/
  3460. (
  3461. ((?P<type_playlist>playlists)/(?P<playlist_id>\d+)) # We have a playlist
  3462. |
  3463. ((?P<type_talk>talks)) # We have a simple talk
  3464. )
  3465. /(?P<name>\w+) # Here goes the name and then ".html"
  3466. '''
  3467. @classmethod
  3468. def suitable(cls, url):
  3469. """Receives a URL and returns True if suitable for this IE."""
  3470. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  3471. def _real_extract(self, url):
  3472. m=re.match(self._VALID_URL, url, re.VERBOSE)
  3473. if m.group('type_talk'):
  3474. return [self._talk_info(url)]
  3475. else :
  3476. playlist_id=m.group('playlist_id')
  3477. name=m.group('name')
  3478. self._downloader.to_screen(u'[%s] Getting info of playlist %s: "%s"' % (self.IE_NAME,playlist_id,name))
  3479. return self._playlist_videos_info(url,name,playlist_id)
  3480. def _talk_video_link(self,mediaSlug):
  3481. '''Returns the video link for that mediaSlug'''
  3482. return 'http://download.ted.com/talks/%s.mp4' % mediaSlug
  3483. def _playlist_videos_info(self,url,name,playlist_id=0):
  3484. '''Returns the videos of the playlist'''
  3485. video_RE=r'''
  3486. <li\ id="talk_(\d+)"([.\s]*?)data-id="(?P<video_id>\d+)"
  3487. ([.\s]*?)data-playlist_item_id="(\d+)"
  3488. ([.\s]*?)data-mediaslug="(?P<mediaSlug>.+?)"
  3489. '''
  3490. video_name_RE=r'<p\ class="talk-title"><a href="(?P<talk_url>/talks/(.+).html)">(?P<fullname>.+?)</a></p>'
  3491. webpage=self._download_webpage(url, playlist_id, 'Downloading playlist webpage')
  3492. m_videos=re.finditer(video_RE,webpage,re.VERBOSE)
  3493. m_names=re.finditer(video_name_RE,webpage)
  3494. info=[]
  3495. for m_video, m_name in zip(m_videos,m_names):
  3496. video_id=m_video.group('video_id')
  3497. talk_url='http://www.ted.com%s' % m_name.group('talk_url')
  3498. info.append(self._talk_info(talk_url,video_id))
  3499. return info
  3500. def _talk_info(self, url, video_id=0):
  3501. """Return the video for the talk in the url"""
  3502. m=re.match(self._VALID_URL, url,re.VERBOSE)
  3503. videoName=m.group('name')
  3504. webpage=self._download_webpage(url, video_id, 'Downloading \"%s\" page' % videoName)
  3505. # If the url includes the language we get the title translated
  3506. title_RE=r'<span id="altHeadline" >(?P<title>.*)</span>'
  3507. title=re.search(title_RE, webpage).group('title')
  3508. info_RE=r'''<script\ type="text/javascript">var\ talkDetails\ =(.*?)
  3509. "id":(?P<videoID>[\d]+).*?
  3510. "mediaSlug":"(?P<mediaSlug>[\w\d]+?)"'''
  3511. thumb_RE=r'</span>[\s.]*</div>[\s.]*<img src="(?P<thumbnail>.*?)"'
  3512. thumb_match=re.search(thumb_RE,webpage)
  3513. info_match=re.search(info_RE,webpage,re.VERBOSE)
  3514. video_id=info_match.group('videoID')
  3515. mediaSlug=info_match.group('mediaSlug')
  3516. video_url=self._talk_video_link(mediaSlug)
  3517. info = {
  3518. 'id': video_id,
  3519. 'url': video_url,
  3520. 'ext': 'mp4',
  3521. 'title': title,
  3522. 'thumbnail': thumb_match.group('thumbnail')
  3523. }
  3524. return info
  3525. class MySpassIE(InfoExtractor):
  3526. _VALID_URL = r'http://www.myspass.de/.*'
  3527. def _real_extract(self, url):
  3528. META_DATA_URL_TEMPLATE = 'http://www.myspass.de/myspass/includes/apps/video/getvideometadataxml.php?id=%s'
  3529. # video id is the last path element of the URL
  3530. # usually there is a trailing slash, so also try the second but last
  3531. url_path = compat_urllib_parse_urlparse(url).path
  3532. url_parent_path, video_id = os.path.split(url_path)
  3533. if not video_id:
  3534. _, video_id = os.path.split(url_parent_path)
  3535. # get metadata
  3536. metadata_url = META_DATA_URL_TEMPLATE % video_id
  3537. metadata_text = self._download_webpage(metadata_url, video_id)
  3538. metadata = xml.etree.ElementTree.fromstring(metadata_text.encode('utf-8'))
  3539. # extract values from metadata
  3540. url_flv_el = metadata.find('url_flv')
  3541. if url_flv_el is None:
  3542. self._downloader.report_error(u'unable to extract download url')
  3543. return
  3544. video_url = url_flv_el.text
  3545. extension = os.path.splitext(video_url)[1][1:]
  3546. title_el = metadata.find('title')
  3547. if title_el is None:
  3548. self._downloader.report_error(u'unable to extract title')
  3549. return
  3550. title = title_el.text
  3551. format_id_el = metadata.find('format_id')
  3552. if format_id_el is None:
  3553. format = ext
  3554. else:
  3555. format = format_id_el.text
  3556. description_el = metadata.find('description')
  3557. if description_el is not None:
  3558. description = description_el.text
  3559. else:
  3560. description = None
  3561. imagePreview_el = metadata.find('imagePreview')
  3562. if imagePreview_el is not None:
  3563. thumbnail = imagePreview_el.text
  3564. else:
  3565. thumbnail = None
  3566. info = {
  3567. 'id': video_id,
  3568. 'url': video_url,
  3569. 'title': title,
  3570. 'ext': extension,
  3571. 'format': format,
  3572. 'thumbnail': thumbnail,
  3573. 'description': description
  3574. }
  3575. return [info]
  3576. class SpiegelIE(InfoExtractor):
  3577. _VALID_URL = r'https?://(?:www\.)?spiegel\.de/video/[^/]*-(?P<videoID>[0-9]+)(?:\.html)?(?:#.*)?$'
  3578. def _real_extract(self, url):
  3579. m = re.match(self._VALID_URL, url)
  3580. video_id = m.group('videoID')
  3581. webpage = self._download_webpage(url, video_id)
  3582. m = re.search(r'<div class="spVideoTitle">(.*?)</div>', webpage)
  3583. if not m:
  3584. raise ExtractorError(u'Cannot find title')
  3585. video_title = unescapeHTML(m.group(1))
  3586. xml_url = u'http://video2.spiegel.de/flash/' + video_id + u'.xml'
  3587. xml_code = self._download_webpage(xml_url, video_id,
  3588. note=u'Downloading XML', errnote=u'Failed to download XML')
  3589. idoc = xml.etree.ElementTree.fromstring(xml_code)
  3590. last_type = idoc[-1]
  3591. filename = last_type.findall('./filename')[0].text
  3592. duration = float(last_type.findall('./duration')[0].text)
  3593. video_url = 'http://video2.spiegel.de/flash/' + filename
  3594. video_ext = filename.rpartition('.')[2]
  3595. info = {
  3596. 'id': video_id,
  3597. 'url': video_url,
  3598. 'ext': video_ext,
  3599. 'title': video_title,
  3600. 'duration': duration,
  3601. }
  3602. return [info]
  3603. class LiveLeakIE(InfoExtractor):
  3604. _VALID_URL = r'^(?:http?://)?(?:\w+\.)?liveleak\.com/view\?(?:.*?)i=(?P<video_id>[\w_]+)(?:.*)'
  3605. IE_NAME = u'liveleak'
  3606. def _real_extract(self, url):
  3607. mobj = re.match(self._VALID_URL, url)
  3608. if mobj is None:
  3609. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  3610. return
  3611. video_id = mobj.group('video_id')
  3612. webpage = self._download_webpage(url, video_id)
  3613. m = re.search(r'file: "(.*?)",', webpage)
  3614. if not m:
  3615. self._downloader.report_error(u'unable to find video url')
  3616. return
  3617. video_url = m.group(1)
  3618. m = re.search(r'<meta property="og:title" content="(?P<title>.*?)"', webpage)
  3619. if not m:
  3620. self._downloader.trouble(u'Cannot find video title')
  3621. title = unescapeHTML(m.group('title')).replace('LiveLeak.com -', '').strip()
  3622. m = re.search(r'<meta property="og:description" content="(?P<desc>.*?)"', webpage)
  3623. if m:
  3624. desc = unescapeHTML(m.group('desc'))
  3625. else:
  3626. desc = None
  3627. m = re.search(r'By:.*?(\w+)</a>', webpage)
  3628. if m:
  3629. uploader = clean_html(m.group(1))
  3630. else:
  3631. uploader = None
  3632. info = {
  3633. 'id': video_id,
  3634. 'url': video_url,
  3635. 'ext': 'mp4',
  3636. 'title': title,
  3637. 'description': desc,
  3638. 'uploader': uploader
  3639. }
  3640. return [info]
  3641. def gen_extractors():
  3642. """ Return a list of an instance of every supported extractor.
  3643. The order does matter; the first extractor matched is the one handling the URL.
  3644. """
  3645. return [
  3646. YoutubePlaylistIE(),
  3647. YoutubeChannelIE(),
  3648. YoutubeUserIE(),
  3649. YoutubeSearchIE(),
  3650. YoutubeIE(),
  3651. MetacafeIE(),
  3652. DailymotionIE(),
  3653. GoogleSearchIE(),
  3654. PhotobucketIE(),
  3655. YahooIE(),
  3656. YahooSearchIE(),
  3657. DepositFilesIE(),
  3658. FacebookIE(),
  3659. BlipTVUserIE(),
  3660. BlipTVIE(),
  3661. VimeoIE(),
  3662. MyVideoIE(),
  3663. ComedyCentralIE(),
  3664. EscapistIE(),
  3665. CollegeHumorIE(),
  3666. XVideosIE(),
  3667. SoundcloudSetIE(),
  3668. SoundcloudIE(),
  3669. InfoQIE(),
  3670. MixcloudIE(),
  3671. StanfordOpenClassroomIE(),
  3672. MTVIE(),
  3673. YoukuIE(),
  3674. XNXXIE(),
  3675. YouJizzIE(),
  3676. PornotubeIE(),
  3677. YouPornIE(),
  3678. GooglePlusIE(),
  3679. ArteTvIE(),
  3680. NBAIE(),
  3681. WorldStarHipHopIE(),
  3682. JustinTVIE(),
  3683. FunnyOrDieIE(),
  3684. SteamIE(),
  3685. UstreamIE(),
  3686. RBMARadioIE(),
  3687. EightTracksIE(),
  3688. KeekIE(),
  3689. TEDIE(),
  3690. MySpassIE(),
  3691. SpiegelIE(),
  3692. LiveLeakIE(),
  3693. GenericIE()
  3694. ]