InfoExtractors.py 175 KB

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