InfoExtractors.py 177 KB

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